blob: 2bf882364cc5e9f2776948f2bd97fda1eb32152a [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
Eugene Zelenko0722f082015-10-24 01:28:05 +000010#include "lldb/Host/Config.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012// C Includes
13#include <errno.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000014#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000015#ifndef LLDB_DISABLE_POSIX
Sean Callanan224f6f52012-07-19 18:07:36 +000016#include <netinet/in.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000017#include <sys/mman.h> // for mmap
Virgile Bellob2f1fb22013-08-23 12:44:05 +000018#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000020#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000021#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022
23// C++ Includes
24#include <algorithm>
25#include <map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000026#include <mutex>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027
Johnny Chen01a67862011-10-14 00:42:25 +000028#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000029#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Core/ArchSpec.h"
31#include "lldb/Core/Debugger.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000032#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000033#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000035#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Core/PluginManager.h"
37#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000038#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Core/StreamString.h"
40#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000041#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000042#include "lldb/DataFormatters/FormatManager.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000043#include "lldb/Host/FileSystem.h"
Zachary Turner39de3112014-09-09 20:54:56 +000044#include "lldb/Host/HostThread.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000045#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000046#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000047#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Host/TimeValue.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000049#include "lldb/Host/XML.h"
Greg Clayton02686b82012-10-15 22:42:16 +000050#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000051#include "lldb/Interpreter/CommandObject.h"
52#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000053#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000054#include "lldb/Interpreter/OptionValueProperties.h"
Greg Claytone034a042015-05-21 20:52:06 +000055#include "lldb/Interpreter/Options.h"
56#include "lldb/Interpreter/OptionGroupBoolean.h"
57#include "lldb/Interpreter/OptionGroupUInt64.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000058#include "lldb/Interpreter/Property.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000059#include "lldb/Symbol/ObjectFile.h"
Jason Molenda21586c82015-09-09 03:36:24 +000060#include "lldb/Target/ABI.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061#include "lldb/Target/DynamicLoader.h"
62#include "lldb/Target/Target.h"
63#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000064#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molenda705b1802014-06-13 02:37:02 +000065#include "lldb/Target/SystemRuntime.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000066#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067
Eugene Zelenko0722f082015-10-24 01:28:05 +000068// Project includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000069#include "lldb/Host/Host.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000070#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000071#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000072#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000073#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000074#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075#include "GDBRemoteRegisterContext.h"
76#include "ProcessGDBRemote.h"
77#include "ProcessGDBRemoteLog.h"
78#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000079
Tamas Berghammerdb264a62015-03-31 09:52:22 +000080#define DEBUGSERVER_BASENAME "debugserver"
81using namespace lldb;
82using namespace lldb_private;
83using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000084
Greg Claytonc1422c12012-04-09 22:46:21 +000085namespace lldb
86{
87 // Provide a function that can easily dump the packet history if we know a
88 // ProcessGDBRemote * value (which we can get from logs or from debugging).
89 // We need the function in the lldb namespace so it makes it into the final
90 // executable since the LLDB shared library only exports stuff in the lldb
91 // namespace. This allows you to attach with a debugger and call this
92 // function and get the packet history dumped to a file.
93 void
94 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
95 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +000096 StreamFile strm;
97 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
Greg Claytond451c1a2012-04-13 21:24:18 +000098 if (error.Success())
99 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +0000100 }
Eugene Zelenko0722f082015-10-24 01:28:05 +0000101}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000102
Greg Clayton7f982402013-07-15 22:54:20 +0000103namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000104
Greg Clayton7f982402013-07-15 22:54:20 +0000105 static PropertyDefinition
106 g_properties[] =
107 {
108 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000109 { "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 +0000110 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
111 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000112
Greg Clayton7f982402013-07-15 22:54:20 +0000113 enum
114 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000115 ePropertyPacketTimeout,
116 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000117 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000118
Greg Clayton7f982402013-07-15 22:54:20 +0000119 class PluginProperties : public Properties
120 {
121 public:
Ed Maste81b4c5f2016-01-04 01:43:47 +0000122
Greg Clayton7f982402013-07-15 22:54:20 +0000123 static ConstString
124 GetSettingName ()
125 {
126 return ProcessGDBRemote::GetPluginNameStatic();
127 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000128
Greg Clayton7f982402013-07-15 22:54:20 +0000129 PluginProperties() :
130 Properties ()
131 {
132 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
133 m_collection_sp->Initialize(g_properties);
134 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000135
Eugene Zelenko0722f082015-10-24 01:28:05 +0000136 virtual
137 ~PluginProperties()
138 {
139 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000140
Greg Clayton7f982402013-07-15 22:54:20 +0000141 uint64_t
142 GetPacketTimeout()
143 {
144 const uint32_t idx = ePropertyPacketTimeout;
145 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
146 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000147
148 bool
149 SetPacketTimeout(uint64_t timeout)
150 {
151 const uint32_t idx = ePropertyPacketTimeout;
152 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
153 }
154
Greg Claytonef8180a2013-10-15 00:14:28 +0000155 FileSpec
156 GetTargetDefinitionFile () const
157 {
158 const uint32_t idx = ePropertyTargetDefinitionFile;
159 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
160 }
Greg Clayton7f982402013-07-15 22:54:20 +0000161 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000162
Greg Clayton7f982402013-07-15 22:54:20 +0000163 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000164
Greg Clayton7f982402013-07-15 22:54:20 +0000165 static const ProcessKDPPropertiesSP &
166 GetGlobalPluginProperties()
167 {
168 static ProcessKDPPropertiesSP g_settings_sp;
169 if (!g_settings_sp)
170 g_settings_sp.reset (new PluginProperties ());
171 return g_settings_sp;
172 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000173
Eugene Zelenko0722f082015-10-24 01:28:05 +0000174} // anonymous namespace end
Greg Clayton7f982402013-07-15 22:54:20 +0000175
Aidan Doddsc0c83852015-05-08 09:36:31 +0000176class ProcessGDBRemote::GDBLoadedModuleInfoList
177{
178public:
Eugene Zelenko0722f082015-10-24 01:28:05 +0000179
Aidan Doddsc0c83852015-05-08 09:36:31 +0000180 class LoadedModuleInfo
181 {
182 public:
Eugene Zelenko0722f082015-10-24 01:28:05 +0000183
Aidan Doddsc0c83852015-05-08 09:36:31 +0000184 enum e_data_point
185 {
186 e_has_name = 0,
187 e_has_base ,
188 e_has_dynamic ,
189 e_has_link_map ,
190 e_num
191 };
192
193 LoadedModuleInfo ()
194 {
195 for (uint32_t i = 0; i < e_num; ++i)
196 m_has[i] = false;
Pavel Labathcb213b32015-07-22 08:12:01 +0000197 }
Aidan Doddsc0c83852015-05-08 09:36:31 +0000198
199 void set_name (const std::string & name)
200 {
201 m_name = name;
202 m_has[e_has_name] = true;
203 }
204 bool get_name (std::string & out) const
205 {
206 out = m_name;
207 return m_has[e_has_name];
208 }
209
210 void set_base (const lldb::addr_t base)
211 {
212 m_base = base;
213 m_has[e_has_base] = true;
214 }
215 bool get_base (lldb::addr_t & out) const
216 {
217 out = m_base;
218 return m_has[e_has_base];
219 }
220
Stephane Sezerc6845a02015-08-20 22:07:48 +0000221 void set_base_is_offset (bool is_offset)
222 {
223 m_base_is_offset = is_offset;
224 }
225 bool get_base_is_offset(bool & out) const
226 {
227 out = m_base_is_offset;
228 return m_has[e_has_base];
229 }
230
Aidan Doddsc0c83852015-05-08 09:36:31 +0000231 void set_link_map (const lldb::addr_t addr)
232 {
233 m_link_map = addr;
234 m_has[e_has_link_map] = true;
235 }
236 bool get_link_map (lldb::addr_t & out) const
237 {
238 out = m_link_map;
239 return m_has[e_has_link_map];
240 }
241
242 void set_dynamic (const lldb::addr_t addr)
243 {
244 m_dynamic = addr;
245 m_has[e_has_dynamic] = true;
246 }
247 bool get_dynamic (lldb::addr_t & out) const
248 {
249 out = m_dynamic;
250 return m_has[e_has_dynamic];
251 }
252
253 bool has_info (e_data_point datum)
254 {
255 assert (datum < e_num);
256 return m_has[datum];
257 }
258
259 protected:
Eugene Zelenko0722f082015-10-24 01:28:05 +0000260
Aidan Doddsc0c83852015-05-08 09:36:31 +0000261 bool m_has[e_num];
262 std::string m_name;
263 lldb::addr_t m_link_map;
264 lldb::addr_t m_base;
Stephane Sezerc6845a02015-08-20 22:07:48 +0000265 bool m_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +0000266 lldb::addr_t m_dynamic;
267 };
268
269 GDBLoadedModuleInfoList ()
270 : m_list ()
271 , m_link_map (LLDB_INVALID_ADDRESS)
272 {}
273
274 void add (const LoadedModuleInfo & mod)
275 {
276 m_list.push_back (mod);
277 }
278
279 void clear ()
280 {
281 m_list.clear ();
282 }
283
284 std::vector<LoadedModuleInfo> m_list;
285 lldb::addr_t m_link_map;
286};
287
Greg Claytonfda4fab2014-01-10 22:24:11 +0000288// TODO Randomly assigning a port is unsafe. We should get an unused
289// ephemeral port from the kernel and make sure we reserve it before passing
290// it to debugserver.
291
292#if defined (__APPLE__)
293#define LOW_PORT (IPPORT_RESERVED)
294#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
295#else
296#define LOW_PORT (1024u)
297#define HIGH_PORT (49151u)
298#endif
299
Todd Fiala013434e2014-07-09 01:29:05 +0000300#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000301static bool rand_initialized = false;
302
Greg Claytonfda4fab2014-01-10 22:24:11 +0000303static inline uint16_t
304get_random_port ()
305{
306 if (!rand_initialized)
307 {
308 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000309
Greg Claytonfda4fab2014-01-10 22:24:11 +0000310 rand_initialized = true;
311 srand(seed);
312 }
313 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
314}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000315#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000316
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000317ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318ProcessGDBRemote::GetPluginNameStatic()
319{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000320 static ConstString g_name("gdb-remote");
321 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000322}
323
324const char *
325ProcessGDBRemote::GetPluginDescriptionStatic()
326{
327 return "GDB Remote protocol based debugging plug-in.";
328}
329
330void
331ProcessGDBRemote::Terminate()
332{
333 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
334}
335
Eugene Zelenko0722f082015-10-24 01:28:05 +0000336
Greg Claytonc3776bf2012-02-09 06:16:32 +0000337lldb::ProcessSP
Zachary Turner7529df92015-09-01 20:02:29 +0000338ProcessGDBRemote::CreateInstance (lldb::TargetSP target_sp, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000339{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000340 lldb::ProcessSP process_sp;
341 if (crash_file_path == NULL)
Zachary Turner7529df92015-09-01 20:02:29 +0000342 process_sp.reset (new ProcessGDBRemote (target_sp, listener));
Greg Claytonc3776bf2012-02-09 06:16:32 +0000343 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000344}
345
346bool
Zachary Turner7529df92015-09-01 20:02:29 +0000347ProcessGDBRemote::CanDebug (lldb::TargetSP target_sp, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000348{
Greg Clayton596ed242011-10-21 21:41:45 +0000349 if (plugin_specified_by_name)
350 return true;
351
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000352 // For now we are just making sure the file exists for a given module
Zachary Turner7529df92015-09-01 20:02:29 +0000353 Module *exe_module = target_sp->GetExecutableModulePointer();
Greg Claytonaa149cb2011-08-11 02:48:45 +0000354 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000355 {
356 ObjectFile *exe_objfile = exe_module->GetObjectFile();
357 // We can't debug core files...
358 switch (exe_objfile->GetType())
359 {
360 case ObjectFile::eTypeInvalid:
361 case ObjectFile::eTypeCoreFile:
362 case ObjectFile::eTypeDebugInfo:
363 case ObjectFile::eTypeObjectFile:
364 case ObjectFile::eTypeSharedLibrary:
365 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000366 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000367 return false;
368 case ObjectFile::eTypeExecutable:
369 case ObjectFile::eTypeDynamicLinker:
370 case ObjectFile::eTypeUnknown:
371 break;
372 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000373 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000374 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000375 // However, if there is no executable module, we return true since we might be preparing to attach.
376 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377}
378
Eugene Zelenko0722f082015-10-24 01:28:05 +0000379//----------------------------------------------------------------------
380// ProcessGDBRemote constructor
381//----------------------------------------------------------------------
Zachary Turner7529df92015-09-01 20:02:29 +0000382ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp, Listener &listener) :
383 Process (target_sp, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000384 m_flags (0),
Tamas Berghammere13c2732015-02-11 10:29:30 +0000385 m_gdb_comm (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000386 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +0000387 m_last_stop_packet_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000389 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Pavel Labath50556852015-09-03 09:36:22 +0000390 m_async_listener("lldb.process.gdb-remote.async-listener"),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000391 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000392 m_thread_ids (),
Jason Molenda545304d2015-12-18 00:45:35 +0000393 m_thread_pcs (),
Greg Clayton2e309072015-07-17 23:42:28 +0000394 m_jstopinfo_sp (),
395 m_jthreadsinfo_sp (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000396 m_continue_c_tids (),
397 m_continue_C_tids (),
398 m_continue_s_tids (),
399 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000400 m_max_memory_size (0),
401 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000402 m_addr_to_mmap_size (),
403 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000404 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000405 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000406 m_command_sp (),
Ewan Crawford78baa192015-05-13 09:18:18 +0000407 m_breakpoint_pc_offset (0),
408 m_initial_tid (LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000409{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000410 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
411 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000412 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000413
414 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_ASYNC));
415
416 const uint32_t async_event_mask = eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
417
418 if (m_async_listener.StartListeningForEvents(&m_async_broadcaster, async_event_mask) != async_event_mask)
419 {
420 if (log)
421 log->Printf("ProcessGDBRemote::%s failed to listen for m_async_broadcaster events", __FUNCTION__);
422 }
423
424 const uint32_t gdb_event_mask = Communication::eBroadcastBitReadThreadDidExit |
425 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
426 if (m_async_listener.StartListeningForEvents(&m_gdb_comm, gdb_event_mask) != gdb_event_mask)
427 {
428 if (log)
429 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events", __FUNCTION__);
430 }
431
Greg Clayton7f982402013-07-15 22:54:20 +0000432 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
433 if (timeout_seconds > 0)
434 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000435}
436
Eugene Zelenko0722f082015-10-24 01:28:05 +0000437//----------------------------------------------------------------------
438// Destructor
439//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000440ProcessGDBRemote::~ProcessGDBRemote()
441{
442 // m_mach_process.UnregisterNotificationCallbacks (this);
443 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000444 // We need to call finalize on the process before destroying ourselves
445 // to make sure all of the broadcaster cleanup goes as planned. If we
446 // destruct this class, then Process::~Process() might have problems
447 // trying to fully destroy the broadcaster.
448 Finalize();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000449
Jim Ingham455fa5c2012-11-01 01:15:33 +0000450 // The general Finalize is going to try to destroy the process and that SHOULD
451 // shut down the async thread. However, if we don't kill it it will get stranded and
452 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
453 StopAsyncThread();
454 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000455}
456
457//----------------------------------------------------------------------
458// PluginInterface
459//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000460ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000461ProcessGDBRemote::GetPluginName()
462{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000463 return GetPluginNameStatic();
464}
465
466uint32_t
467ProcessGDBRemote::GetPluginVersion()
468{
469 return 1;
470}
471
Greg Claytonef8180a2013-10-15 00:14:28 +0000472bool
473ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
474{
475 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
476 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000477 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000478 if (module_object_sp)
479 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000480 StructuredData::DictionarySP target_definition_sp(
481 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000482
Zachary Turner0641ca12015-03-17 20:04:04 +0000483 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000484 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000485 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
486 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000487 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000488 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000489 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000490 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
491 if (auto triple_string_value = triple_value->GetAsString())
492 {
493 std::string triple_string = triple_string_value->GetValue();
494 ArchSpec host_arch(triple_string.c_str());
495 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
496 {
497 GetTarget().SetArchitecture(host_arch);
498 }
499 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000500 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000501 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000502 m_breakpoint_pc_offset = 0;
503 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
504 if (breakpoint_pc_offset_value)
505 {
506 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
507 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
508 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000509
Greg Claytond04f0ed2015-05-26 18:00:51 +0000510 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000511 {
512 return true;
513 }
514 }
515 }
516 return false;
517}
518
Jason Molenda21586c82015-09-09 03:36:24 +0000519// If the remote stub didn't give us eh_frame or DWARF register numbers for a register,
520// see if the ABI can provide them.
521// DWARF and eh_frame register numbers are defined as a part of the ABI.
522static void
523AugmentRegisterInfoViaABI (RegisterInfo &reg_info, ConstString reg_name, ABISP abi_sp)
524{
525 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM
526 || reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM)
527 {
528 if (abi_sp)
529 {
530 RegisterInfo abi_reg_info;
531 if (abi_sp->GetRegisterInfoByName (reg_name, abi_reg_info))
532 {
Greg Claytonb1583dc2015-12-04 18:37:48 +0000533 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM &&
534 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
Jason Molenda21586c82015-09-09 03:36:24 +0000535 {
536 reg_info.kinds[eRegisterKindEHFrame] = abi_reg_info.kinds[eRegisterKindEHFrame];
537 }
Greg Claytonb1583dc2015-12-04 18:37:48 +0000538 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM &&
539 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
Jason Molenda21586c82015-09-09 03:36:24 +0000540 {
541 reg_info.kinds[eRegisterKindDWARF] = abi_reg_info.kinds[eRegisterKindDWARF];
542 }
Greg Claytonb1583dc2015-12-04 18:37:48 +0000543 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM &&
544 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM)
545 {
546 reg_info.kinds[eRegisterKindGeneric] = abi_reg_info.kinds[eRegisterKindGeneric];
547 }
Jason Molenda21586c82015-09-09 03:36:24 +0000548 }
549 }
550 }
551}
552
Greg Claytond04f0ed2015-05-26 18:00:51 +0000553static size_t
554SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
555{
556 regnums.clear();
557 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
558 value_pair.second = comma_separated_regiter_numbers;
559 do
560 {
561 value_pair = value_pair.second.split(',');
562 if (!value_pair.first.empty())
563 {
564 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
565 if (reg != LLDB_INVALID_REGNUM)
566 regnums.push_back (reg);
567 }
568 } while (!value_pair.second.empty());
569 return regnums.size();
570}
571
Eugene Zelenko0722f082015-10-24 01:28:05 +0000572
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000573void
Greg Clayton513c26c2011-01-29 07:10:55 +0000574ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000575{
Greg Clayton513c26c2011-01-29 07:10:55 +0000576 if (!force && m_register_info.GetNumRegisters() > 0)
577 return;
578
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000579 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000580
581 // Check if qHostInfo specified a specific packet timeout for this connection.
582 // If so then lets update our setting so the user knows what the timeout is
583 // and can see it.
584 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
585 if (host_packet_timeout)
586 {
587 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
588 }
589
Ed Maste81b4c5f2016-01-04 01:43:47 +0000590 // Register info search order:
Ewan Crawford0c996a92015-06-30 13:08:44 +0000591 // 1 - Use the target definition python file if one is specified.
592 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
593 // 3 - Fall back on the qRegisterInfo packets.
594
595 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Jason Molenda91e468c2015-08-20 04:29:46 +0000596 if (!target_definition_fspec.Exists())
597 {
598 // If the filename doesn't exist, it may be a ~ not having been expanded - try to resolve it.
599 target_definition_fspec.ResolvePath();
600 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000601 if (target_definition_fspec)
602 {
603 // See if we can get register definitions from a python file
604 if (ParsePythonTargetDefinition (target_definition_fspec))
Jason Molenda5543abb2015-08-20 03:05:09 +0000605 {
Ewan Crawford0c996a92015-06-30 13:08:44 +0000606 return;
Jason Molenda5543abb2015-08-20 03:05:09 +0000607 }
608 else
609 {
610 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
611 stream_sp->Printf ("ERROR: target description file %s failed to parse.\n", target_definition_fspec.GetPath().c_str());
612 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000613 }
614
Greg Claytond04f0ed2015-05-26 18:00:51 +0000615 if (GetGDBServerRegisterInfo ())
616 return;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000617
Greg Claytond04f0ed2015-05-26 18:00:51 +0000618 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000619 uint32_t reg_offset = 0;
620 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000621 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000622 response_type == StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000623 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000624 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000625 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000626 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000627 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000628 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000629 {
Greg Clayton576d8832011-03-22 04:00:09 +0000630 response_type = response.GetResponseType();
631 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000632 {
633 std::string name;
634 std::string value;
635 ConstString reg_name;
636 ConstString alt_name;
637 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000638 std::vector<uint32_t> value_regs;
639 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640 RegisterInfo reg_info = { NULL, // Name
641 NULL, // Alt name
642 0, // byte size
643 reg_offset, // offset
644 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +0000645 eFormatHex, // format
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000646 {
Jason Molendabf67a302015-09-01 05:17:01 +0000647 LLDB_INVALID_REGNUM, // eh_frame reg num
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000648 LLDB_INVALID_REGNUM, // DWARF reg num
649 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +0000650 reg_num, // process plugin reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000651 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000652 },
653 NULL,
654 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000655 };
656
657 while (response.GetNameColonValue(name, value))
658 {
659 if (name.compare("name") == 0)
660 {
661 reg_name.SetCString(value.c_str());
662 }
663 else if (name.compare("alt-name") == 0)
664 {
665 alt_name.SetCString(value.c_str());
666 }
667 else if (name.compare("bitsize") == 0)
668 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000669 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000670 }
671 else if (name.compare("offset") == 0)
672 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000673 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000674 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000675 {
676 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000677 }
678 }
679 else if (name.compare("encoding") == 0)
680 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000681 const Encoding encoding = Args::StringToEncoding (value.c_str());
682 if (encoding != eEncodingInvalid)
683 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000684 }
685 else if (name.compare("format") == 0)
686 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000687 Format format = eFormatInvalid;
688 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
689 reg_info.format = format;
690 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000691 reg_info.format = eFormatBinary;
692 else if (value.compare("decimal") == 0)
693 reg_info.format = eFormatDecimal;
694 else if (value.compare("hex") == 0)
695 reg_info.format = eFormatHex;
696 else if (value.compare("float") == 0)
697 reg_info.format = eFormatFloat;
698 else if (value.compare("vector-sint8") == 0)
699 reg_info.format = eFormatVectorOfSInt8;
700 else if (value.compare("vector-uint8") == 0)
701 reg_info.format = eFormatVectorOfUInt8;
702 else if (value.compare("vector-sint16") == 0)
703 reg_info.format = eFormatVectorOfSInt16;
704 else if (value.compare("vector-uint16") == 0)
705 reg_info.format = eFormatVectorOfUInt16;
706 else if (value.compare("vector-sint32") == 0)
707 reg_info.format = eFormatVectorOfSInt32;
708 else if (value.compare("vector-uint32") == 0)
709 reg_info.format = eFormatVectorOfUInt32;
710 else if (value.compare("vector-float32") == 0)
711 reg_info.format = eFormatVectorOfFloat32;
712 else if (value.compare("vector-uint128") == 0)
713 reg_info.format = eFormatVectorOfUInt128;
714 }
715 else if (name.compare("set") == 0)
716 {
717 set_name.SetCString(value.c_str());
718 }
Jason Molendaa18f7072015-08-15 01:21:01 +0000719 else if (name.compare("gcc") == 0 || name.compare("ehframe") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000720 {
Jason Molendaa18f7072015-08-15 01:21:01 +0000721 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000722 }
723 else if (name.compare("dwarf") == 0)
724 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000725 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726 }
727 else if (name.compare("generic") == 0)
728 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000729 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000731 else if (name.compare("container-regs") == 0)
732 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000733 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000734 }
735 else if (name.compare("invalidate-regs") == 0)
736 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000737 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000738 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000739 }
740
Jason Molenda743e86a2010-06-11 23:44:18 +0000741 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742 assert (reg_info.byte_size != 0);
743 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000744 if (!value_regs.empty())
745 {
746 value_regs.push_back(LLDB_INVALID_REGNUM);
747 reg_info.value_regs = value_regs.data();
748 }
749 if (!invalidate_regs.empty())
750 {
751 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
752 reg_info.invalidate_regs = invalidate_regs.data();
753 }
754
Jason Molenda21586c82015-09-09 03:36:24 +0000755 AugmentRegisterInfoViaABI (reg_info, reg_name, GetABI ());
756
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000757 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
758 }
Todd Fiala1a634402014-01-08 07:52:40 +0000759 else
760 {
761 break; // ensure exit before reg_num is incremented
762 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000763 }
764 else
765 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000766 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000767 }
768 }
769
Greg Claytond04f0ed2015-05-26 18:00:51 +0000770 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000771 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000772 m_register_info.Finalize(GetTarget().GetArchitecture());
773 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000774 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000775
Johnny Chen2fa9de12012-05-14 18:44:23 +0000776 // We didn't get anything if the accumulated reg_num is zero. See if we are
777 // debugging ARM and fill with a hard coded register set until we can get an
778 // updated debugserver down on the devices.
779 // On the other hand, if the accumulated reg_num is positive, see if we can
780 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000781 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000782
783 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000784 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
785 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
786
787 // Use the process' architecture instead of the host arch, if available
788 ArchSpec remote_arch;
789 if (remote_process_arch.IsValid ())
790 remote_arch = remote_process_arch;
791 else
792 remote_arch = remote_host_arch;
793
Johnny Chen2fa9de12012-05-14 18:44:23 +0000794 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000796 if (remote_arch.IsValid()
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000797 && (remote_arch.GetMachine() == llvm::Triple::arm || remote_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000798 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
799 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000800 }
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000801 else if (target_arch.GetMachine() == llvm::Triple::arm
802 || target_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000803 {
804 m_register_info.HardcodeARMRegisters(from_scratch);
805 }
806
807 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000808 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000809}
810
811Error
812ProcessGDBRemote::WillLaunch (Module* module)
813{
814 return WillLaunchOrAttach ();
815}
816
817Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000818ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000819{
820 return WillLaunchOrAttach ();
821}
822
823Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000824ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000825{
826 return WillLaunchOrAttach ();
827}
828
829Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000830ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000831{
Todd Fialaaf245d12014-06-30 21:05:18 +0000832 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000833 Error error (WillLaunchOrAttach ());
Ed Maste81b4c5f2016-01-04 01:43:47 +0000834
Greg Claytonb766a732011-02-04 01:58:07 +0000835 if (error.Fail())
836 return error;
837
Greg Clayton2289fa42011-04-30 01:09:13 +0000838 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000839
840 if (error.Fail())
841 return error;
842 StartAsyncThread ();
843
Greg Claytonc574ede2011-03-10 02:26:48 +0000844 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000845 if (pid == LLDB_INVALID_PROCESS_ID)
846 {
847 // We don't have a valid process ID, so note that we are connected
Ed Maste81b4c5f2016-01-04 01:43:47 +0000848 // and could now request to launch or attach, or get remote process
Greg Claytonb766a732011-02-04 01:58:07 +0000849 // listings...
850 SetPrivateState (eStateConnected);
851 }
852 else
853 {
854 // We have a valid process
855 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000856 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000857 StringExtractorGDBRemote response;
858 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000859 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000860 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000861
862 // '?' Packets must be handled differently in non-stop mode
863 if (GetTarget().GetNonStopModeEnabled())
864 HandleStopReplySequence();
865
Zachary Turner7529df92015-09-01 20:02:29 +0000866 Target &target = GetTarget();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000867 if (!target.GetArchitecture().IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +0000868 {
869 if (m_gdb_comm.GetProcessArchitecture().IsValid())
870 {
Zachary Turner7529df92015-09-01 20:02:29 +0000871 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000872 }
873 else
874 {
Zachary Turner7529df92015-09-01 20:02:29 +0000875 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000876 }
Carlo Kok74389122013-10-14 07:09:13 +0000877 }
878
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000879 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000880 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000881 {
882 SetPrivateState (state);
883 }
884 else
Daniel Malead01b2952012-11-29 21:49:15 +0000885 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 +0000886 }
887 else
Daniel Malead01b2952012-11-29 21:49:15 +0000888 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 +0000889 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000890
Todd Fialaaf245d12014-06-30 21:05:18 +0000891 if (log)
892 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalizing target architecture initial triple: %s (GetTarget().GetArchitecture().IsValid() %s, m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str (), GetTarget ().GetArchitecture ().IsValid () ? "true" : "false", m_gdb_comm.GetHostArchitecture ().IsValid () ? "true" : "false");
893
894
895 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000896 && !GetTarget().GetArchitecture().IsValid()
897 && m_gdb_comm.GetHostArchitecture().IsValid())
898 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000899 // Prefer the *process'* architecture over that of the *host*, if available.
900 if (m_gdb_comm.GetProcessArchitecture().IsValid())
901 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
902 else
903 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000904 }
905
Todd Fialaaf245d12014-06-30 21:05:18 +0000906 if (log)
907 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
908
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000909 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000910 {
911 PlatformSP platform_sp = GetTarget().GetPlatform();
912 if (platform_sp && platform_sp->IsConnected())
913 SetUnixSignals(platform_sp->GetUnixSignals());
914 else
915 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
916 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000917
Greg Claytonb766a732011-02-04 01:58:07 +0000918 return error;
919}
920
921Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000922ProcessGDBRemote::WillLaunchOrAttach ()
923{
924 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000925 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000926 return error;
927}
928
929//----------------------------------------------------------------------
930// Process Control
931//----------------------------------------------------------------------
932Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000933ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000934{
Todd Fiala75f47c32014-10-11 21:42:09 +0000935 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000936 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000937
Todd Fiala75f47c32014-10-11 21:42:09 +0000938 if (log)
939 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
940
Greg Clayton982c9762011-11-03 21:22:33 +0000941 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000942 FileSpec stdin_file_spec{};
943 FileSpec stdout_file_spec{};
944 FileSpec stderr_file_spec{};
945 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000946
Zachary Turner696b5282014-08-14 16:01:25 +0000947 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000948 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
949 if (file_action)
950 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000951 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000952 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000953 }
954 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
955 if (file_action)
956 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000957 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000958 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000959 }
960 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
961 if (file_action)
962 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000963 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000964 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000965 }
966
Todd Fiala75f47c32014-10-11 21:42:09 +0000967 if (log)
968 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000969 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000970 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000971 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000972 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
973 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
974 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000975 else
976 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
977 }
978
Vince Harrondf3f00f2015-02-10 21:09:04 +0000979 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000980 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000981 {
982 // the inferior will be reading stdin from the specified file
983 // or stdio is completely disabled
984 m_stdin_forward = false;
985 }
986 else
987 {
988 m_stdin_forward = true;
989 }
990
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
992 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
993 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000994
Greg Clayton982c9762011-11-03 21:22:33 +0000995 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000996 if (object_file)
997 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +0000998 error = EstablishConnectionIfNeeded (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000999 if (error.Success())
1000 {
1001 lldb_utility::PseudoTerminal pty;
1002 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +00001003
Zachary Turner7529df92015-09-01 20:02:29 +00001004 PlatformSP platform_sp (GetTarget().GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +00001005 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +00001006 {
Vince Harrondf3f00f2015-02-10 21:09:04 +00001007 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +00001008 if (!stdin_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +00001009 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +00001010 if (!stdout_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +00001011 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +00001012 if (!stderr_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +00001013 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
Vince Harrondf3f00f2015-02-10 21:09:04 +00001014 }
1015 else if (platform_sp && platform_sp->IsHost())
1016 {
1017 // If the debugserver is local and we aren't disabling STDIO, lets use
1018 // a pseudo terminal to instead of relying on the 'O' packets for stdio
1019 // since 'O' packets can really slow down debugging if the inferior
1020 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +00001021 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
1022 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001023 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001024 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
1025
1026 if (!stdin_file_spec)
1027 stdin_file_spec = slave_name;
1028
1029 if (!stdout_file_spec)
1030 stdout_file_spec = slave_name;
1031
1032 if (!stderr_file_spec)
1033 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001035 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +00001036 log->Printf ("ProcessGDBRemote::%s adjusted STDIO paths for local platform (IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +00001037 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +00001038 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
1039 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
1040 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +00001041 }
1042
Todd Fiala75f47c32014-10-11 21:42:09 +00001043 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +00001044 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +00001045 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +00001046 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
1047 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
1048 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +00001049
Chaoren Lind3173f32015-05-29 19:52:29 +00001050 if (stdin_file_spec)
1051 m_gdb_comm.SetSTDIN(stdin_file_spec);
1052 if (stdout_file_spec)
1053 m_gdb_comm.SetSTDOUT(stdout_file_spec);
1054 if (stderr_file_spec)
1055 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +00001056
1057 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +00001058 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +00001059
Zachary Turner7529df92015-09-01 20:02:29 +00001060 m_gdb_comm.SendLaunchArchPacket (GetTarget().GetArchitecture().GetArchitectureName());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001061
Jason Molendaa3329782014-03-29 18:54:20 +00001062 const char * launch_event_data = launch_info.GetLaunchEventData();
1063 if (launch_event_data != NULL && *launch_event_data != '\0')
1064 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001065
Chaoren Lind3173f32015-05-29 19:52:29 +00001066 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +00001067 {
1068 m_gdb_comm.SetWorkingDir (working_dir);
1069 }
1070
1071 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +00001072 const Args &environment = launch_info.GetEnvironmentEntries();
1073 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +00001074 {
Greg Clayton982c9762011-11-03 21:22:33 +00001075 size_t num_environment_entries = environment.GetArgumentCount();
1076 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001077 {
Greg Clayton982c9762011-11-03 21:22:33 +00001078 const char *env_entry = environment.GetArgumentAtIndex(i);
1079 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001080 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001081 }
Greg Clayton71337622011-02-24 22:24:29 +00001082 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001083
Greg Clayton71337622011-02-24 22:24:29 +00001084 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001085 // Scope for the scoped timeout object
1086 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1087
1088 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1089 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001090 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001091 std::string error_str;
1092 if (m_gdb_comm.GetLaunchSuccess (error_str))
1093 {
1094 SetID (m_gdb_comm.GetCurrentProcessID ());
1095 }
1096 else
1097 {
1098 error.SetErrorString (error_str.c_str());
1099 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100 }
1101 else
1102 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001103 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 }
Greg Clayton71337622011-02-24 22:24:29 +00001105 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001106
Greg Clayton71337622011-02-24 22:24:29 +00001107 if (GetID() == LLDB_INVALID_PROCESS_ID)
1108 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001109 if (log)
1110 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001111 KillDebugserverProcess ();
1112 return error;
1113 }
1114
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001115 StringExtractorGDBRemote response;
1116 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001117 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001118 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001119 // '?' Packets must be handled differently in non-stop mode
1120 if (GetTarget().GetNonStopModeEnabled())
1121 HandleStopReplySequence();
1122
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001123 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1124
1125 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001126 {
Zachary Turner7529df92015-09-01 20:02:29 +00001127 GetTarget().MergeArchitecture(process_arch);
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001128 }
1129 else
1130 {
1131 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1132 if (host_arch.IsValid())
Zachary Turner7529df92015-09-01 20:02:29 +00001133 GetTarget().MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001134 }
1135
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001136 SetPrivateState (SetThreadStopInfo (response));
Ed Maste81b4c5f2016-01-04 01:43:47 +00001137
Greg Clayton71337622011-02-24 22:24:29 +00001138 if (!disable_stdio)
1139 {
1140 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001141 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001142 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143 }
1144 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001145 else
1146 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001147 if (log)
1148 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001149 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001150 }
1151 else
1152 {
1153 // Set our user ID to an invalid process ID.
1154 SetID(LLDB_INVALID_PROCESS_ID);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001155 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1156 exe_module->GetFileSpec().GetFilename().AsCString(),
Greg Clayton982c9762011-11-03 21:22:33 +00001157 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001158 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001159 return error;
Eugene Zelenko0722f082015-10-24 01:28:05 +00001160
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001161}
1162
Eugene Zelenko0722f082015-10-24 01:28:05 +00001163
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001164Error
Greg Claytonb766a732011-02-04 01:58:07 +00001165ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166{
1167 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001168 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001169 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Ed Maste81b4c5f2016-01-04 01:43:47 +00001170
Greg Clayton00fe87b2013-12-05 22:58:22 +00001171 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001172 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001173 if (log)
1174 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001175 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1176 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001177 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001178 const uint32_t max_retry_count = 50;
1179 uint32_t retry_count = 0;
1180 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001181 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001182 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1183 {
1184 m_gdb_comm.SetConnection (conn_ap.release());
1185 break;
1186 }
1187 else if (error.WasInterrupted())
1188 {
1189 // If we were interrupted, don't keep retrying.
1190 break;
1191 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001192
Greg Clayton00fe87b2013-12-05 22:58:22 +00001193 retry_count++;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001194
Greg Clayton00fe87b2013-12-05 22:58:22 +00001195 if (retry_count >= max_retry_count)
1196 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001197
Greg Clayton00fe87b2013-12-05 22:58:22 +00001198 usleep (100000);
1199 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200 }
1201 }
1202
1203 if (!m_gdb_comm.IsConnected())
1204 {
1205 if (error.Success())
1206 error.SetErrorString("not connected to remote gdb server");
1207 return error;
1208 }
1209
Eugene Zelenko0722f082015-10-24 01:28:05 +00001210
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001211 // Start the communications read thread so all incoming data can be
1212 // parsed into packets and queued as they arrive.
1213 if (GetTarget().GetNonStopModeEnabled())
1214 m_gdb_comm.StartReadThread();
1215
Greg Clayton32e0a752011-03-30 18:16:51 +00001216 // We always seem to be able to open a connection to a local port
1217 // so we need to make sure we can then send data to it. If we can't
1218 // then we aren't actually connected to anything, so try and do the
Ed Maste81b4c5f2016-01-04 01:43:47 +00001219 // handshake with the remote GDB server and make sure that goes
Greg Clayton32e0a752011-03-30 18:16:51 +00001220 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001221 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001222 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001223 m_gdb_comm.Disconnect();
1224 if (error.Success())
1225 error.SetErrorString("not connected to remote gdb server");
1226 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001227 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001228
1229 // Send $QNonStop:1 packet on startup if required
1230 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001231 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001232
Greg Claytonb30c50c2015-05-29 00:01:55 +00001233 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001234 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001235 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001236 m_gdb_comm.GetHostInfo ();
1237 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001238 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001239
1240 // Ask the remote server for the default thread id
1241 if (GetTarget().GetNonStopModeEnabled())
1242 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1243
1244
Jim Ingham03afad82012-07-02 05:40:07 +00001245 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1246 for (size_t idx = 0; idx < num_cmds; idx++)
1247 {
1248 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001249 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1250 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001251 return error;
1252}
1253
1254void
Jim Inghambb006ce2014-08-02 00:33:35 +00001255ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001256{
Greg Clayton5160ce52013-03-27 23:08:40 +00001257 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001258 if (log)
1259 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001260 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001261 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001262 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001263
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001264 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001265
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001266
1267 // See if the GDB server supports the qProcessInfo packet, if so
1268 // prefer that over the Host information as it will be more specific
1269 // to our process.
1270
Todd Fiala75f47c32014-10-11 21:42:09 +00001271 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1272 if (remote_process_arch.IsValid())
1273 {
1274 process_arch = remote_process_arch;
1275 if (log)
1276 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1277 __FUNCTION__,
1278 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1279 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1280 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001281 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001282 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001283 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001284 if (log)
1285 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1286 __FUNCTION__,
1287 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1288 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1289 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001290
Jim Inghambb006ce2014-08-02 00:33:35 +00001291 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001292 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001293 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001294 if (target_arch.IsValid())
1295 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001296 if (log)
1297 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1298 __FUNCTION__,
1299 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1300 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1301
1302 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001303 // ARM executables and shared libraries can have mixed ARM architectures.
1304 // You can have an armv6 executable, and if the host is armv7, then the
1305 // system will load the best possible architecture for all shared libraries
1306 // it has, so we really need to take the remote host architecture as our
1307 // defacto architecture in this case.
1308
Jason Molenda6d9fe8c2015-08-21 00:13:37 +00001309 if ((process_arch.GetMachine() == llvm::Triple::arm || process_arch.GetMachine() == llvm::Triple::thumb)
1310 && process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001311 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001312 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001313 if (log)
1314 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1315 __FUNCTION__,
1316 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1317 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001318 }
1319 else
1320 {
1321 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001322 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001323 llvm::Triple new_target_triple = target_arch.GetTriple();
1324 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001325 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001326 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001327
Tamas Berghammere724af12015-03-13 10:32:37 +00001328 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001329 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001330 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001331
Tamas Berghammere724af12015-03-13 10:32:37 +00001332 if (new_target_triple.getEnvironmentName().size() == 0)
1333 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001334 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001335
Tamas Berghammere724af12015-03-13 10:32:37 +00001336 ArchSpec new_target_arch = target_arch;
1337 new_target_arch.SetTriple(new_target_triple);
1338 GetTarget().SetArchitecture(new_target_arch);
1339 }
Greg Claytond314e812011-03-23 00:09:55 +00001340 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001341
1342 if (log)
1343 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1344 __FUNCTION__,
1345 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1346 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001347 }
1348 else
1349 {
1350 // The target doesn't have a valid architecture yet, set it from
1351 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001352 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001353 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001354 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001355 }
1356}
1357
1358void
1359ProcessGDBRemote::DidLaunch ()
1360{
Jim Inghambb006ce2014-08-02 00:33:35 +00001361 ArchSpec process_arch;
1362 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001363}
1364
1365Error
Han Ming Ong84647042012-02-25 01:07:38 +00001366ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1367{
Todd Fiala75f47c32014-10-11 21:42:09 +00001368 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001369 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001370
1371 if (log)
1372 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1373
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374 // Clear out and clean up from any current state
1375 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001376 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1377 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001378 error = EstablishConnectionIfNeeded (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001379 if (error.Success())
1380 {
Jim Ingham106d0282014-06-25 02:32:56 +00001381 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001382
Greg Clayton71337622011-02-24 22:24:29 +00001383 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001384 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001385 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001386 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001387 }
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001388 else
1389 SetExitStatus (-1, error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001390 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001391
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001392 return error;
1393}
1394
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001395Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001396ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001397{
1398 Error error;
1399 // Clear out and clean up from any current state
1400 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001401
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001402 if (process_name && process_name[0])
1403 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001404 error = EstablishConnectionIfNeeded (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001405 if (error.Success())
1406 {
1407 StreamString packet;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001408
Jim Ingham106d0282014-06-25 02:32:56 +00001409 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001410
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001411 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001412 {
1413 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1414 {
1415 packet.PutCString ("vAttachWait");
1416 }
1417 else
1418 {
1419 if (attach_info.GetIgnoreExisting())
1420 packet.PutCString("vAttachWait");
1421 else
1422 packet.PutCString ("vAttachOrWait");
1423 }
1424 }
Greg Clayton71337622011-02-24 22:24:29 +00001425 else
1426 packet.PutCString("vAttachName");
1427 packet.PutChar(';');
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00001428 packet.PutBytesAsRawHex8(process_name, strlen(process_name), endian::InlHostByteOrder(), endian::InlHostByteOrder());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001429
Greg Clayton71337622011-02-24 22:24:29 +00001430 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1431
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001432 }
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001433 else
1434 SetExitStatus (-1, error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001435 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001436 return error;
1437}
1438
Greg Clayton5df78fa2015-05-23 03:54:53 +00001439void
1440ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001441{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001442 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001443 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001444}
1445
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001446void
Jim Inghambb006ce2014-08-02 00:33:35 +00001447ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001448{
Jim Inghambb006ce2014-08-02 00:33:35 +00001449 // If you can figure out what the architecture is, fill it in here.
1450 process_arch.Clear();
1451 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001452}
1453
Eugene Zelenko0722f082015-10-24 01:28:05 +00001454
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001455Error
1456ProcessGDBRemote::WillResume ()
1457{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001458 m_continue_c_tids.clear();
1459 m_continue_C_tids.clear();
1460 m_continue_s_tids.clear();
1461 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001462 m_jstopinfo_sp.reset();
1463 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001464 return Error();
1465}
1466
1467Error
1468ProcessGDBRemote::DoResume ()
1469{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001470 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001471 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001472 if (log)
1473 log->Printf ("ProcessGDBRemote::Resume()");
Ed Maste81b4c5f2016-01-04 01:43:47 +00001474
Greg Claytone5219662010-12-03 06:02:24 +00001475 Listener listener ("gdb-remote.resume-packet-sent");
1476 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1477 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001478 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001479
Greg Claytond1d06e42013-04-20 00:27:58 +00001480 const size_t num_threads = GetThreadList().GetSize();
1481
Greg Clayton71fc2a32011-02-12 06:28:37 +00001482 StreamString continue_packet;
1483 bool continue_packet_error = false;
1484 if (m_gdb_comm.HasAnyVContSupport ())
1485 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001486 if (!GetTarget().GetNonStopModeEnabled() &&
1487 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001488 (m_continue_c_tids.empty() &&
1489 m_continue_C_tids.empty() &&
1490 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001491 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001492 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001493 // All threads are continuing, just send a "c" packet
1494 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001495 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001496 else
1497 {
1498 continue_packet.PutCString ("vCont");
Ed Maste81b4c5f2016-01-04 01:43:47 +00001499
Greg Claytond1d06e42013-04-20 00:27:58 +00001500 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001501 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001502 if (m_gdb_comm.GetVContSupported ('c'))
1503 {
1504 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)
1505 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1506 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001507 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001508 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001509 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001510
Greg Claytond1d06e42013-04-20 00:27:58 +00001511 if (!continue_packet_error && !m_continue_C_tids.empty())
1512 {
1513 if (m_gdb_comm.GetVContSupported ('C'))
1514 {
1515 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)
1516 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1517 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001518 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001519 continue_packet_error = true;
1520 }
Greg Claytone5219662010-12-03 06:02:24 +00001521
Greg Claytond1d06e42013-04-20 00:27:58 +00001522 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001523 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001524 if (m_gdb_comm.GetVContSupported ('s'))
1525 {
1526 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)
1527 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1528 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001529 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001530 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001531 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001532
Greg Claytond1d06e42013-04-20 00:27:58 +00001533 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001534 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001535 if (m_gdb_comm.GetVContSupported ('S'))
1536 {
1537 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)
1538 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1539 }
1540 else
1541 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001542 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001543
Greg Claytond1d06e42013-04-20 00:27:58 +00001544 if (continue_packet_error)
1545 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001546 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001547 }
1548 else
1549 continue_packet_error = true;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001550
Greg Clayton71fc2a32011-02-12 06:28:37 +00001551 if (continue_packet_error)
1552 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001553 // Either no vCont support, or we tried to use part of the vCont
1554 // packet that wasn't supported by the remote GDB server.
1555 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001556 const size_t num_continue_c_tids = m_continue_c_tids.size();
1557 const size_t num_continue_C_tids = m_continue_C_tids.size();
1558 const size_t num_continue_s_tids = m_continue_s_tids.size();
1559 const size_t num_continue_S_tids = m_continue_S_tids.size();
1560 if (num_continue_c_tids > 0)
1561 {
1562 if (num_continue_c_tids == num_threads)
1563 {
1564 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001565 m_gdb_comm.SetCurrentThreadForRun (-1);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001566 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001567 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001568 }
1569 else if (num_continue_c_tids == 1 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001570 num_continue_C_tids == 0 &&
1571 num_continue_s_tids == 0 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001572 num_continue_S_tids == 0 )
1573 {
1574 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001575 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001576 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001577 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001578 }
1579 }
1580
Greg Clayton0c74e782011-06-24 03:21:43 +00001581 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001582 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001583 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1584 num_continue_C_tids > 0 &&
1585 num_continue_s_tids == 0 &&
Greg Clayton0c74e782011-06-24 03:21:43 +00001586 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001587 {
1588 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001589 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001590 if (num_continue_C_tids > 1)
1591 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001592 // More that one thread with a signal, yet we don't have
Greg Clayton0c74e782011-06-24 03:21:43 +00001593 // vCont support and we are being asked to resume each
1594 // thread with a signal, we need to make sure they are
1595 // all the same signal, or we can't issue the continue
1596 // accurately with the current support...
1597 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001598 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001599 continue_packet_error = false;
1600 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1601 {
1602 if (m_continue_C_tids[i].second != continue_signo)
1603 continue_packet_error = true;
1604 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001605 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001606 if (!continue_packet_error)
1607 m_gdb_comm.SetCurrentThreadForRun (-1);
1608 }
1609 else
1610 {
1611 // Set the continue thread ID
1612 continue_packet_error = false;
1613 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001614 }
1615 if (!continue_packet_error)
1616 {
1617 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001618 continue_packet.Printf("C%2.2x", continue_signo);
1619 }
1620 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001621 }
1622
Greg Clayton0c74e782011-06-24 03:21:43 +00001623 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001624 {
1625 if (num_continue_s_tids == num_threads)
1626 {
1627 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001628 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001629
1630 // If in Non-Stop-Mode use vCont when stepping
1631 if (GetTarget().GetNonStopModeEnabled())
1632 {
1633 if (m_gdb_comm.GetVContSupported('s'))
1634 continue_packet.PutCString("vCont;s");
1635 else
1636 continue_packet.PutChar('s');
1637 }
1638 else
1639 continue_packet.PutChar('s');
1640
Greg Clayton0c74e782011-06-24 03:21:43 +00001641 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001642 }
1643 else if (num_continue_c_tids == 0 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001644 num_continue_C_tids == 0 &&
1645 num_continue_s_tids == 1 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001646 num_continue_S_tids == 0 )
1647 {
1648 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001649 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001650 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001651 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001652 }
1653 }
1654
1655 if (!continue_packet_error && num_continue_S_tids > 0)
1656 {
1657 if (num_continue_S_tids == num_threads)
1658 {
1659 const int step_signo = m_continue_S_tids.front().second;
1660 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001661 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001662 if (num_continue_S_tids > 1)
1663 {
1664 for (size_t i=1; i<num_threads; ++i)
1665 {
1666 if (m_continue_S_tids[i].second != step_signo)
1667 continue_packet_error = true;
1668 }
1669 }
1670 if (!continue_packet_error)
1671 {
1672 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001673 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001674 continue_packet.Printf("S%2.2x", step_signo);
1675 }
1676 }
1677 else if (num_continue_c_tids == 0 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001678 num_continue_C_tids == 0 &&
1679 num_continue_s_tids == 0 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001680 num_continue_S_tids == 1 )
1681 {
1682 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001683 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001684 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001685 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001686 }
1687 }
1688 }
1689
1690 if (continue_packet_error)
1691 {
1692 error.SetErrorString ("can't make continue packet for this resume");
1693 }
1694 else
1695 {
1696 EventSP event_sp;
1697 TimeValue timeout;
1698 timeout = TimeValue::Now();
1699 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001700 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001701 {
1702 error.SetErrorString ("Trying to resume but the async thread is dead.");
1703 if (log)
1704 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1705 return error;
1706 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001707
Greg Clayton71fc2a32011-02-12 06:28:37 +00001708 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1709
1710 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001711 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001712 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001713 if (log)
1714 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1715 }
1716 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1717 {
1718 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1719 if (log)
1720 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1721 return error;
1722 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001723 }
Greg Claytone5219662010-12-03 06:02:24 +00001724 }
1725
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001726 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001727}
1728
Greg Clayton9e920902012-04-10 02:25:43 +00001729void
Ewan Crawford78baa192015-05-13 09:18:18 +00001730ProcessGDBRemote::HandleStopReplySequence ()
1731{
1732 while(true)
1733 {
1734 // Send vStopped
1735 StringExtractorGDBRemote response;
1736 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1737
1738 // OK represents end of signal list
1739 if (response.IsOKResponse())
1740 break;
1741
1742 // If not OK or a normal packet we have a problem
1743 if (!response.IsNormalResponse())
1744 break;
1745
1746 SetLastStopPacket(response);
1747 }
1748}
1749
1750void
Greg Clayton9e920902012-04-10 02:25:43 +00001751ProcessGDBRemote::ClearThreadIDList ()
1752{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001753 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001754 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001755 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00001756}
1757
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001758size_t
1759ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1760{
1761 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001762 m_thread_pcs.clear();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001763 size_t comma_pos;
1764 lldb::tid_t tid;
1765 while ((comma_pos = value.find(',')) != std::string::npos)
1766 {
1767 value[comma_pos] = '\0';
1768 // thread in big endian hex
1769 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1770 if (tid != LLDB_INVALID_THREAD_ID)
1771 m_thread_ids.push_back (tid);
1772 value.erase(0, comma_pos + 1);
1773 }
1774 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1775 if (tid != LLDB_INVALID_THREAD_ID)
1776 m_thread_ids.push_back (tid);
1777 return m_thread_ids.size();
1778}
1779
Jason Molenda545304d2015-12-18 00:45:35 +00001780size_t
1781ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue (std::string &value)
1782{
1783 m_thread_pcs.clear();
1784 size_t comma_pos;
1785 lldb::addr_t pc;
1786 while ((comma_pos = value.find(',')) != std::string::npos)
1787 {
1788 value[comma_pos] = '\0';
1789 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1790 if (pc != LLDB_INVALID_ADDRESS)
1791 m_thread_pcs.push_back (pc);
1792 value.erase(0, comma_pos + 1);
1793 }
1794 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1795 if (pc != LLDB_INVALID_THREAD_ID)
1796 m_thread_pcs.push_back (pc);
1797 return m_thread_pcs.size();
1798}
1799
Greg Clayton9e920902012-04-10 02:25:43 +00001800bool
1801ProcessGDBRemote::UpdateThreadIDList ()
1802{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001803 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001804
Greg Clayton2e309072015-07-17 23:42:28 +00001805 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001806 {
1807 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001808 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001809 if (thread_infos && thread_infos->GetSize() > 0)
1810 {
1811 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001812 m_thread_pcs.clear();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001813 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1814 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1815 if (thread_dict)
1816 {
1817 // Set the thread stop info from the JSON dictionary
1818 SetThreadStopInfo (thread_dict);
1819 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1820 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1821 m_thread_ids.push_back(tid);
1822 }
1823 return true; // Keep iterating through all thread_info objects
1824 });
1825 }
1826 if (!m_thread_ids.empty())
1827 return true;
1828 }
1829 else
1830 {
1831 // See if we can get the thread IDs from the current stop reply packets
1832 // that might contain a "threads" key/value pair
1833
1834 // Lock the thread stack while we access it
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001835 //Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1836 Mutex::Locker stop_stack_lock;
1837 if (stop_stack_lock.TryLock(m_last_stop_packet_mutex))
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001838 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001839 // Get the number of stop packets on the stack
1840 int nItems = m_stop_packet_stack.size();
1841 // Iterate over them
1842 for (int i = 0; i < nItems; i++)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001843 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001844 // Get the thread stop info
1845 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1846 const std::string &stop_info_str = stop_info.GetStringRef();
Jason Molenda545304d2015-12-18 00:45:35 +00001847
1848 m_thread_pcs.clear();
1849 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1850 if (thread_pcs_pos != std::string::npos)
1851 {
1852 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1853 const size_t end = stop_info_str.find(';', start);
1854 if (end != std::string::npos)
1855 {
1856 std::string value = stop_info_str.substr(start, end - start);
1857 UpdateThreadPCsFromStopReplyThreadsValue(value);
1858 }
1859 }
1860
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001861 const size_t threads_pos = stop_info_str.find(";threads:");
1862 if (threads_pos != std::string::npos)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001863 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001864 const size_t start = threads_pos + strlen(";threads:");
1865 const size_t end = stop_info_str.find(';', start);
1866 if (end != std::string::npos)
1867 {
1868 std::string value = stop_info_str.substr(start, end - start);
1869 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1870 return true;
1871 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001872 }
1873 }
1874 }
1875 }
1876
Greg Clayton9e920902012-04-10 02:25:43 +00001877 bool sequence_mutex_unavailable = false;
1878 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1879 if (sequence_mutex_unavailable)
1880 {
Greg Clayton9e920902012-04-10 02:25:43 +00001881 return false; // We just didn't get the list
1882 }
1883 return true;
1884}
1885
Greg Clayton9fc13552012-04-10 00:18:59 +00001886bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001887ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001888{
1889 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001890 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001891 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001892 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001893
Greg Clayton9e920902012-04-10 02:25:43 +00001894 size_t num_thread_ids = m_thread_ids.size();
1895 // The "m_thread_ids" thread ID list should always be updated after each stop
1896 // reply packet, but in case it isn't, update it here.
1897 if (num_thread_ids == 0)
1898 {
1899 if (!UpdateThreadIDList ())
1900 return false;
1901 num_thread_ids = m_thread_ids.size();
1902 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001903
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001904 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001905 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001906 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001907 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001908 {
Greg Clayton9e920902012-04-10 02:25:43 +00001909 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001910 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001911 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001912 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001913 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001914 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1915 log->Printf(
1916 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001917 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001918 thread_sp->GetID());
1919 }
1920 else
1921 {
1922 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1923 log->Printf(
1924 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001925 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001926 thread_sp->GetID());
1927 }
Jason Molenda545304d2015-12-18 00:45:35 +00001928 // The m_thread_pcs vector has pc values in big-endian order, not target-endian, unlike most
Ed Maste81b4c5f2016-01-04 01:43:47 +00001929 // of the register read/write packets in gdb-remote protocol.
Jason Molenda545304d2015-12-18 00:45:35 +00001930 // Early in the process startup, we may not yet have set the process ByteOrder so we ignore these;
1931 // they are a performance improvement over fetching thread register values individually, the
1932 // method we will fall back to if needed.
1933 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() && GetByteOrder() != eByteOrderInvalid)
1934 {
1935 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1936 RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
1937 if (reg_ctx_sp)
1938 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001939 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber
Jason Molenda545304d2015-12-18 00:45:35 +00001940 (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1941 if (pc_regnum != LLDB_INVALID_REGNUM)
1942 {
1943 gdb_thread->PrivateSetRegisterValue (pc_regnum, m_thread_pcs[i]);
1944 }
1945 }
1946 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001947 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001948 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001949 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001950
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001951 // Whatever that is left in old_thread_list_copy are not
1952 // present in new_thread_list. Remove non-existent threads from internal id table.
1953 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1954 for (size_t i=0; i<old_num_thread_ids; i++)
1955 {
1956 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1957 if (old_thread_sp)
1958 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001959 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001960 m_thread_id_to_index_id_map.erase(old_thread_id);
1961 }
1962 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001963
Greg Clayton9fc13552012-04-10 00:18:59 +00001964 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001965}
1966
Eugene Zelenko0722f082015-10-24 01:28:05 +00001967
Greg Clayton358cf1e2015-06-25 21:46:34 +00001968bool
Greg Clayton2e309072015-07-17 23:42:28 +00001969ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001970{
1971 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001972 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001973 {
Greg Clayton2e309072015-07-17 23:42:28 +00001974 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001975 if (thread_infos)
1976 {
1977 lldb::tid_t tid;
1978 const size_t n = thread_infos->GetSize();
1979 for (size_t i=0; i<n; ++i)
1980 {
1981 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1982 if (thread_dict)
1983 {
1984 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1985 {
1986 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001987 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001988 }
1989 }
1990 }
1991 }
1992 }
Greg Clayton2e309072015-07-17 23:42:28 +00001993 return false;
1994}
1995
1996bool
1997ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1998{
1999 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
2000 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
2001 return true;
2002
2003 // See if we got thread stop info for any threads valid stop info reasons threads
2004 // via the "jstopinfo" packet stop reply packet key/value pair?
2005 if (m_jstopinfo_sp)
2006 {
2007 // If we have "jstopinfo" then we have stop descriptions for all threads
2008 // that have stop reasons, and if there is no entry for a thread, then
2009 // it has no stop reason.
2010 thread->GetRegisterContext()->InvalidateIfNeeded(true);
2011 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
2012 {
2013 thread->SetStopInfo (StopInfoSP());
2014 }
2015 return true;
2016 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002017
2018 // Fall back to using the qThreadStopInfo packet
2019 StringExtractorGDBRemote stop_packet;
2020 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
2021 return SetThreadStopInfo (stop_packet) == eStateStopped;
2022 return false;
2023}
2024
Eugene Zelenko0722f082015-10-24 01:28:05 +00002025
Greg Clayton358cf1e2015-06-25 21:46:34 +00002026ThreadSP
2027ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
2028 ExpeditedRegisterMap &expedited_register_map,
2029 uint8_t signo,
2030 const std::string &thread_name,
2031 const std::string &reason,
2032 const std::string &description,
2033 uint32_t exc_type,
2034 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002035 addr_t thread_dispatch_qaddr,
2036 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002037 LazyBool associated_with_dispatch_queue,
2038 addr_t dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002039 std::string &queue_name,
2040 QueueKind queue_kind,
2041 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002042{
2043 ThreadSP thread_sp;
2044 if (tid != LLDB_INVALID_THREAD_ID)
2045 {
2046 // Scope for "locker" below
2047 {
2048 // m_thread_list_real does have its own mutex, but we need to
2049 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
2050 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
2051 Mutex::Locker locker (m_thread_list_real.GetMutex ());
2052 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
2053
2054 if (!thread_sp)
2055 {
2056 // Create the thread if we need to
2057 thread_sp.reset (new ThreadGDBRemote (*this, tid));
2058 m_thread_list_real.AddThread(thread_sp);
2059 }
2060 }
2061
2062 if (thread_sp)
2063 {
2064 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
2065 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002066
Greg Clayton358cf1e2015-06-25 21:46:34 +00002067 for (const auto &pair : expedited_register_map)
2068 {
2069 StringExtractor reg_value_extractor;
2070 reg_value_extractor.GetStringRef() = pair.second;
2071 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
2072 }
2073
Greg Clayton358cf1e2015-06-25 21:46:34 +00002074 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
2075
2076 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002077 // Check if the GDB server was able to provide the queue name, kind and serial number
2078 if (queue_vars_valid)
Jason Molenda77f89352016-01-12 07:09:16 +00002079 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial, dispatch_queue_t, associated_with_dispatch_queue);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002080 else
2081 gdb_thread->ClearQueueInfo();
2082
Jason Molenda77f89352016-01-12 07:09:16 +00002083 gdb_thread->SetAssociatedWithLibdispatchQueue (associated_with_dispatch_queue);
2084
2085 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
2086 gdb_thread->SetQueueLibdispatchQueueAddress (dispatch_queue_t);
2087
Greg Clayton2e309072015-07-17 23:42:28 +00002088 // Make sure we update our thread stop reason just once
2089 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002090 {
Greg Clayton2e309072015-07-17 23:42:28 +00002091 thread_sp->SetStopInfo (StopInfoSP());
Ryan Brown65d4d5c2015-09-16 21:20:44 +00002092 // If there's a memory thread backed by this thread, we need to use it to calcualte StopInfo.
2093 ThreadSP memory_thread_sp = m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
2094 if (memory_thread_sp)
2095 thread_sp = memory_thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002096
Greg Clayton2e309072015-07-17 23:42:28 +00002097 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002098 {
Greg Clayton2e309072015-07-17 23:42:28 +00002099 const size_t exc_data_size = exc_data.size();
2100
2101 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
2102 exc_type,
2103 exc_data_size,
2104 exc_data_size >= 1 ? exc_data[0] : 0,
2105 exc_data_size >= 2 ? exc_data[1] : 0,
2106 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002107 }
Greg Clayton2e309072015-07-17 23:42:28 +00002108 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002109 {
Greg Clayton2e309072015-07-17 23:42:28 +00002110 bool handled = false;
2111 bool did_exec = false;
2112 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002113 {
Greg Clayton2e309072015-07-17 23:42:28 +00002114 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002115 {
Greg Clayton2e309072015-07-17 23:42:28 +00002116 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2117 handled = true;
2118 }
2119 else if (reason.compare("breakpoint") == 0)
2120 {
2121 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2122 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2123 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002124 {
Greg Clayton2e309072015-07-17 23:42:28 +00002125 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2126 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2127 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2128 handled = true;
2129 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2130 {
2131 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2132 }
2133 else
2134 {
2135 StopInfoSP invalid_stop_info_sp;
2136 thread_sp->SetStopInfo (invalid_stop_info_sp);
2137 }
2138 }
2139 }
2140 else if (reason.compare("trap") == 0)
2141 {
2142 // Let the trap just use the standard signal stop reason below...
2143 }
2144 else if (reason.compare("watchpoint") == 0)
2145 {
2146 StringExtractor desc_extractor(description.c_str());
2147 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2148 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002149 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002150 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2151 if (wp_addr != LLDB_INVALID_ADDRESS)
2152 {
Mohit K. Bhakkad6846bc82015-12-02 17:45:02 +00002153 WatchpointSP wp_sp;
2154 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
2155 if (core >= ArchSpec::kCore_mips_first && core <= ArchSpec::kCore_mips_last)
2156 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_hit_addr);
2157 if (!wp_sp)
2158 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
Greg Clayton2e309072015-07-17 23:42:28 +00002159 if (wp_sp)
2160 {
2161 wp_sp->SetHardwareIndex(wp_index);
2162 watch_id = wp_sp->GetID();
2163 }
2164 }
2165 if (watch_id == LLDB_INVALID_WATCH_ID)
2166 {
2167 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2168 if (log) log->Printf ("failed to find watchpoint");
2169 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002170 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002171 handled = true;
2172 }
2173 else if (reason.compare("exception") == 0)
2174 {
2175 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2176 handled = true;
2177 }
2178 else if (reason.compare("exec") == 0)
2179 {
2180 did_exec = true;
2181 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2182 handled = true;
2183 }
2184 }
2185
2186 if (!handled && signo && did_exec == false)
2187 {
2188 if (signo == SIGTRAP)
2189 {
2190 // Currently we are going to assume SIGTRAP means we are either
2191 // hitting a breakpoint or hardware single stepping.
2192 handled = true;
2193 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2194 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2195
2196 if (bp_site_sp)
2197 {
2198 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2199 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2200 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2201 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2202 {
2203 if(m_breakpoint_pc_offset != 0)
2204 thread_sp->GetRegisterContext()->SetPC(pc);
2205 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2206 }
2207 else
2208 {
2209 StopInfoSP invalid_stop_info_sp;
2210 thread_sp->SetStopInfo (invalid_stop_info_sp);
2211 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002212 }
2213 else
2214 {
Greg Clayton2e309072015-07-17 23:42:28 +00002215 // If we were stepping then assume the stop was the result of the trace. If we were
2216 // not stepping then report the SIGTRAP.
2217 // FIXME: We are still missing the case where we single step over a trap instruction.
2218 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2219 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2220 else
2221 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002222 }
2223 }
Greg Clayton2e309072015-07-17 23:42:28 +00002224 if (!handled)
2225 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2226 }
2227
2228 if (!description.empty())
2229 {
2230 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2231 if (stop_info_sp)
2232 {
2233 const char *stop_info_desc = stop_info_sp->GetDescription();
2234 if (!stop_info_desc || !stop_info_desc[0])
2235 stop_info_sp->SetDescription (description.c_str());
2236 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002237 else
2238 {
Greg Clayton2e309072015-07-17 23:42:28 +00002239 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002240 }
2241 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002242 }
2243 }
2244 }
2245 }
2246 return thread_sp;
2247}
2248
Greg Clayton2e309072015-07-17 23:42:28 +00002249lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002250ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2251{
2252 static ConstString g_key_tid("tid");
2253 static ConstString g_key_name("name");
2254 static ConstString g_key_reason("reason");
2255 static ConstString g_key_metype("metype");
2256 static ConstString g_key_medata("medata");
2257 static ConstString g_key_qaddr("qaddr");
Jason Molenda77f89352016-01-12 07:09:16 +00002258 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2259 static ConstString g_key_associated_with_dispatch_queue("associated_with_dispatch_queue");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002260 static ConstString g_key_queue_name("qname");
2261 static ConstString g_key_queue_kind("qkind");
Jason Molenda26d84e82016-01-08 00:20:48 +00002262 static ConstString g_key_queue_serial_number("qserialnum");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002263 static ConstString g_key_registers("registers");
2264 static ConstString g_key_memory("memory");
2265 static ConstString g_key_address("address");
2266 static ConstString g_key_bytes("bytes");
2267 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002268 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002269
2270 // Stop with signal and thread info
2271 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2272 uint8_t signo = 0;
2273 std::string value;
2274 std::string thread_name;
2275 std::string reason;
2276 std::string description;
2277 uint32_t exc_type = 0;
2278 std::vector<addr_t> exc_data;
2279 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2280 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002281 bool queue_vars_valid = false;
Jason Molenda77f89352016-01-12 07:09:16 +00002282 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2283 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002284 std::string queue_name;
2285 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002286 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002287 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2288
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002289 thread_dict->ForEach([this,
2290 &tid,
2291 &expedited_register_map,
2292 &thread_name,
2293 &signo,
2294 &reason,
2295 &description,
2296 &exc_type,
2297 &exc_data,
2298 &thread_dispatch_qaddr,
2299 &queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002300 &associated_with_dispatch_queue,
2301 &dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002302 &queue_name,
2303 &queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002304 &queue_serial_number]
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002305 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002306 {
2307 if (key == g_key_tid)
2308 {
2309 // thread in big endian hex
2310 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2311 }
2312 else if (key == g_key_metype)
2313 {
2314 // exception type in big endian hex
2315 exc_type = object->GetIntegerValue(0);
2316 }
2317 else if (key == g_key_medata)
2318 {
2319 // exception data in big endian hex
2320 StructuredData::Array *array = object->GetAsArray();
2321 if (array)
2322 {
2323 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2324 exc_data.push_back(object->GetIntegerValue());
2325 return true; // Keep iterating through all array items
2326 });
2327 }
2328 }
2329 else if (key == g_key_name)
2330 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002331 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002332 }
2333 else if (key == g_key_qaddr)
2334 {
2335 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2336 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002337 else if (key == g_key_queue_name)
2338 {
2339 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002340 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002341 }
2342 else if (key == g_key_queue_kind)
2343 {
2344 std::string queue_kind_str = object->GetStringValue();
2345 if (queue_kind_str == "serial")
2346 {
2347 queue_vars_valid = true;
2348 queue_kind = eQueueKindSerial;
2349 }
2350 else if (queue_kind_str == "concurrent")
2351 {
2352 queue_vars_valid = true;
2353 queue_kind = eQueueKindConcurrent;
2354 }
2355 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002356 else if (key == g_key_queue_serial_number)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002357 {
Jason Molenda26d84e82016-01-08 00:20:48 +00002358 queue_serial_number = object->GetIntegerValue(0);
2359 if (queue_serial_number != 0)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002360 queue_vars_valid = true;
2361 }
Jason Molenda77f89352016-01-12 07:09:16 +00002362 else if (key == g_key_dispatch_queue_t)
2363 {
2364 dispatch_queue_t = object->GetIntegerValue(0);
2365 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2366 queue_vars_valid = true;
2367 }
2368 else if (key == g_key_associated_with_dispatch_queue)
2369 {
2370 queue_vars_valid = true;
2371 bool associated = object->GetBooleanValue ();
2372 if (associated)
2373 associated_with_dispatch_queue = eLazyBoolYes;
2374 else
2375 associated_with_dispatch_queue = eLazyBoolNo;
2376 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002377 else if (key == g_key_reason)
2378 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002379 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002380 }
2381 else if (key == g_key_description)
2382 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002383 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002384 }
2385 else if (key == g_key_registers)
2386 {
2387 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2388
2389 if (registers_dict)
2390 {
2391 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2392 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2393 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002394 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002395 return true; // Keep iterating through all array items
2396 });
2397 }
2398 }
2399 else if (key == g_key_memory)
2400 {
2401 StructuredData::Array *array = object->GetAsArray();
2402 if (array)
2403 {
2404 array->ForEach([this](StructuredData::Object* object) -> bool {
2405 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2406 if (mem_cache_dict)
2407 {
2408 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2409 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2410 {
2411 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2412 {
2413 StringExtractor bytes;
2414 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2415 {
2416 bytes.SetFilePos(0);
2417
2418 const size_t byte_size = bytes.GetStringRef().size()/2;
2419 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2420 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2421 if (bytes_copied == byte_size)
2422 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2423 }
2424 }
2425 }
2426 }
2427 return true; // Keep iterating through all array items
2428 });
2429 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00002430
Greg Clayton358cf1e2015-06-25 21:46:34 +00002431 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002432 else if (key == g_key_signal)
2433 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002434 return true; // Keep iterating through all dictionary key/value pairs
2435 });
2436
Greg Clayton2e309072015-07-17 23:42:28 +00002437 return SetThreadStopInfo (tid,
2438 expedited_register_map,
2439 signo,
2440 thread_name,
2441 reason,
2442 description,
2443 exc_type,
2444 exc_data,
2445 thread_dispatch_qaddr,
2446 queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002447 associated_with_dispatch_queue,
2448 dispatch_queue_t,
Greg Clayton2e309072015-07-17 23:42:28 +00002449 queue_name,
2450 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002451 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002452}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002453
2454StateType
2455ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2456{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002457 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002458 const char stop_type = stop_packet.GetChar();
2459 switch (stop_type)
2460 {
2461 case 'T':
2462 case 'S':
2463 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002464 // This is a bit of a hack, but is is required. If we did exec, we
2465 // need to clear our thread lists and also know to rebuild our dynamic
2466 // register info before we lookup and threads and populate the expedited
2467 // register values so we need to know this right away so we can cleanup
2468 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002469 const uint32_t stop_id = GetStopID();
2470 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002471 {
2472 // Our first stop, make sure we have a process ID, and also make
2473 // sure we know about our registers
2474 if (GetID() == LLDB_INVALID_PROCESS_ID)
2475 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002476 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002477 if (pid != LLDB_INVALID_PROCESS_ID)
2478 SetID (pid);
2479 }
2480 BuildDynamicRegisterInfo (true);
2481 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002482 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002483 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002484 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002485 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002486 std::string value;
2487 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002488 std::string reason;
2489 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002490 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002491 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002492 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002493 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002494 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2495 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton0b90be12015-06-23 21:27:50 +00002496 std::string queue_name;
2497 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002498 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002499 ExpeditedRegisterMap expedited_register_map;
2500 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002502 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002503 {
2504 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002505 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002506 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002507 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002508 {
2509 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002510 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002511 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002512 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002513 {
2514 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002515 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002516 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002517 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002518 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002519 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002520 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002521 // A comma separated list of all threads in the current
2522 // process that includes the thread for this stop reply
2523 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002524 size_t comma_pos;
2525 lldb::tid_t tid;
2526 while ((comma_pos = value.find(',')) != std::string::npos)
2527 {
2528 value[comma_pos] = '\0';
2529 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002530 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002531 if (tid != LLDB_INVALID_THREAD_ID)
2532 m_thread_ids.push_back (tid);
2533 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002534 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002535 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002536 if (tid != LLDB_INVALID_THREAD_ID)
2537 m_thread_ids.push_back (tid);
2538 }
Jason Molenda545304d2015-12-18 00:45:35 +00002539 else if (key.compare("thread-pcs") == 0)
2540 {
2541 m_thread_pcs.clear();
2542 // A comma separated list of all threads in the current
2543 // process that includes the thread for this stop reply
2544 // packet
2545 size_t comma_pos;
2546 lldb::addr_t pc;
2547 while ((comma_pos = value.find(',')) != std::string::npos)
2548 {
2549 value[comma_pos] = '\0';
2550 // thread in big endian hex
2551 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2552 if (pc != LLDB_INVALID_ADDRESS)
2553 m_thread_pcs.push_back (pc);
2554 value.erase(0, comma_pos + 1);
2555 }
2556 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2557 if (pc != LLDB_INVALID_ADDRESS)
2558 m_thread_pcs.push_back (pc);
2559 }
Greg Clayton2e309072015-07-17 23:42:28 +00002560 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002561 {
2562 StringExtractor json_extractor;
2563 // Swap "value" over into "name_extractor"
2564 json_extractor.GetStringRef().swap(value);
2565 // Now convert the HEX bytes into a string value
2566 json_extractor.GetHexByteString (value);
2567
2568 // This JSON contains thread IDs and thread stop info for all threads.
2569 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002570 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002571 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002572 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002573 {
2574 StringExtractor name_extractor;
2575 // Swap "value" over into "name_extractor"
2576 name_extractor.GetStringRef().swap(value);
2577 // Now convert the HEX bytes into a string value
2578 name_extractor.GetHexByteString (value);
2579 thread_name.swap (value);
2580 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002581 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002582 {
2583 thread_name.swap (value);
2584 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002585 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002586 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002587 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002588 }
Jason Molenda77f89352016-01-12 07:09:16 +00002589 else if (key.compare("dispatch_queue_t") == 0)
2590 {
2591 queue_vars_valid = true;
2592 dispatch_queue_t = StringConvert::ToUInt64 (value.c_str(), 0, 16);
2593 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002594 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002595 {
2596 queue_vars_valid = true;
2597 StringExtractor name_extractor;
2598 // Swap "value" over into "name_extractor"
2599 name_extractor.GetStringRef().swap(value);
2600 // Now convert the HEX bytes into a string value
2601 name_extractor.GetHexByteString (value);
2602 queue_name.swap (value);
2603 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002604 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002605 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002606 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002607 {
2608 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002609 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002610 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002611 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002612 {
2613 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002614 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002615 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002616 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002617 else if (key.compare("qserialnum") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002618 {
Jason Molenda26d84e82016-01-08 00:20:48 +00002619 queue_serial_number = StringConvert::ToUInt64 (value.c_str(), 0, 0);
2620 if (queue_serial_number != 0)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002621 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002622 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002623 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002624 {
2625 reason.swap(value);
2626 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002627 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002628 {
2629 StringExtractor desc_extractor;
2630 // Swap "value" over into "name_extractor"
2631 desc_extractor.GetStringRef().swap(value);
2632 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002633 desc_extractor.GetHexByteString (value);
2634 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002635 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002636 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002637 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002638 // Expedited memory. GDB servers can choose to send back expedited memory
2639 // that can populate the L1 memory cache in the process so that things like
2640 // the frame pointer backchain can be expedited. This will help stack
2641 // backtracing be more efficient by not having to send as many memory read
2642 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002643
Greg Clayton358cf1e2015-06-25 21:46:34 +00002644 // Key/value pair format: memory:<addr>=<bytes>;
2645 // <addr> is a number whose base will be interpreted by the prefix:
2646 // "0x[0-9a-fA-F]+" for hex
2647 // "0[0-7]+" for octal
2648 // "[1-9]+" for decimal
2649 // <bytes> is native endian ASCII hex bytes just like the register values
2650 llvm::StringRef value_ref(value);
2651 std::pair<llvm::StringRef, llvm::StringRef> pair;
2652 pair = value_ref.split('=');
2653 if (!pair.first.empty() && !pair.second.empty())
2654 {
2655 std::string addr_str(pair.first.str());
2656 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2657 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002658 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002659 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002660 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002661 const size_t byte_size = bytes.GetStringRef().size()/2;
2662 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2663 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2664 if (bytes_copied == byte_size)
2665 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002666 }
2667 }
2668 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002669 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2670 {
2671 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2672 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2673 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2674 uint32_t wp_index = LLDB_INVALID_INDEX32;
2675
2676 if (wp_sp)
2677 wp_index = wp_sp->GetHardwareIndex();
2678
2679 reason = "watchpoint";
2680 StreamString ostr;
2681 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2682 description = ostr.GetString().c_str();
2683 }
Stephane Sezer2618e912015-08-21 16:51:56 +00002684 else if (key.compare("library") == 0)
2685 {
2686 LoadModules();
2687 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002688 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2689 {
2690 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2691 if (reg != UINT32_MAX)
2692 expedited_register_map[reg] = std::move(value);
2693 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002695
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002696 if (tid == LLDB_INVALID_THREAD_ID)
2697 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00002698 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002699 // thread information. So update the thread list and choose the first one.
2700 UpdateThreadIDList ();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002701
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002702 if (!m_thread_ids.empty ())
2703 {
2704 tid = m_thread_ids.front ();
2705 }
2706 }
2707
Greg Clayton358cf1e2015-06-25 21:46:34 +00002708 ThreadSP thread_sp = SetThreadStopInfo (tid,
2709 expedited_register_map,
2710 signo,
2711 thread_name,
2712 reason,
2713 description,
2714 exc_type,
2715 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002716 thread_dispatch_qaddr,
2717 queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002718 associated_with_dispatch_queue,
2719 dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002720 queue_name,
2721 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002722 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002723
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724 return eStateStopped;
2725 }
2726 break;
2727
2728 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002729 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002730 // process exited
2731 return eStateExited;
2732
2733 default:
2734 break;
2735 }
2736 return eStateInvalid;
2737}
2738
2739void
2740ProcessGDBRemote::RefreshStateAfterStop ()
2741{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002742 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002743 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00002744 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00002745 // Set the thread stop info. It might have a "threads" key whose value is
2746 // a list of all thread IDs in the current process, so m_thread_ids might
2747 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002748
2749 // Scope for the lock
2750 {
2751 // Lock the thread stack while we access it
2752 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2753 // Get the number of stop packets on the stack
2754 int nItems = m_stop_packet_stack.size();
2755 // Iterate over them
2756 for (int i = 0; i < nItems; i++)
2757 {
2758 // Get the thread stop info
2759 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2760 // Process thread stop info
2761 SetThreadStopInfo(stop_info);
2762 }
2763 // Clear the thread stop stack
2764 m_stop_packet_stack.clear();
2765 }
2766
Greg Clayton9e920902012-04-10 02:25:43 +00002767 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2768 if (m_thread_ids.empty())
2769 {
2770 // No, we need to fetch the thread list manually
2771 UpdateThreadIDList();
2772 }
2773
Ewan Crawford78baa192015-05-13 09:18:18 +00002774 // If we have queried for a default thread id
2775 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2776 {
2777 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2778 m_initial_tid = LLDB_INVALID_THREAD_ID;
2779 }
2780
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002781 // Let all threads recover from stopping and do any clean up based
2782 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002783 m_thread_list_real.RefreshStateAfterStop();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002784
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002785}
2786
2787Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002788ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002789{
2790 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002791
Greg Clayton6ed95942011-01-22 07:12:45 +00002792 bool timed_out = false;
2793 Mutex::Locker locker;
Ed Maste81b4c5f2016-01-04 01:43:47 +00002794
Greg Clayton513c26c2011-01-29 07:10:55 +00002795 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002796 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002797 // We are being asked to halt during an attach. We need to just close
2798 // our file handle and debugserver will go away, and we can be done...
2799 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002800 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002801 else
2802 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002803 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002804 {
2805 if (timed_out)
2806 error.SetErrorString("timed out sending interrupt packet");
2807 else
2808 error.SetErrorString("unknown error sending interrupt packet");
2809 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002810
Greg Clayton2687cd12012-03-29 01:55:41 +00002811 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002812 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813 return error;
2814}
2815
2816Error
Jim Inghamacff8952013-05-02 00:27:30 +00002817ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002818{
2819 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002820 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002821 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002822 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Ed Maste81b4c5f2016-01-04 01:43:47 +00002823
Jim Inghamacff8952013-05-02 00:27:30 +00002824 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002825 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002826 {
Jim Inghamacff8952013-05-02 00:27:30 +00002827 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002828 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2829 else
Jim Inghamacff8952013-05-02 00:27:30 +00002830 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002831 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002832
Jim Inghamacff8952013-05-02 00:27:30 +00002833 if (!error.Success())
2834 return error;
2835
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002836 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002837 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002838
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002839 SetPrivateState (eStateDetached);
2840 ResumePrivateStateThread();
2841
2842 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002843 return error;
2844}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002845
Eugene Zelenko0722f082015-10-24 01:28:05 +00002846
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002847Error
2848ProcessGDBRemote::DoDestroy ()
2849{
2850 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002851 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852 if (log)
2853 log->Printf ("ProcessGDBRemote::DoDestroy()");
2854
Jim Ingham43c555d2012-07-04 00:35:43 +00002855 // There is a bug in older iOS debugservers where they don't shut down the process
2856 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2857 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2858 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2859 // destroy it again.
2860 //
2861 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2862 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2863 // the debugservers with this bug are equal. There really should be a better way to test this!
2864 //
2865 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2866 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2867 // just do the straight-forward kill.
2868 //
2869 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2870 // necessary (or helpful) to do any of this.
2871
2872 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2873 {
2874 PlatformSP platform_sp = GetTarget().GetPlatform();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002875
Jim Ingham43c555d2012-07-04 00:35:43 +00002876 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2877 if (platform_sp
2878 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002879 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002880 {
2881 if (m_destroy_tried_resuming)
2882 {
2883 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002884 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002885 }
2886 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00002887 {
Jim Ingham43c555d2012-07-04 00:35:43 +00002888 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2889 // but we really need it to happen here and it doesn't matter if we do it twice.
2890 m_thread_list.DiscardThreadPlans();
2891 DisableAllBreakpointSites();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002892
Jim Ingham43c555d2012-07-04 00:35:43 +00002893 bool stop_looks_like_crash = false;
2894 ThreadList &threads = GetThreadList();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002895
Jim Ingham43c555d2012-07-04 00:35:43 +00002896 {
Jim Ingham45350372012-09-11 00:08:52 +00002897 Mutex::Locker locker(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002898
Jim Ingham43c555d2012-07-04 00:35:43 +00002899 size_t num_threads = threads.GetSize();
2900 for (size_t i = 0; i < num_threads; i++)
2901 {
2902 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002903 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002904 StopReason reason = eStopReasonInvalid;
2905 if (stop_info_sp)
2906 reason = stop_info_sp->GetStopReason();
2907 if (reason == eStopReasonBreakpoint
2908 || reason == eStopReasonException)
2909 {
2910 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002911 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2912 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002913 stop_info_sp->GetDescription());
2914 stop_looks_like_crash = true;
2915 break;
2916 }
2917 }
2918 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002919
Jim Ingham43c555d2012-07-04 00:35:43 +00002920 if (stop_looks_like_crash)
2921 {
2922 if (log)
2923 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2924 m_destroy_tried_resuming = true;
Ed Maste81b4c5f2016-01-04 01:43:47 +00002925
2926 // If we are going to run again before killing, it would be good to suspend all the threads
Jim Ingham43c555d2012-07-04 00:35:43 +00002927 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2928 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2929 // have to run the risk of letting those threads proceed a bit.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002930
Jim Ingham43c555d2012-07-04 00:35:43 +00002931 {
Jim Ingham45350372012-09-11 00:08:52 +00002932 Mutex::Locker locker(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002933
Jim Ingham43c555d2012-07-04 00:35:43 +00002934 size_t num_threads = threads.GetSize();
2935 for (size_t i = 0; i < num_threads; i++)
2936 {
2937 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002938 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002939 StopReason reason = eStopReasonInvalid;
2940 if (stop_info_sp)
2941 reason = stop_info_sp->GetStopReason();
2942 if (reason != eStopReasonBreakpoint
2943 && reason != eStopReasonException)
2944 {
2945 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002946 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2947 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002948 thread_sp->SetResumeState(eStateSuspended);
2949 }
2950 }
2951 }
2952 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002953 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002954 }
2955 }
2956 }
2957 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002958
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002959 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002960 int exit_status = SIGABRT;
2961 std::string exit_string;
2962
Greg Clayton6ed95942011-01-22 07:12:45 +00002963 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002964 {
Jim Inghamaab78372011-10-28 01:11:35 +00002965 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002966 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002967 StringExtractorGDBRemote response;
2968 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002969 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002970
Greg Clayton3dedae12013-12-06 21:45:27 +00002971 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002972 {
2973 char packet_cmd = response.GetChar(0);
2974
2975 if (packet_cmd == 'W' || packet_cmd == 'X')
2976 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002977#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002978 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2979 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2980 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2981 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2982 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2983 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2984 // Anyway, so call waitpid here to finally reap it.
2985 PlatformSP platform_sp(GetTarget().GetPlatform());
2986 if (platform_sp && platform_sp->IsHost())
2987 {
2988 int status;
2989 ::pid_t reap_pid;
2990 reap_pid = waitpid (GetID(), &status, WNOHANG);
2991 if (log)
2992 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2993 }
2994#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002995 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002996 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002997 exit_status = response.GetHexU8();
2998 }
2999 else
3000 {
3001 if (log)
3002 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
3003 exit_string.assign("got unexpected response to k packet: ");
3004 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00003005 }
3006 }
3007 else
3008 {
Jim Inghambabfc382012-06-06 00:32:39 +00003009 if (log)
3010 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
3011 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00003012 }
Greg Clayton6779606a2011-01-22 23:43:18 +00003013 }
Jim Inghambabfc382012-06-06 00:32:39 +00003014 else
3015 {
3016 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00003017 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00003018 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00003019 }
Greg Clayton6779606a2011-01-22 23:43:18 +00003020 }
Jim Inghambabfc382012-06-06 00:32:39 +00003021 else
3022 {
3023 // If we missed setting the exit status on the way out, do it here.
3024 // NB set exit status can be called multiple times, the first one sets the status.
3025 exit_string.assign("destroying when not connected to debugserver");
3026 }
3027
3028 SetExitStatus(exit_status, exit_string.c_str());
3029
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003030 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003031 KillDebugserverProcess ();
3032 return error;
3033}
3034
Greg Clayton8cda7f02013-05-21 21:55:59 +00003035void
3036ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
3037{
Greg Clayton8cda7f02013-05-21 21:55:59 +00003038 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
3039 if (did_exec)
3040 {
3041 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3042 if (log)
3043 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
3044
3045 m_thread_list_real.Clear();
3046 m_thread_list.Clear();
3047 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00003048 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00003049 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00003050
3051 // Scope the lock
3052 {
3053 // Lock the thread stack while we access it
3054 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00003055
3056 // We are are not using non-stop mode, there can only be one last stop
3057 // reply packet, so clear the list.
3058 if (GetTarget().GetNonStopModeEnabled() == false)
3059 m_stop_packet_stack.clear();
3060
Ewan Crawford9aa2da002015-05-27 14:12:34 +00003061 // Add this stop packet to the stop packet stack
3062 // This stack will get popped and examined when we switch to the
3063 // Stopped state
3064 m_stop_packet_stack.push_back(response);
3065 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00003066}
3067
Chaoren Linc963a222015-09-01 16:58:45 +00003068void
3069ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
3070{
3071 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
3072}
3073
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003074//------------------------------------------------------------------
3075// Process Queries
3076//------------------------------------------------------------------
3077
3078bool
3079ProcessGDBRemote::IsAlive ()
3080{
Jason Molenda1d3b3562015-11-05 23:54:29 +00003081 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003082}
3083
3084addr_t
3085ProcessGDBRemote::GetImageInfoAddress()
3086{
Aidan Doddsc0c83852015-05-08 09:36:31 +00003087 // request the link map address via the $qShlibInfoAddr packet
3088 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
3089
3090 // the loaded module list can also provides a link map address
3091 if (addr == LLDB_INVALID_ADDRESS)
3092 {
3093 GDBLoadedModuleInfoList list;
3094 if (GetLoadedModuleList (list).Success())
3095 addr = list.m_link_map;
3096 }
3097
3098 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003099}
3100
Greg Clayton2e309072015-07-17 23:42:28 +00003101void
3102ProcessGDBRemote::WillPublicStop ()
3103{
3104 // See if the GDB remote client supports the JSON threads info.
3105 // If so, we gather stop info for all threads, expedited registers,
3106 // expedited memory, runtime queue information (iOS and MacOSX only),
3107 // and more. Expediting memory will help stack backtracing be much
3108 // faster. Expediting registers will make sure we don't have to read
3109 // the thread registers for GPRs.
3110 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
3111
3112 if (m_jthreadsinfo_sp)
3113 {
3114 // Now set the stop info for each thread and also expedite any registers
3115 // and memory that was in the jThreadsInfo response.
3116 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
3117 if (thread_infos)
3118 {
3119 const size_t n = thread_infos->GetSize();
3120 for (size_t i=0; i<n; ++i)
3121 {
3122 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
3123 if (thread_dict)
3124 SetThreadStopInfo(thread_dict);
3125 }
3126 }
3127 }
3128}
3129
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003130//------------------------------------------------------------------
3131// Process Memory
3132//------------------------------------------------------------------
3133size_t
3134ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
3135{
Jason Molenda6076bf42014-05-06 04:34:52 +00003136 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003137 if (size > m_max_memory_size)
3138 {
3139 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003140 // called multiple times in order to complete the task by
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003141 // lldb_private::Process so it is ok to do this.
3142 size = m_max_memory_size;
3143 }
3144
3145 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00003146 int packet_len;
3147 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
Pavel Labath3bf11252015-10-14 12:59:37 +00003148 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
3149 binary_memory_read ? 'x' : 'm', (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00003150 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003151 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003152 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003153 {
Greg Clayton576d8832011-03-22 04:00:09 +00003154 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003155 {
3156 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00003157 if (binary_memory_read)
3158 {
3159 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3160 // 0x7d character escaping that was present in the packet
3161
3162 size_t data_received_size = response.GetBytesLeft();
3163 if (data_received_size > size)
3164 {
3165 // Don't write past the end of BUF if the remote debug server gave us too
3166 // much data for some reason.
3167 data_received_size = size;
3168 }
3169 memcpy (buf, response.GetStringRef().data(), data_received_size);
3170 return data_received_size;
3171 }
3172 else
3173 {
3174 return response.GetHexBytes(buf, size, '\xdd');
3175 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003176 }
Greg Clayton576d8832011-03-22 04:00:09 +00003177 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003178 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003179 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003180 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003181 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003182 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003183 }
3184 else
3185 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003186 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003187 }
3188 return 0;
3189}
3190
3191size_t
3192ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3193{
Jason Molenda6076bf42014-05-06 04:34:52 +00003194 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003195 if (size > m_max_memory_size)
3196 {
3197 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003198 // called multiple times in order to complete the task by
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003199 // lldb_private::Process so it is ok to do this.
3200 size = m_max_memory_size;
3201 }
3202
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003203 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003204 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00003205 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003206 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003207 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003208 {
Greg Clayton576d8832011-03-22 04:00:09 +00003209 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003210 {
3211 error.Clear();
3212 return size;
3213 }
Greg Clayton576d8832011-03-22 04:00:09 +00003214 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003215 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003216 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003217 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003218 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003219 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 +00003220 }
3221 else
3222 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003223 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003224 }
3225 return 0;
3226}
3227
3228lldb::addr_t
3229ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3230{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003231 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003232 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003233
Greg Clayton70b57652011-05-15 01:25:55 +00003234 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003235 switch (supported)
3236 {
3237 case eLazyBoolCalculate:
3238 case eLazyBoolYes:
3239 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3240 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3241 return allocated_addr;
3242
3243 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003244 // Call mmap() to create memory in the inferior..
3245 unsigned prot = 0;
3246 if (permissions & lldb::ePermissionsReadable)
3247 prot |= eMmapProtRead;
3248 if (permissions & lldb::ePermissionsWritable)
3249 prot |= eMmapProtWrite;
3250 if (permissions & lldb::ePermissionsExecutable)
3251 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003252
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003253 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3254 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3255 m_addr_to_mmap_size[allocated_addr] = size;
3256 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003257 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003258 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003259 if (log)
3260 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3261 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003262 break;
3263 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003264
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003265 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003266 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003267 else
3268 error.Clear();
3269 return allocated_addr;
3270}
3271
3272Error
Ed Maste81b4c5f2016-01-04 01:43:47 +00003273ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
Greg Clayton46fb5582011-11-18 07:03:08 +00003274 MemoryRegionInfo &region_info)
3275{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003276
Greg Clayton46fb5582011-11-18 07:03:08 +00003277 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3278 return error;
3279}
3280
3281Error
Johnny Chen64637202012-05-23 21:09:52 +00003282ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3283{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003284
Johnny Chen64637202012-05-23 21:09:52 +00003285 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3286 return error;
3287}
3288
3289Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003290ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3291{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003292 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003293 return error;
3294}
3295
3296Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003297ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3298{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003299 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003300 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3301
3302 switch (supported)
3303 {
3304 case eLazyBoolCalculate:
Ed Maste81b4c5f2016-01-04 01:43:47 +00003305 // We should never be deallocating memory without allocating memory
Greg Clayton70b57652011-05-15 01:25:55 +00003306 // first so we should never get eLazyBoolCalculate
3307 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3308 break;
3309
3310 case eLazyBoolYes:
3311 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003312 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003313 break;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003314
Greg Clayton70b57652011-05-15 01:25:55 +00003315 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003316 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003317 {
3318 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003319 if (pos != m_addr_to_mmap_size.end() &&
3320 InferiorCallMunmap(this, addr, pos->second))
3321 m_addr_to_mmap_size.erase (pos);
3322 else
Daniel Malead01b2952012-11-29 21:49:15 +00003323 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003324 }
3325 break;
3326 }
3327
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003328 return error;
3329}
3330
Eugene Zelenko0722f082015-10-24 01:28:05 +00003331
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003332//------------------------------------------------------------------
3333// Process STDIO
3334//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003335size_t
3336ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3337{
3338 if (m_stdio_communication.IsConnected())
3339 {
3340 ConnectionStatus status;
3341 m_stdio_communication.Write(src, src_len, status, NULL);
3342 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003343 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003344 {
3345 m_gdb_comm.SendStdinNotification(src, src_len);
3346 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003347 return 0;
3348}
3349
3350Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003351ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003352{
3353 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003354 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003355
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003356 // Get logging info
3357 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003358 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003359
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003360 // Get the breakpoint address
3361 const addr_t addr = bp_site->GetLoadAddress();
3362
3363 // Log that a breakpoint was requested
3364 if (log)
3365 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3366
3367 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003368 if (bp_site->IsEnabled())
3369 {
3370 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003371 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 +00003372 return error;
3373 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003374
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003375 // Get the software breakpoint trap opcode size
3376 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3377
3378 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3379 // is supported by the remote stub. These are set to true by default, and later set to false
3380 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3381 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3382 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3383 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3384 // skip over software breakpoints.
3385 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3386 {
3387 // Try to send off a software breakpoint packet ($Z0)
3388 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003389 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003390 // The breakpoint was placed successfully
3391 bp_site->SetEnabled(true);
3392 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003393 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003394 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003395
3396 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3397 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3398 // or if we have learned that this breakpoint type is unsupported. To do this, we
3399 // must test the support boolean for this breakpoint type to see if it now indicates that
3400 // this breakpoint type is unsupported. If they are still supported then we should return
3401 // with the error code. If they are now unsupported, then we would like to fall through
3402 // and try another form of breakpoint.
3403 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3404 return error;
3405
3406 // We reach here when software breakpoints have been found to be unsupported. For future
3407 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3408 // known not to be supported.
3409 if (log)
3410 log->Printf("Software breakpoints are unsupported");
3411
3412 // So we will fall through and try a hardware breakpoint
3413 }
3414
3415 // The process of setting a hardware breakpoint is much the same as above. We check the
3416 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3417 // will try to set this breakpoint with a hardware breakpoint.
3418 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3419 {
3420 // Try to send off a hardware breakpoint packet ($Z1)
3421 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003422 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003423 // The breakpoint was placed successfully
3424 bp_site->SetEnabled(true);
3425 bp_site->SetType(BreakpointSite::eHardware);
3426 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003427 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003428
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003429 // Check if the error was something other then an unsupported breakpoint type
3430 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3431 {
3432 // Unable to set this hardware breakpoint
3433 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3434 return error;
3435 }
3436
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003437 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003438 if (log)
3439 log->Printf("Hardware breakpoints are unsupported");
3440
3441 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003442 }
3443
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003444 // Don't fall through when hardware breakpoints were specifically requested
3445 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003446 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003447 error.SetErrorString("hardware breakpoints are not supported");
3448 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003449 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003450
3451 // As a last resort we want to place a manual breakpoint. An instruction
3452 // is placed into the process memory using memory write packets.
3453 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003454}
3455
3456Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003457ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003458{
3459 Error error;
3460 assert (bp_site != NULL);
3461 addr_t addr = bp_site->GetLoadAddress();
3462 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003463 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003464 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003465 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003466
3467 if (bp_site->IsEnabled())
3468 {
3469 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3470
Greg Clayton8b82f082011-04-12 05:54:46 +00003471 BreakpointSite::Type bp_type = bp_site->GetType();
3472 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003473 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003474 case BreakpointSite::eSoftware:
3475 error = DisableSoftwareBreakpoint (bp_site);
3476 break;
3477
3478 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003479 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003480 error.SetErrorToGenericError();
3481 break;
3482
3483 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003484 {
3485 GDBStoppointType stoppoint_type;
3486 if (bp_site->IsHardware())
3487 stoppoint_type = eBreakpointHardware;
3488 else
3489 stoppoint_type = eBreakpointSoftware;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003490
Jim Inghama04ef752014-03-07 11:18:02 +00003491 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003492 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003493 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003494 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003495 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003496 if (error.Success())
3497 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003498 }
3499 else
3500 {
3501 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003502 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 +00003503 return error;
3504 }
3505
3506 if (error.Success())
3507 error.SetErrorToGenericError();
3508 return error;
3509}
3510
Johnny Chen11309a32011-09-06 22:38:36 +00003511// Pre-requisite: wp != NULL.
3512static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003513GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003514{
3515 assert(wp);
3516 bool watch_read = wp->WatchpointRead();
3517 bool watch_write = wp->WatchpointWrite();
3518
3519 // watch_read and watch_write cannot both be false.
3520 assert(watch_read || watch_write);
3521 if (watch_read && watch_write)
3522 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003523 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003524 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003525 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003526 return eWatchpointWrite;
3527}
3528
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003529Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003530ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003531{
3532 Error error;
3533 if (wp)
3534 {
3535 user_id_t watchID = wp->GetID();
3536 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003537 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003538 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003539 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003540 if (wp->IsEnabled())
3541 {
3542 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003543 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 +00003544 return error;
3545 }
Johnny Chen11309a32011-09-06 22:38:36 +00003546
3547 GDBStoppointType type = GetGDBStoppointType(wp);
3548 // Pass down an appropriate z/Z packet...
3549 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003550 {
Johnny Chen11309a32011-09-06 22:38:36 +00003551 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3552 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003553 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003554 return error;
3555 }
3556 else
3557 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003558 }
Johnny Chen11309a32011-09-06 22:38:36 +00003559 else
3560 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003561 }
3562 else
3563 {
Johnny Chen01a67862011-10-14 00:42:25 +00003564 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003565 }
3566 if (error.Success())
3567 error.SetErrorToGenericError();
3568 return error;
3569}
3570
3571Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003572ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003573{
3574 Error error;
3575 if (wp)
3576 {
3577 user_id_t watchID = wp->GetID();
3578
Greg Clayton5160ce52013-03-27 23:08:40 +00003579 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003580
3581 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003582
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003583 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003584 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003585
Johnny Chen11309a32011-09-06 22:38:36 +00003586 if (!wp->IsEnabled())
3587 {
3588 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003589 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 +00003590 // See also 'class WatchpointSentry' within StopInfo.cpp.
3591 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3592 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003593 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003594 return error;
3595 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003596
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003597 if (wp->IsHardware())
3598 {
Johnny Chen11309a32011-09-06 22:38:36 +00003599 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003600 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003601 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3602 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003603 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003604 return error;
3605 }
3606 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00003607 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003608 }
3609 // TODO: clear software watchpoints if we implement them
3610 }
3611 else
3612 {
Johnny Chen01a67862011-10-14 00:42:25 +00003613 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003614 }
3615 if (error.Success())
3616 error.SetErrorToGenericError();
3617 return error;
3618}
3619
3620void
3621ProcessGDBRemote::Clear()
3622{
3623 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003624 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003625 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003626}
3627
3628Error
3629ProcessGDBRemote::DoSignal (int signo)
3630{
3631 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003632 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003633 if (log)
3634 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3635
3636 if (!m_gdb_comm.SendAsyncSignal (signo))
3637 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3638 return error;
3639}
3640
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003641Error
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003642ProcessGDBRemote::EstablishConnectionIfNeeded (const ProcessInfo &process_info)
3643{
3644 // Make sure we aren't already connected?
3645 if (m_gdb_comm.IsConnected())
3646 return Error();
3647
3648 PlatformSP platform_sp (GetTarget ().GetPlatform ());
3649 if (platform_sp && !platform_sp->IsHost ())
3650 return Error("Lost debug server connection");
3651
3652 auto error = LaunchAndConnectToDebugserver (process_info);
3653 if (error.Fail())
3654 {
3655 const char *error_string = error.AsCString();
3656 if (error_string == nullptr)
3657 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3658 }
3659 return error;
3660}
3661
3662Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003663ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003664{
3665 Error error;
3666 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3667 {
3668 // If we locate debugserver, keep that located version around
3669 static FileSpec g_debugserver_file_spec;
3670
Han Ming Ong84647042012-02-25 01:07:38 +00003671 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003672 // Make debugserver run in its own session so signals generated by
3673 // special terminal key sequences (^C) don't affect debugserver.
3674 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3675
Greg Clayton91a9b2472013-12-04 19:19:12 +00003676 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3677 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003678
Todd Fiala013434e2014-07-09 01:29:05 +00003679#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003680 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003681 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003682 uint16_t port = get_random_port ();
3683#else
3684 // Set hostname being NULL to do the reverse connect where debugserver
3685 // will bind to port zero and it will communicate back to us the port
3686 // that we will connect to
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003687 const char *hostname = nullptr;
Greg Claytonfda4fab2014-01-10 22:24:11 +00003688 uint16_t port = 0;
3689#endif
3690
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003691 StreamString url_str;
3692 const char* url = nullptr;
3693 if (hostname != nullptr)
3694 {
3695 url_str.Printf("%s:%u", hostname, port);
3696 url = url_str.GetData();
3697 }
3698
3699 error = m_gdb_comm.StartDebugserverProcess (url,
Greg Clayton6988abc2015-10-19 20:44:01 +00003700 GetTarget().GetPlatform().get(),
Greg Clayton00fe87b2013-12-05 22:58:22 +00003701 debugserver_launch_info,
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003702 &port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003703
3704 if (error.Success ())
3705 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003706 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003707 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003708
3709 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3710 StartAsyncThread ();
Ed Maste81b4c5f2016-01-04 01:43:47 +00003711
Greg Clayton91a9b2472013-12-04 19:19:12 +00003712 if (error.Fail())
3713 {
3714 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3715
3716 if (log)
3717 log->Printf("failed to start debugserver process: %s", error.AsCString());
3718 return error;
3719 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003720
Greg Clayton00fe87b2013-12-05 22:58:22 +00003721 if (m_gdb_comm.IsConnected())
3722 {
3723 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3724 ConnectToDebugserver (NULL);
3725 }
3726 else
3727 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003728 StreamString connect_url;
3729 connect_url.Printf("connect://%s:%u", hostname, port);
3730 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003731 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003732
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003733 }
3734 return error;
3735}
3736
3737bool
3738ProcessGDBRemote::MonitorDebugserverProcess
3739(
3740 void *callback_baton,
3741 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003742 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003743 int signo, // Zero for no signal
3744 int exit_status // Exit value of process if signal is zero
3745)
3746{
Greg Claytone4e45922011-11-16 05:37:56 +00003747 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3748 // and might not exist anymore, so we need to carefully try to get the
3749 // target for this process first since we have a race condition when
Ed Maste81b4c5f2016-01-04 01:43:47 +00003750 // we are done running between getting the notice that the inferior
Greg Claytone4e45922011-11-16 05:37:56 +00003751 // process has died and the debugserver that was debugging this process.
3752 // In our test suite, we are also continually running process after
3753 // process, so we must be very careful to make sure:
3754 // 1 - process object hasn't been deleted already
3755 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003756
3757 // "debugserver_pid" argument passed in is the process ID for
3758 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003759 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003760
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003761 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003762
Greg Claytone4e45922011-11-16 05:37:56 +00003763 // Get a shared pointer to the target that has a matching process pointer.
3764 // This target could be gone, or the target could already have a new process
3765 // object inside of it
3766 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3767
Greg Clayton6779606a2011-01-22 23:43:18 +00003768 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003769 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 +00003770
Greg Claytone4e45922011-11-16 05:37:56 +00003771 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003772 {
Greg Claytone4e45922011-11-16 05:37:56 +00003773 // We found a process in a target that matches, but another thread
3774 // might be in the process of launching a new process that will
3775 // soon replace it, so get a shared pointer to the process so we
3776 // can keep it alive.
3777 ProcessSP process_sp (target_sp->GetProcessSP());
3778 // Now we have a shared pointer to the process that can't go away on us
3779 // so we now make sure it was the same as the one passed in, and also make
Ed Maste81b4c5f2016-01-04 01:43:47 +00003780 // sure that our previous "process *" didn't get deleted and have a new
Greg Claytone4e45922011-11-16 05:37:56 +00003781 // "process *" created in its place with the same pointer. To verify this
3782 // we make sure the process has our debugserver process ID. If we pass all
3783 // of these tests, then we are sure that this process is the one we were
3784 // looking for.
3785 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003786 {
Greg Claytone4e45922011-11-16 05:37:56 +00003787 // Sleep for a half a second to make sure our inferior process has
3788 // time to set its exit status before we set it incorrectly when
3789 // both the debugserver and the inferior process shut down.
3790 usleep (500000);
3791 // If our process hasn't yet exited, debugserver might have died.
3792 // If the process did exit, the we are reaping it.
3793 const StateType state = process->GetState();
Ed Maste81b4c5f2016-01-04 01:43:47 +00003794
Greg Claytone4e45922011-11-16 05:37:56 +00003795 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3796 state != eStateInvalid &&
3797 state != eStateUnloaded &&
3798 state != eStateExited &&
3799 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003800 {
Greg Claytone4e45922011-11-16 05:37:56 +00003801 char error_str[1024];
3802 if (signo)
3803 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003804 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003805 if (signal_cstr)
3806 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3807 else
3808 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3809 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003810 else
Greg Claytone4e45922011-11-16 05:37:56 +00003811 {
3812 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3813 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003814
Greg Claytone4e45922011-11-16 05:37:56 +00003815 process->SetExitStatus (-1, error_str);
3816 }
3817 // Debugserver has exited we need to let our ProcessGDBRemote
3818 // know that it no longer has a debugserver instance
3819 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003820 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003821 }
3822 return true;
3823}
3824
3825void
3826ProcessGDBRemote::KillDebugserverProcess ()
3827{
Greg Claytonfbb76342013-11-20 21:07:01 +00003828 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003829 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3830 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003831 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003832 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3833 }
3834}
3835
3836void
3837ProcessGDBRemote::Initialize()
3838{
Davide Italianoc8d69822015-04-03 04:24:32 +00003839 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003840
Davide Italianoc8d69822015-04-03 04:24:32 +00003841 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003842 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003843 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3844 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003845 CreateInstance,
3846 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003847 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003848}
3849
Greg Clayton7f982402013-07-15 22:54:20 +00003850void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003851ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003852{
3853 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3854 {
3855 const bool is_global_setting = true;
3856 PluginManager::CreateSettingForProcessPlugin (debugger,
3857 GetGlobalPluginProperties()->GetValueProperties(),
3858 ConstString ("Properties for the gdb-remote process plug-in."),
3859 is_global_setting);
3860 }
3861}
3862
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003863bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003864ProcessGDBRemote::StartAsyncThread ()
3865{
Greg Clayton5160ce52013-03-27 23:08:40 +00003866 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003867
3868 if (log)
3869 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003870
Jim Ingham455fa5c2012-11-01 01:15:33 +00003871 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003872 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003873 {
3874 // Create a thread that watches our internal state and controls which
3875 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003876
3877 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003878 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003879 else if (log)
3880 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003881
Zachary Turneracee96a2014-09-23 18:32:09 +00003882 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003883}
3884
3885void
3886ProcessGDBRemote::StopAsyncThread ()
3887{
Greg Clayton5160ce52013-03-27 23:08:40 +00003888 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003889
3890 if (log)
3891 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3892
Jim Ingham455fa5c2012-11-01 01:15:33 +00003893 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003894 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003895 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003896 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003897
Jim Ingham455fa5c2012-11-01 01:15:33 +00003898 // This will shut down the async thread.
3899 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3900
3901 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003902 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003903 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003904 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003905 else if (log)
3906 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003907}
3908
Ewan Crawford76df2882015-06-23 12:32:06 +00003909bool
3910ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3911{
3912 // get the packet at a string
3913 const std::string &pkt = packet.GetStringRef();
3914 // skip %stop:
3915 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3916
3917 // pass as a thread stop info packet
3918 SetLastStopPacket(stop_info);
3919
3920 // check for more stop reasons
3921 HandleStopReplySequence();
3922
3923 // if the process is stopped then we need to fake a resume
3924 // so that we can stop properly with the new break. This
3925 // is possible due to SetPrivateState() broadcasting the
3926 // state change as a side effect.
3927 if (GetPrivateState() == lldb::StateType::eStateStopped)
3928 {
3929 SetPrivateState(lldb::StateType::eStateRunning);
3930 }
3931
3932 // since we have some stopped packets we can halt the process
3933 SetPrivateState(lldb::StateType::eStateStopped);
3934
3935 return true;
3936}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003937
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003938thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003939ProcessGDBRemote::AsyncThread (void *arg)
3940{
3941 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3942
Greg Clayton5160ce52013-03-27 23:08:40 +00003943 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003944 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003945 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003946
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003947 EventSP event_sp;
Pavel Labath50556852015-09-03 09:36:22 +00003948 bool done = false;
3949 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003950 {
Pavel Labath50556852015-09-03 09:36:22 +00003951 if (log)
3952 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
3953 if (process->m_async_listener.WaitForEvent (NULL, event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003954 {
Pavel Labath50556852015-09-03 09:36:22 +00003955 const uint32_t event_type = event_sp->GetType();
3956 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003957 {
3958 if (log)
Pavel Labath50556852015-09-03 09:36:22 +00003959 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3960
3961 switch (event_type)
3962 {
3963 case eBroadcastBitAsyncContinue:
3964 {
3965 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3966
3967 if (continue_packet)
3968 {
3969 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3970 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3971 if (log)
3972 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3973
3974 if (::strstr (continue_cstr, "vAttach") == NULL)
3975 process->SetPrivateState(eStateRunning);
3976 StringExtractorGDBRemote response;
3977
3978 // If in Non-Stop-Mode
3979 if (process->GetTarget().GetNonStopModeEnabled())
3980 {
3981 // send the vCont packet
3982 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
3983 {
3984 // Something went wrong
3985 done = true;
3986 break;
3987 }
3988 }
3989 // If in All-Stop-Mode
3990 else
3991 {
3992 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3993
3994 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3995 // The thread ID list might be contained within the "response", or the stop reply packet that
3996 // caused the stop. So clear it now before we give the stop reply packet to the process
3997 // using the process->SetLastStopPacket()...
3998 process->ClearThreadIDList ();
3999
4000 switch (stop_state)
4001 {
4002 case eStateStopped:
4003 case eStateCrashed:
4004 case eStateSuspended:
4005 process->SetLastStopPacket (response);
4006 process->SetPrivateState (stop_state);
4007 break;
4008
4009 case eStateExited:
4010 {
4011 process->SetLastStopPacket (response);
4012 process->ClearThreadIDList();
4013 response.SetFilePos(1);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004014
Pavel Labath50556852015-09-03 09:36:22 +00004015 int exit_status = response.GetHexU8();
4016 const char *desc_cstr = NULL;
4017 StringExtractor extractor;
4018 std::string desc_string;
4019 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
4020 {
4021 std::string desc_token;
4022 while (response.GetNameColonValue (desc_token, desc_string))
4023 {
4024 if (desc_token == "description")
4025 {
4026 extractor.GetStringRef().swap(desc_string);
4027 extractor.SetFilePos(0);
4028 extractor.GetHexByteString (desc_string);
4029 desc_cstr = desc_string.c_str();
4030 }
4031 }
4032 }
4033 process->SetExitStatus(exit_status, desc_cstr);
4034 done = true;
4035 break;
4036 }
4037 case eStateInvalid:
4038 {
4039 // Check to see if we were trying to attach and if we got back
4040 // the "E87" error code from debugserver -- this indicates that
4041 // the process is not debuggable. Return a slightly more helpful
4042 // error message about why the attach failed.
4043 if (::strstr (continue_cstr, "vAttach") != NULL
4044 && response.GetError() == 0x87)
4045 {
4046 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
4047 }
4048 // E01 code from vAttach means that the attach failed
4049 if (::strstr (continue_cstr, "vAttach") != NULL
4050 && response.GetError() == 0x1)
4051 {
4052 process->SetExitStatus(-1, "unable to attach");
4053 }
4054 else
4055 {
4056 process->SetExitStatus(-1, "lost connection");
4057 }
4058 break;
4059 }
4060
4061 default:
4062 process->SetPrivateState (stop_state);
4063 break;
4064 } // switch(stop_state)
4065 } // else // if in All-stop-mode
4066 } // if (continue_packet)
4067 } // case eBroadcastBitAysncContinue
4068 break;
4069
4070 case eBroadcastBitAsyncThreadShouldExit:
4071 if (log)
4072 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
4073 done = true;
4074 break;
4075
4076 default:
4077 if (log)
4078 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4079 done = true;
4080 break;
4081 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004082 }
Pavel Labath50556852015-09-03 09:36:22 +00004083 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
4084 {
4085 switch (event_type)
4086 {
4087 case Communication::eBroadcastBitReadThreadDidExit:
4088 process->SetExitStatus (-1, "lost connection");
4089 done = true;
4090 break;
4091
4092 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
4093 {
4094 lldb_private::Event *event = event_sp.get();
4095 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
4096 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
4097 // Hand this over to the process to handle
4098 process->HandleNotifyPacket(notify);
4099 break;
4100 }
4101
4102 default:
4103 if (log)
4104 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4105 done = true;
4106 break;
4107 }
4108 }
4109 }
4110 else
4111 {
4112 if (log)
4113 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
4114 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004115 }
4116 }
4117
4118 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004119 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004120
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004121 return NULL;
4122}
4123
Greg Claytone996fd32011-03-08 22:40:15 +00004124//uint32_t
4125//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4126//{
4127// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
4128// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
4129// if (m_local_debugserver)
4130// {
4131// return Host::ListProcessesMatchingName (name, matches, pids);
4132// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004133// else
Greg Claytone996fd32011-03-08 22:40:15 +00004134// {
4135// // FIXME: Implement talking to the remote debugserver.
4136// return 0;
4137// }
4138//
4139//}
4140//
Jim Ingham1c823b42011-01-22 01:33:44 +00004141bool
4142ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004143 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00004144 lldb::user_id_t break_id,
4145 lldb::user_id_t break_loc_id)
4146{
Ed Maste81b4c5f2016-01-04 01:43:47 +00004147 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
Jim Ingham1c823b42011-01-22 01:33:44 +00004148 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004149 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00004150 if (log)
4151 log->Printf("Hit New Thread Notification breakpoint.");
4152 return false;
4153}
4154
Eugene Zelenko0722f082015-10-24 01:28:05 +00004155
Jim Ingham1c823b42011-01-22 01:33:44 +00004156bool
4157ProcessGDBRemote::StartNoticingNewThreads()
4158{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004159 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00004160 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004161 {
Greg Clayton4116e932012-05-15 02:33:01 +00004162 if (log && log->GetVerbose())
4163 log->Printf("Enabled noticing new thread breakpoint.");
4164 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004165 }
Greg Clayton4116e932012-05-15 02:33:01 +00004166 else
Jim Ingham1c823b42011-01-22 01:33:44 +00004167 {
Zachary Turner7529df92015-09-01 20:02:29 +00004168 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Clayton4116e932012-05-15 02:33:01 +00004169 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004170 {
Zachary Turner7529df92015-09-01 20:02:29 +00004171 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget());
Greg Clayton4116e932012-05-15 02:33:01 +00004172 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004173 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004174 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00004175 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4176 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004177 }
4178 else
4179 {
4180 if (log)
4181 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00004182 }
4183 }
4184 }
Greg Clayton4116e932012-05-15 02:33:01 +00004185 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004186}
4187
4188bool
4189ProcessGDBRemote::StopNoticingNewThreads()
Ed Maste81b4c5f2016-01-04 01:43:47 +00004190{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004191 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004192 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004193 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004194
4195 if (m_thread_create_bp_sp)
4196 m_thread_create_bp_sp->SetEnabled(false);
4197
Jim Ingham1c823b42011-01-22 01:33:44 +00004198 return true;
4199}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004200
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004201DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004202ProcessGDBRemote::GetDynamicLoader ()
4203{
4204 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004205 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004206 return m_dyld_ap.get();
4207}
Jim Ingham1c823b42011-01-22 01:33:44 +00004208
Jason Molendaa3329782014-03-29 18:54:20 +00004209Error
4210ProcessGDBRemote::SendEventData(const char *data)
4211{
4212 int return_value;
4213 bool was_supported;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004214
Jason Molendaa3329782014-03-29 18:54:20 +00004215 Error error;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004216
Jason Molendaa3329782014-03-29 18:54:20 +00004217 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4218 if (return_value != 0)
4219 {
4220 if (!was_supported)
4221 error.SetErrorString("Sending events is not supported for this process.");
4222 else
4223 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4224 }
4225 return error;
4226}
4227
Steve Pucci03904ac2014-03-04 23:18:46 +00004228const DataBufferSP
4229ProcessGDBRemote::GetAuxvData()
4230{
4231 DataBufferSP buf;
4232 if (m_gdb_comm.GetQXferAuxvReadSupported())
4233 {
4234 std::string response_string;
4235 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4236 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4237 }
4238 return buf;
4239}
4240
Jason Molenda705b1802014-06-13 02:37:02 +00004241StructuredData::ObjectSP
4242ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4243{
4244 StructuredData::ObjectSP object_sp;
4245
4246 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4247 {
4248 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4249 SystemRuntime *runtime = GetSystemRuntime();
4250 if (runtime)
4251 {
4252 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4253 }
4254 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4255
4256 StreamString packet;
4257 packet << "jThreadExtendedInfo:";
4258 args_dict->Dump (packet);
4259
4260 // FIXME the final character of a JSON dictionary, '}', is the escape
4261 // character in gdb-remote binary mode. lldb currently doesn't escape
4262 // these characters in its packet output -- so we add the quoted version
4263 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004264 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004265 packet << (char) (0x7d ^ 0x20);
4266
4267 StringExtractorGDBRemote response;
4268 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4269 {
4270 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4271 if (response_type == StringExtractorGDBRemote::eResponse)
4272 {
4273 if (!response.Empty())
4274 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004275 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4276 }
4277 }
4278 }
4279 }
4280 return object_sp;
4281}
4282
4283StructuredData::ObjectSP
4284ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4285{
4286 StructuredData::ObjectSP object_sp;
4287
4288 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4289 {
Jason Molenda1d3b3562015-11-05 23:54:29 +00004290 // Scope for the scoped timeout object
4291 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
4292
Jason Molenda20ee21b2015-07-10 23:15:22 +00004293 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4294 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4295 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4296
4297 StreamString packet;
4298 packet << "jGetLoadedDynamicLibrariesInfos:";
4299 args_dict->Dump (packet);
4300
4301 // FIXME the final character of a JSON dictionary, '}', is the escape
4302 // character in gdb-remote binary mode. lldb currently doesn't escape
4303 // these characters in its packet output -- so we add the quoted version
4304 // of the } character here manually in case we talk to a debugserver which
4305 // un-escapes the characters at packet read time.
4306 packet << (char) (0x7d ^ 0x20);
4307
4308 StringExtractorGDBRemote response;
4309 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4310 {
4311 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4312 if (response_type == StringExtractorGDBRemote::eResponse)
4313 {
4314 if (!response.Empty())
4315 {
Jason Molenda705b1802014-06-13 02:37:02 +00004316 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4317 }
4318 }
4319 }
4320 }
4321 return object_sp;
4322}
4323
Jason Molenda6076bf42014-05-06 04:34:52 +00004324// Establish the largest memory read/write payloads we should use.
4325// If the remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004326//
4327// If the remote stub's max packet size is crazy large, use a
Jason Molenda6076bf42014-05-06 04:34:52 +00004328// reasonable largeish default.
4329//
4330// If the remote stub doesn't advertise a max packet size, use a
4331// conservative default.
4332
4333void
4334ProcessGDBRemote::GetMaxMemorySize()
4335{
4336 const uint64_t reasonable_largeish_default = 128 * 1024;
4337 const uint64_t conservative_default = 512;
4338
4339 if (m_max_memory_size == 0)
4340 {
4341 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4342 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4343 {
4344 // Save the stub's claimed maximum packet size
4345 m_remote_stub_max_memory_size = stub_max_size;
4346
4347 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004348 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004349 if (stub_max_size > reasonable_largeish_default)
4350 {
4351 stub_max_size = reasonable_largeish_default;
4352 }
4353
4354 m_max_memory_size = stub_max_size;
4355 }
4356 else
4357 {
4358 m_max_memory_size = conservative_default;
4359 }
4360 }
4361}
4362
4363void
4364ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4365{
4366 if (user_specified_max != 0)
4367 {
4368 GetMaxMemorySize ();
4369
4370 if (m_remote_stub_max_memory_size != 0)
4371 {
4372 if (m_remote_stub_max_memory_size < user_specified_max)
4373 {
4374 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4375 // as the remote stub says we can go.
4376 }
4377 else
4378 {
4379 m_max_memory_size = user_specified_max; // user's packet size is good
4380 }
4381 }
4382 else
4383 {
4384 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4385 }
4386 }
4387}
4388
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004389bool
4390ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4391 const ArchSpec& arch,
4392 ModuleSpec &module_spec)
4393{
4394 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4395
4396 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4397 {
4398 if (log)
4399 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4400 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4401 arch.GetTriple ().getTriple ().c_str ());
4402 return false;
4403 }
4404
4405 if (log)
4406 {
4407 StreamString stream;
4408 module_spec.Dump (stream);
4409 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4410 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4411 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4412 }
4413
4414 return true;
4415}
4416
Jim Ingham13c30d22015-11-05 22:33:17 +00004417bool
4418ProcessGDBRemote::GetHostOSVersion(uint32_t &major,
4419 uint32_t &minor,
4420 uint32_t &update)
4421{
4422 if (m_gdb_comm.GetOSVersion(major, minor, update))
4423 return true;
4424 // We failed to get the host OS version, defer to the base
4425 // implementation to correctly invalidate the arguments.
4426 return Process::GetHostOSVersion(major, minor, update);
4427}
4428
Colin Rileyc3c95b22015-04-16 15:51:33 +00004429namespace {
4430
4431typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004432
4433typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004434struct RegisterSetInfo
4435{
4436 ConstString name;
4437};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004438
Greg Claytond04f0ed2015-05-26 18:00:51 +00004439typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004440
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004441struct GdbServerTargetInfo
4442{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004443 std::string arch;
4444 std::string osabi;
4445 stringVec includes;
4446 RegisterSetMap reg_set_map;
4447 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004448};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004449
Colin Rileyc3c95b22015-04-16 15:51:33 +00004450bool
Jason Molenda21586c82015-09-09 03:36:24 +00004451ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004452{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004453 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004454 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004455
Jason Molenda63bd0db2015-09-15 23:20:34 +00004456 uint32_t cur_reg_num = 0;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004457 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004458
Jason Molenda63bd0db2015-09-15 23:20:34 +00004459 feature_node.ForEachChildElementWithName("reg", [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset, &abi_sp](const XMLNode &reg_node) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004460 std::string gdb_group;
4461 std::string gdb_type;
4462 ConstString reg_name;
4463 ConstString alt_name;
4464 ConstString set_name;
4465 std::vector<uint32_t> value_regs;
4466 std::vector<uint32_t> invalidate_regs;
4467 bool encoding_set = false;
4468 bool format_set = false;
4469 RegisterInfo reg_info = { NULL, // Name
4470 NULL, // Alt name
4471 0, // byte size
4472 reg_offset, // offset
4473 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +00004474 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004475 {
Jason Molendabf67a302015-09-01 05:17:01 +00004476 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004477 LLDB_INVALID_REGNUM, // DWARF reg num
4478 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +00004479 cur_reg_num, // process plugin reg num
4480 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004481 },
4482 NULL,
4483 NULL
4484 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004485
Jason Molenda63bd0db2015-09-15 23:20:34 +00004486 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, &reg_name, &alt_name, &set_name, &value_regs, &invalidate_regs, &encoding_set, &format_set, &reg_info, &cur_reg_num, &reg_offset](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004487 if (name == "name")
4488 {
4489 reg_name.SetString(value);
4490 }
4491 else if (name == "bitsize")
4492 {
4493 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4494 }
4495 else if (name == "type")
4496 {
4497 gdb_type = value.str();
4498 }
4499 else if (name == "group")
4500 {
4501 gdb_group = value.str();
4502 }
4503 else if (name == "regnum")
4504 {
4505 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4506 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004507 {
Jason Molenda63bd0db2015-09-15 23:20:34 +00004508 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004509 }
4510 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004511 else if (name == "offset")
4512 {
4513 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4514 }
4515 else if (name == "altname")
4516 {
4517 alt_name.SetString(value);
4518 }
4519 else if (name == "encoding")
4520 {
4521 encoding_set = true;
4522 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4523 }
4524 else if (name == "format")
4525 {
4526 format_set = true;
4527 Format format = eFormatInvalid;
4528 if (Args::StringToFormat (value.data(), format, NULL).Success())
4529 reg_info.format = format;
4530 else if (value == "vector-sint8")
4531 reg_info.format = eFormatVectorOfSInt8;
4532 else if (value == "vector-uint8")
4533 reg_info.format = eFormatVectorOfUInt8;
4534 else if (value == "vector-sint16")
4535 reg_info.format = eFormatVectorOfSInt16;
4536 else if (value == "vector-uint16")
4537 reg_info.format = eFormatVectorOfUInt16;
4538 else if (value == "vector-sint32")
4539 reg_info.format = eFormatVectorOfSInt32;
4540 else if (value == "vector-uint32")
4541 reg_info.format = eFormatVectorOfUInt32;
4542 else if (value == "vector-float32")
4543 reg_info.format = eFormatVectorOfFloat32;
4544 else if (value == "vector-uint128")
4545 reg_info.format = eFormatVectorOfUInt128;
4546 }
4547 else if (name == "group_id")
4548 {
4549 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4550 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4551 if (pos != target_info.reg_set_map.end())
4552 set_name = pos->second.name;
4553 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004554 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004555 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004556 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004557 }
4558 else if (name == "dwarf_regnum")
4559 {
4560 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4561 }
4562 else if (name == "generic")
4563 {
4564 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4565 }
4566 else if (name == "value_regnums")
4567 {
4568 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4569 }
4570 else if (name == "invalidate_regnums")
4571 {
4572 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4573 }
4574 else
4575 {
4576 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4577 }
4578 return true; // Keep iterating through all attributes
4579 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004580
Greg Claytond04f0ed2015-05-26 18:00:51 +00004581 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004582 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004583 if (gdb_type.find("int") == 0)
4584 {
4585 reg_info.format = eFormatHex;
4586 reg_info.encoding = eEncodingUint;
4587 }
4588 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4589 {
4590 reg_info.format = eFormatAddressInfo;
4591 reg_info.encoding = eEncodingUint;
4592 }
4593 else if (gdb_type == "i387_ext" || gdb_type == "float")
4594 {
4595 reg_info.format = eFormatFloat;
4596 reg_info.encoding = eEncodingIEEE754;
4597 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004598 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004599
Greg Claytond04f0ed2015-05-26 18:00:51 +00004600 // Only update the register set name if we didn't get a "reg_set" attribute.
4601 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4602 if (!set_name && !gdb_group.empty())
4603 set_name.SetCString(gdb_group.c_str());
Ed Maste81b4c5f2016-01-04 01:43:47 +00004604
Greg Claytond04f0ed2015-05-26 18:00:51 +00004605 reg_info.byte_offset = reg_offset;
4606 assert (reg_info.byte_size != 0);
4607 reg_offset += reg_info.byte_size;
4608 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004609 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004610 value_regs.push_back(LLDB_INVALID_REGNUM);
4611 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004612 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004613 if (!invalidate_regs.empty())
4614 {
4615 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4616 reg_info.invalidate_regs = invalidate_regs.data();
4617 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004618
Jason Molenda63bd0db2015-09-15 23:20:34 +00004619 ++cur_reg_num;
Jason Molenda21586c82015-09-09 03:36:24 +00004620 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004621 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004622
Greg Claytond04f0ed2015-05-26 18:00:51 +00004623 return true; // Keep iterating through all "reg" elements
4624 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004625 return true;
4626}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004627
Eugene Zelenko0722f082015-10-24 01:28:05 +00004628} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004629
Colin Rileyc3c95b22015-04-16 15:51:33 +00004630
4631// query the target of gdb-remote for extended target information
4632// return: 'true' on success
4633// 'false' on failure
4634bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004635ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004636{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004637 // Make sure LLDB has an XML parser it can use first
4638 if (!XMLDocument::XMLEnabled())
4639 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004640
4641 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004642
4643 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004644
4645 // check that we have extended feature read support
4646 if ( !comm.GetQXferFeaturesReadSupported( ) )
4647 return false;
4648
4649 // request the target xml file
4650 std::string raw;
4651 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004652 if (!comm.ReadExtFeature(ConstString("features"),
4653 ConstString("target.xml"),
4654 raw,
4655 lldberr))
4656 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004657 return false;
4658 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004659
Colin Rileyc3c95b22015-04-16 15:51:33 +00004660
Greg Claytond04f0ed2015-05-26 18:00:51 +00004661 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004662
Greg Claytond04f0ed2015-05-26 18:00:51 +00004663 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004664 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004665 GdbServerTargetInfo target_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004666
Greg Claytond04f0ed2015-05-26 18:00:51 +00004667 XMLNode target_node = xml_document.GetRootElement("target");
4668 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004669 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004670 XMLNode feature_node;
4671 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4672 {
4673 llvm::StringRef name = node.GetName();
4674 if (name == "architecture")
4675 {
4676 node.GetElementText(target_info.arch);
4677 }
4678 else if (name == "osabi")
4679 {
4680 node.GetElementText(target_info.osabi);
4681 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004682 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004683 {
4684 llvm::StringRef href = node.GetAttributeValue("href");
4685 if (!href.empty())
4686 target_info.includes.push_back(href.str());
4687 }
4688 else if (name == "feature")
4689 {
4690 feature_node = node;
4691 }
4692 else if (name == "groups")
4693 {
4694 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4695 uint32_t set_id = UINT32_MAX;
4696 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004697
Greg Claytond04f0ed2015-05-26 18:00:51 +00004698 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4699 if (name == "id")
4700 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4701 if (name == "name")
4702 set_info.name = ConstString(value);
4703 return true; // Keep iterating through all attributes
4704 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004705
Greg Claytond04f0ed2015-05-26 18:00:51 +00004706 if (set_id != UINT32_MAX)
4707 target_info.reg_set_map[set_id] = set_info;
4708 return true; // Keep iterating through all "group" elements
4709 });
4710 }
4711 return true; // Keep iterating through all children of the target_node
4712 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004713
Greg Claytond04f0ed2015-05-26 18:00:51 +00004714 if (feature_node)
4715 {
Jason Molenda21586c82015-09-09 03:36:24 +00004716 ParseRegisters(feature_node, target_info, this->m_register_info, GetABI());
Greg Claytond04f0ed2015-05-26 18:00:51 +00004717 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004718
Greg Claytond04f0ed2015-05-26 18:00:51 +00004719 for (const auto &include : target_info.includes)
4720 {
4721 // request register file
4722 std::string xml_data;
4723 if (!comm.ReadExtFeature(ConstString("features"),
4724 ConstString(include),
4725 xml_data,
4726 lldberr))
4727 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004728
Greg Claytond04f0ed2015-05-26 18:00:51 +00004729 XMLDocument include_xml_document;
4730 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4731 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4732 if (include_feature_node)
4733 {
Jason Molenda21586c82015-09-09 03:36:24 +00004734 ParseRegisters(include_feature_node, target_info, this->m_register_info, GetABI());
Greg Claytond04f0ed2015-05-26 18:00:51 +00004735 }
4736 }
4737 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004738 }
4739 }
4740
Greg Claytond04f0ed2015-05-26 18:00:51 +00004741 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004742}
4743
Aidan Doddsc0c83852015-05-08 09:36:31 +00004744Error
4745ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4746{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004747 // Make sure LLDB has an XML parser it can use first
4748 if (!XMLDocument::XMLEnabled())
4749 return Error (0, ErrorType::eErrorTypeGeneric);
4750
Aidan Doddsc0c83852015-05-08 09:36:31 +00004751 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4752 if (log)
4753 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4754
Aidan Doddsc0c83852015-05-08 09:36:31 +00004755 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004756
4757 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004758 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4759 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004760
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004761 // request the loaded library list
4762 std::string raw;
4763 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004764
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004765 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4766 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004767
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004768 // parse the xml file in memory
4769 if (log)
4770 log->Printf ("parsing: %s", raw.c_str());
4771 XMLDocument doc;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004772
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004773 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4774 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004775
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004776 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4777 if (!root_element)
4778 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004779
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004780 // main link map structure
4781 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4782 if (!main_lm.empty())
4783 {
4784 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4785 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004786
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004787 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004788
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004789 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004790
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004791 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004792
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004793 if (name == "name")
4794 module.set_name (value.str());
4795 else if (name == "lm")
4796 {
4797 // the address of the link_map struct.
4798 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4799 }
4800 else if (name == "l_addr")
4801 {
4802 // the displacement as read from the field 'l_addr' of the link_map struct.
4803 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004804 // base address is always a displacement, not an absolute value.
4805 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004806 }
4807 else if (name == "l_ld")
4808 {
4809 // the memory address of the libraries PT_DYAMIC section.
4810 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4811 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004812
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004813 return true; // Keep iterating over all properties of "library"
4814 });
4815
4816 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004817 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004818 std::string name;
4819 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004820 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004821
4822 module.get_name (name);
4823 module.get_link_map (lm);
4824 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004825 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004826 module.get_dynamic (ld);
4827
Stephane Sezerc6845a02015-08-20 22:07:48 +00004828 log->Printf ("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64 "[%s], ld:0x%08" PRIx64 ", name:'%s')", lm, base, (base_is_offset ? "offset" : "absolute"), ld, name.c_str());
Aidan Doddsc0c83852015-05-08 09:36:31 +00004829 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004830
4831 list.add (module);
4832 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004833 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004834
4835 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004836 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4837 } else if (comm.GetQXferLibrariesReadSupported ()) {
4838 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004839
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004840 // request the loaded library list
4841 std::string raw;
4842 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004843
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004844 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4845 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004846
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004847 if (log)
4848 log->Printf ("parsing: %s", raw.c_str());
4849 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004850
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004851 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4852 return Error (0, ErrorType::eErrorTypeGeneric);
4853
4854 XMLNode root_element = doc.GetRootElement("library-list");
4855 if (!root_element)
4856 return Error();
4857
4858 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4859 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4860
4861 llvm::StringRef name = library.GetAttributeValue("name");
4862 module.set_name(name.str());
4863
4864 // The base address of a given library will be the address of its
4865 // first section. Most remotes send only one section for Windows
4866 // targets for example.
4867 const XMLNode &section = library.FindFirstChildElementWithName("section");
4868 llvm::StringRef address = section.GetAttributeValue("address");
4869 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004870 // These addresses are absolute values.
4871 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004872
4873 if (log)
4874 {
4875 std::string name;
4876 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004877 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004878 module.get_name (name);
4879 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004880 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004881
Stephane Sezerc6845a02015-08-20 22:07:48 +00004882 log->Printf ("found (base:0x%08" PRIx64 "[%s], name:'%s')", base, (base_is_offset ? "offset" : "absolute"), name.c_str());
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004883 }
4884
4885 list.add (module);
4886 return true; // Keep iterating over all "library" elements in the root node
4887 });
4888
4889 if (log)
4890 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4891 } else {
4892 return Error (0, ErrorType::eErrorTypeGeneric);
4893 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004894
4895 return Error();
4896}
4897
Aidan Doddsc0c83852015-05-08 09:36:31 +00004898lldb::ModuleSP
Stephane Sezerc6845a02015-08-20 22:07:48 +00004899ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004900{
4901 Target &target = m_process->GetTarget();
4902 ModuleList &modules = target.GetImages();
4903 ModuleSP module_sp;
4904
4905 bool changed = false;
4906
4907 ModuleSpec module_spec (file, target.GetArchitecture());
4908 if ((module_sp = modules.FindFirstModule (module_spec)))
4909 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004910 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004911 }
4912 else if ((module_sp = target.GetSharedModule (module_spec)))
4913 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004914 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004915 }
4916
4917 return module_sp;
4918}
4919
4920size_t
4921ProcessGDBRemote::LoadModules ()
4922{
4923 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4924
4925 // request a list of loaded libraries from GDBServer
4926 GDBLoadedModuleInfoList module_list;
4927 if (GetLoadedModuleList (module_list).Fail())
4928 return 0;
4929
4930 // get a list of all the modules
4931 ModuleList new_modules;
4932
4933 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4934 {
4935 std::string mod_name;
4936 lldb::addr_t mod_base;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004937 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004938
4939 bool valid = true;
4940 valid &= modInfo.get_name (mod_name);
4941 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004942 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004943 if (!valid)
4944 continue;
4945
4946 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004947 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004948 if (marker == std::string::npos)
4949 marker = 0;
4950 else
4951 marker += 1;
4952
4953 FileSpec file (mod_name.c_str()+marker, true);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004954 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base, mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004955
4956 if (module_sp.get())
4957 new_modules.Append (module_sp);
4958 }
4959
4960 if (new_modules.GetSize() > 0)
4961 {
Zachary Turner7529df92015-09-01 20:02:29 +00004962 Target &target = GetTarget();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004963
4964 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4965 {
4966 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4967 if (!obj)
4968 return true;
4969
4970 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4971 return true;
4972
4973 lldb::ModuleSP module_copy_sp = module_sp;
4974 target.SetExecutableModule (module_copy_sp, false);
4975 return false;
4976 });
4977
4978 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4979 loaded_modules.AppendIfNeeded (new_modules);
4980 m_process->GetTarget().ModulesDidLoad (new_modules);
4981 }
4982
4983 return new_modules.GetSize();
4984}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004985
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004986Error
4987ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4988{
4989 is_loaded = false;
4990 load_addr = LLDB_INVALID_ADDRESS;
4991
4992 std::string file_path = file.GetPath(false);
4993 if (file_path.empty ())
4994 return Error("Empty file name specified");
4995
4996 StreamString packet;
4997 packet.PutCString("qFileLoadAddress:");
4998 packet.PutCStringAsRawHex8(file_path.c_str());
4999
5000 StringExtractorGDBRemote response;
5001 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
5002 return Error("Sending qFileLoadAddress packet failed");
5003
5004 if (response.IsErrorResponse())
5005 {
5006 if (response.GetError() == 1)
5007 {
5008 // The file is not loaded into the inferior
5009 is_loaded = false;
5010 load_addr = LLDB_INVALID_ADDRESS;
5011 return Error();
5012 }
5013
5014 return Error("Fetching file load address from remote server returned an error");
5015 }
5016
5017 if (response.IsNormalResponse())
5018 {
5019 is_loaded = true;
5020 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
5021 return Error();
5022 }
5023
5024 return Error("Unknown error happened during sending the load address packet");
5025}
5026
Eugene Zelenko0722f082015-10-24 01:28:05 +00005027
Greg Clayton0b90be12015-06-23 21:27:50 +00005028void
5029ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
5030{
5031 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
5032 Process::ModulesDidLoad (module_list);
5033
5034 // After loading shared libraries, we can ask our remote GDB server if
5035 // it needs any symbols.
5036 m_gdb_comm.ServeSymbolLookups(this);
5037}
5038
Eugene Zelenko0722f082015-10-24 01:28:05 +00005039
Greg Claytone034a042015-05-21 20:52:06 +00005040class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
5041{
5042public:
5043 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
5044 CommandObjectParsed (interpreter,
5045 "process plugin packet speed-test",
5046 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
5047 NULL),
5048 m_option_group (interpreter),
5049 m_num_packets (LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, "The number of packets to send of each varying size (default is 1000).", 1000),
5050 m_max_send (LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, "The maximum number of bytes to send in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024),
5051 m_max_recv (LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, "The maximum number of bytes to receive in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024),
5052 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
5053 {
5054 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5055 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5056 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5057 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5058 m_option_group.Finalize();
5059 }
5060
Eugene Zelenko0722f082015-10-24 01:28:05 +00005061 ~CommandObjectProcessGDBRemoteSpeedTest ()
5062 {
5063 }
5064
Greg Claytone034a042015-05-21 20:52:06 +00005065
5066 Options *
5067 GetOptions () override
5068 {
5069 return &m_option_group;
5070 }
5071
5072 bool
5073 DoExecute (Args& command, CommandReturnObject &result) override
5074 {
5075 const size_t argc = command.GetArgumentCount();
5076 if (argc == 0)
5077 {
5078 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5079 if (process)
5080 {
5081 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
5082 result.SetImmediateOutputStream (output_stream_sp);
5083
5084 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5085 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5086 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5087 const bool json = m_json.GetOptionValue().GetCurrentValue();
5088 if (output_stream_sp)
5089 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
5090 else
5091 {
5092 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
5093 }
5094 result.SetStatus (eReturnStatusSuccessFinishResult);
5095 return true;
5096 }
5097 }
5098 else
5099 {
5100 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5101 }
5102 result.SetStatus (eReturnStatusFailed);
5103 return false;
5104 }
5105protected:
5106 OptionGroupOptions m_option_group;
5107 OptionGroupUInt64 m_num_packets;
5108 OptionGroupUInt64 m_max_send;
5109 OptionGroupUInt64 m_max_recv;
5110 OptionGroupBoolean m_json;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005111
Greg Claytone034a042015-05-21 20:52:06 +00005112};
5113
Greg Clayton02686b82012-10-15 22:42:16 +00005114class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00005115{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005116private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005117
Greg Clayton998255b2012-10-13 02:07:45 +00005118public:
Greg Clayton02686b82012-10-15 22:42:16 +00005119 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00005120 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00005121 "process plugin packet history",
5122 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00005123 NULL)
5124 {
5125 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005126
Eugene Zelenko0722f082015-10-24 01:28:05 +00005127 ~CommandObjectProcessGDBRemotePacketHistory ()
5128 {
5129 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005130
Greg Clayton998255b2012-10-13 02:07:45 +00005131 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005132 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00005133 {
Greg Clayton02686b82012-10-15 22:42:16 +00005134 const size_t argc = command.GetArgumentCount();
5135 if (argc == 0)
5136 {
5137 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5138 if (process)
5139 {
5140 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5141 result.SetStatus (eReturnStatusSuccessFinishResult);
5142 return true;
5143 }
5144 }
5145 else
5146 {
5147 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5148 }
5149 result.SetStatus (eReturnStatusFailed);
5150 return false;
5151 }
5152};
5153
Jason Molenda6076bf42014-05-06 04:34:52 +00005154class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
5155{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005156private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005157
Jason Molenda6076bf42014-05-06 04:34:52 +00005158public:
5159 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
5160 CommandObjectParsed (interpreter,
5161 "process plugin packet xfer-size",
5162 "Maximum size that lldb will try to read/write one one chunk.",
5163 NULL)
5164 {
5165 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005166
Eugene Zelenko0722f082015-10-24 01:28:05 +00005167 ~CommandObjectProcessGDBRemotePacketXferSize ()
5168 {
5169 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005170
Jason Molenda6076bf42014-05-06 04:34:52 +00005171 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005172 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00005173 {
5174 const size_t argc = command.GetArgumentCount();
5175 if (argc == 0)
5176 {
5177 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
5178 result.SetStatus (eReturnStatusFailed);
5179 return false;
5180 }
5181
5182 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5183 if (process)
5184 {
5185 const char *packet_size = command.GetArgumentAtIndex(0);
5186 errno = 0;
5187 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5188 if (errno == 0 && user_specified_max != 0)
5189 {
5190 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5191 result.SetStatus (eReturnStatusSuccessFinishResult);
5192 return true;
5193 }
5194 }
5195 result.SetStatus (eReturnStatusFailed);
5196 return false;
5197 }
5198};
5199
Eugene Zelenko0722f082015-10-24 01:28:05 +00005200
Greg Clayton02686b82012-10-15 22:42:16 +00005201class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5202{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005203private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005204
Greg Clayton02686b82012-10-15 22:42:16 +00005205public:
5206 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5207 CommandObjectParsed (interpreter,
5208 "process plugin packet send",
5209 "Send a custom packet through the GDB remote protocol and print the answer. "
5210 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5211 NULL)
5212 {
5213 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005214
Eugene Zelenko0722f082015-10-24 01:28:05 +00005215 ~CommandObjectProcessGDBRemotePacketSend ()
5216 {
5217 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005218
Greg Clayton02686b82012-10-15 22:42:16 +00005219 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005220 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005221 {
5222 const size_t argc = command.GetArgumentCount();
5223 if (argc == 0)
5224 {
5225 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5226 result.SetStatus (eReturnStatusFailed);
5227 return false;
5228 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005229
Greg Clayton02686b82012-10-15 22:42:16 +00005230 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5231 if (process)
5232 {
Han Ming Ong84145852012-11-26 20:42:03 +00005233 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005234 {
Han Ming Ong84145852012-11-26 20:42:03 +00005235 const char *packet_cstr = command.GetArgumentAtIndex(0);
5236 bool send_async = true;
5237 StringExtractorGDBRemote response;
5238 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5239 result.SetStatus (eReturnStatusSuccessFinishResult);
5240 Stream &output_strm = result.GetOutputStream();
5241 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005242 std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005243
Han Ming Ong399289e2013-06-21 19:56:59 +00005244 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005245 {
5246 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5247 }
5248
Han Ming Ong84145852012-11-26 20:42:03 +00005249 if (response_str.empty())
5250 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5251 else
5252 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005253 }
Greg Clayton02686b82012-10-15 22:42:16 +00005254 }
Greg Clayton998255b2012-10-13 02:07:45 +00005255 return true;
5256 }
5257};
5258
Greg Claytonba4a0a52013-02-01 23:03:47 +00005259class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5260{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005261private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005262
Greg Claytonba4a0a52013-02-01 23:03:47 +00005263public:
5264 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5265 CommandObjectRaw (interpreter,
5266 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005267 "Send a qRcmd packet through the GDB remote protocol and print the response."
5268 "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 +00005269 NULL)
5270 {
5271 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005272
Eugene Zelenko0722f082015-10-24 01:28:05 +00005273 ~CommandObjectProcessGDBRemotePacketMonitor ()
5274 {
5275 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005276
Greg Claytonba4a0a52013-02-01 23:03:47 +00005277 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005278 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005279 {
5280 if (command == NULL || command[0] == '\0')
5281 {
5282 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5283 result.SetStatus (eReturnStatusFailed);
5284 return false;
5285 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005286
Greg Claytonba4a0a52013-02-01 23:03:47 +00005287 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5288 if (process)
5289 {
5290 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005291 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005292 packet.PutBytesAsRawHex8(command, strlen(command));
5293 const char *packet_cstr = packet.GetString().c_str();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005294
Greg Claytonba4a0a52013-02-01 23:03:47 +00005295 bool send_async = true;
5296 StringExtractorGDBRemote response;
5297 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5298 result.SetStatus (eReturnStatusSuccessFinishResult);
5299 Stream &output_strm = result.GetOutputStream();
5300 output_strm.Printf (" packet: %s\n", packet_cstr);
5301 const std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005302
Greg Claytonba4a0a52013-02-01 23:03:47 +00005303 if (response_str.empty())
5304 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5305 else
5306 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5307 }
5308 return true;
5309 }
5310};
5311
Greg Clayton02686b82012-10-15 22:42:16 +00005312class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5313{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005314private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005315
Greg Clayton02686b82012-10-15 22:42:16 +00005316public:
5317 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5318 CommandObjectMultiword (interpreter,
5319 "process plugin packet",
5320 "Commands that deal with GDB remote packets.",
5321 NULL)
5322 {
5323 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5324 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005325 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005326 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005327 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005328 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005329
Eugene Zelenko0722f082015-10-24 01:28:05 +00005330 ~CommandObjectProcessGDBRemotePacket ()
5331 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00005332 }
Greg Clayton02686b82012-10-15 22:42:16 +00005333};
Greg Clayton998255b2012-10-13 02:07:45 +00005334
5335class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5336{
5337public:
5338 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5339 CommandObjectMultiword (interpreter,
5340 "process plugin",
5341 "A set of commands for operating on a ProcessGDBRemote process.",
5342 "process plugin <subcommand> [<subcommand-options>]")
5343 {
5344 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5345 }
5346
Eugene Zelenko0722f082015-10-24 01:28:05 +00005347 ~CommandObjectMultiwordProcessGDBRemote ()
5348 {
5349 }
Greg Clayton998255b2012-10-13 02:07:45 +00005350};
5351
Greg Clayton998255b2012-10-13 02:07:45 +00005352CommandObject *
5353ProcessGDBRemote::GetPluginCommandObject()
5354{
5355 if (!m_command_sp)
5356 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5357 return m_command_sp.get();
5358}