blob: 83a0d5bd94f6645c471dd67468010b37bc54168f [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
2037 std::string &queue_name,
2038 QueueKind queue_kind,
2039 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002040{
2041 ThreadSP thread_sp;
2042 if (tid != LLDB_INVALID_THREAD_ID)
2043 {
2044 // Scope for "locker" below
2045 {
2046 // m_thread_list_real does have its own mutex, but we need to
2047 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
2048 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
2049 Mutex::Locker locker (m_thread_list_real.GetMutex ());
2050 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
2051
2052 if (!thread_sp)
2053 {
2054 // Create the thread if we need to
2055 thread_sp.reset (new ThreadGDBRemote (*this, tid));
2056 m_thread_list_real.AddThread(thread_sp);
2057 }
2058 }
2059
2060 if (thread_sp)
2061 {
2062 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
2063 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002064
Greg Clayton358cf1e2015-06-25 21:46:34 +00002065 for (const auto &pair : expedited_register_map)
2066 {
2067 StringExtractor reg_value_extractor;
2068 reg_value_extractor.GetStringRef() = pair.second;
2069 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
2070 }
2071
Greg Clayton358cf1e2015-06-25 21:46:34 +00002072 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
2073
2074 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002075 // Check if the GDB server was able to provide the queue name, kind and serial number
2076 if (queue_vars_valid)
2077 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
2078 else
2079 gdb_thread->ClearQueueInfo();
2080
Greg Clayton2e309072015-07-17 23:42:28 +00002081 // Make sure we update our thread stop reason just once
2082 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002083 {
Greg Clayton2e309072015-07-17 23:42:28 +00002084 thread_sp->SetStopInfo (StopInfoSP());
Ryan Brown65d4d5c2015-09-16 21:20:44 +00002085 // If there's a memory thread backed by this thread, we need to use it to calcualte StopInfo.
2086 ThreadSP memory_thread_sp = m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
2087 if (memory_thread_sp)
2088 thread_sp = memory_thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002089
Greg Clayton2e309072015-07-17 23:42:28 +00002090 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002091 {
Greg Clayton2e309072015-07-17 23:42:28 +00002092 const size_t exc_data_size = exc_data.size();
2093
2094 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
2095 exc_type,
2096 exc_data_size,
2097 exc_data_size >= 1 ? exc_data[0] : 0,
2098 exc_data_size >= 2 ? exc_data[1] : 0,
2099 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002100 }
Greg Clayton2e309072015-07-17 23:42:28 +00002101 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002102 {
Greg Clayton2e309072015-07-17 23:42:28 +00002103 bool handled = false;
2104 bool did_exec = false;
2105 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002106 {
Greg Clayton2e309072015-07-17 23:42:28 +00002107 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002108 {
Greg Clayton2e309072015-07-17 23:42:28 +00002109 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2110 handled = true;
2111 }
2112 else if (reason.compare("breakpoint") == 0)
2113 {
2114 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2115 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2116 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002117 {
Greg Clayton2e309072015-07-17 23:42:28 +00002118 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2119 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2120 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2121 handled = true;
2122 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2123 {
2124 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2125 }
2126 else
2127 {
2128 StopInfoSP invalid_stop_info_sp;
2129 thread_sp->SetStopInfo (invalid_stop_info_sp);
2130 }
2131 }
2132 }
2133 else if (reason.compare("trap") == 0)
2134 {
2135 // Let the trap just use the standard signal stop reason below...
2136 }
2137 else if (reason.compare("watchpoint") == 0)
2138 {
2139 StringExtractor desc_extractor(description.c_str());
2140 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2141 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002142 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002143 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2144 if (wp_addr != LLDB_INVALID_ADDRESS)
2145 {
Mohit K. Bhakkad6846bc82015-12-02 17:45:02 +00002146 WatchpointSP wp_sp;
2147 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
2148 if (core >= ArchSpec::kCore_mips_first && core <= ArchSpec::kCore_mips_last)
2149 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_hit_addr);
2150 if (!wp_sp)
2151 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
Greg Clayton2e309072015-07-17 23:42:28 +00002152 if (wp_sp)
2153 {
2154 wp_sp->SetHardwareIndex(wp_index);
2155 watch_id = wp_sp->GetID();
2156 }
2157 }
2158 if (watch_id == LLDB_INVALID_WATCH_ID)
2159 {
2160 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2161 if (log) log->Printf ("failed to find watchpoint");
2162 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002163 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002164 handled = true;
2165 }
2166 else if (reason.compare("exception") == 0)
2167 {
2168 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2169 handled = true;
2170 }
2171 else if (reason.compare("exec") == 0)
2172 {
2173 did_exec = true;
2174 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2175 handled = true;
2176 }
2177 }
2178
2179 if (!handled && signo && did_exec == false)
2180 {
2181 if (signo == SIGTRAP)
2182 {
2183 // Currently we are going to assume SIGTRAP means we are either
2184 // hitting a breakpoint or hardware single stepping.
2185 handled = true;
2186 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2187 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2188
2189 if (bp_site_sp)
2190 {
2191 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2192 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2193 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2194 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2195 {
2196 if(m_breakpoint_pc_offset != 0)
2197 thread_sp->GetRegisterContext()->SetPC(pc);
2198 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2199 }
2200 else
2201 {
2202 StopInfoSP invalid_stop_info_sp;
2203 thread_sp->SetStopInfo (invalid_stop_info_sp);
2204 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002205 }
2206 else
2207 {
Greg Clayton2e309072015-07-17 23:42:28 +00002208 // If we were stepping then assume the stop was the result of the trace. If we were
2209 // not stepping then report the SIGTRAP.
2210 // FIXME: We are still missing the case where we single step over a trap instruction.
2211 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2212 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2213 else
2214 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002215 }
2216 }
Greg Clayton2e309072015-07-17 23:42:28 +00002217 if (!handled)
2218 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2219 }
2220
2221 if (!description.empty())
2222 {
2223 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2224 if (stop_info_sp)
2225 {
2226 const char *stop_info_desc = stop_info_sp->GetDescription();
2227 if (!stop_info_desc || !stop_info_desc[0])
2228 stop_info_sp->SetDescription (description.c_str());
2229 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002230 else
2231 {
Greg Clayton2e309072015-07-17 23:42:28 +00002232 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002233 }
2234 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002235 }
2236 }
2237 }
2238 }
2239 return thread_sp;
2240}
2241
Greg Clayton2e309072015-07-17 23:42:28 +00002242lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002243ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2244{
2245 static ConstString g_key_tid("tid");
2246 static ConstString g_key_name("name");
2247 static ConstString g_key_reason("reason");
2248 static ConstString g_key_metype("metype");
2249 static ConstString g_key_medata("medata");
2250 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002251 static ConstString g_key_queue_name("qname");
2252 static ConstString g_key_queue_kind("qkind");
Jason Molenda26d84e82016-01-08 00:20:48 +00002253 static ConstString g_key_queue_serial_number("qserialnum");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002254 static ConstString g_key_registers("registers");
2255 static ConstString g_key_memory("memory");
2256 static ConstString g_key_address("address");
2257 static ConstString g_key_bytes("bytes");
2258 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002259 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002260
2261 // Stop with signal and thread info
2262 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2263 uint8_t signo = 0;
2264 std::string value;
2265 std::string thread_name;
2266 std::string reason;
2267 std::string description;
2268 uint32_t exc_type = 0;
2269 std::vector<addr_t> exc_data;
2270 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2271 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002272 bool queue_vars_valid = false;
2273 std::string queue_name;
2274 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002275 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002276 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2277
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002278 thread_dict->ForEach([this,
2279 &tid,
2280 &expedited_register_map,
2281 &thread_name,
2282 &signo,
2283 &reason,
2284 &description,
2285 &exc_type,
2286 &exc_data,
2287 &thread_dispatch_qaddr,
2288 &queue_vars_valid,
2289 &queue_name,
2290 &queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002291 &queue_serial_number]
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002292 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002293 {
2294 if (key == g_key_tid)
2295 {
2296 // thread in big endian hex
2297 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2298 }
2299 else if (key == g_key_metype)
2300 {
2301 // exception type in big endian hex
2302 exc_type = object->GetIntegerValue(0);
2303 }
2304 else if (key == g_key_medata)
2305 {
2306 // exception data in big endian hex
2307 StructuredData::Array *array = object->GetAsArray();
2308 if (array)
2309 {
2310 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2311 exc_data.push_back(object->GetIntegerValue());
2312 return true; // Keep iterating through all array items
2313 });
2314 }
2315 }
2316 else if (key == g_key_name)
2317 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002318 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002319 }
2320 else if (key == g_key_qaddr)
2321 {
2322 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2323 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002324 else if (key == g_key_queue_name)
2325 {
2326 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002327 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002328 }
2329 else if (key == g_key_queue_kind)
2330 {
2331 std::string queue_kind_str = object->GetStringValue();
2332 if (queue_kind_str == "serial")
2333 {
2334 queue_vars_valid = true;
2335 queue_kind = eQueueKindSerial;
2336 }
2337 else if (queue_kind_str == "concurrent")
2338 {
2339 queue_vars_valid = true;
2340 queue_kind = eQueueKindConcurrent;
2341 }
2342 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002343 else if (key == g_key_queue_serial_number)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002344 {
Jason Molenda26d84e82016-01-08 00:20:48 +00002345 queue_serial_number = object->GetIntegerValue(0);
2346 if (queue_serial_number != 0)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002347 queue_vars_valid = true;
2348 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002349 else if (key == g_key_reason)
2350 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002351 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002352 }
2353 else if (key == g_key_description)
2354 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002355 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002356 }
2357 else if (key == g_key_registers)
2358 {
2359 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2360
2361 if (registers_dict)
2362 {
2363 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2364 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2365 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002366 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002367 return true; // Keep iterating through all array items
2368 });
2369 }
2370 }
2371 else if (key == g_key_memory)
2372 {
2373 StructuredData::Array *array = object->GetAsArray();
2374 if (array)
2375 {
2376 array->ForEach([this](StructuredData::Object* object) -> bool {
2377 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2378 if (mem_cache_dict)
2379 {
2380 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2381 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2382 {
2383 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2384 {
2385 StringExtractor bytes;
2386 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2387 {
2388 bytes.SetFilePos(0);
2389
2390 const size_t byte_size = bytes.GetStringRef().size()/2;
2391 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2392 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2393 if (bytes_copied == byte_size)
2394 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2395 }
2396 }
2397 }
2398 }
2399 return true; // Keep iterating through all array items
2400 });
2401 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00002402
Greg Clayton358cf1e2015-06-25 21:46:34 +00002403 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002404 else if (key == g_key_signal)
2405 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002406 return true; // Keep iterating through all dictionary key/value pairs
2407 });
2408
Greg Clayton2e309072015-07-17 23:42:28 +00002409 return SetThreadStopInfo (tid,
2410 expedited_register_map,
2411 signo,
2412 thread_name,
2413 reason,
2414 description,
2415 exc_type,
2416 exc_data,
2417 thread_dispatch_qaddr,
2418 queue_vars_valid,
2419 queue_name,
2420 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002421 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002422}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002423
2424StateType
2425ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2426{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002427 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428 const char stop_type = stop_packet.GetChar();
2429 switch (stop_type)
2430 {
2431 case 'T':
2432 case 'S':
2433 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002434 // This is a bit of a hack, but is is required. If we did exec, we
2435 // need to clear our thread lists and also know to rebuild our dynamic
2436 // register info before we lookup and threads and populate the expedited
2437 // register values so we need to know this right away so we can cleanup
2438 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002439 const uint32_t stop_id = GetStopID();
2440 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002441 {
2442 // Our first stop, make sure we have a process ID, and also make
2443 // sure we know about our registers
2444 if (GetID() == LLDB_INVALID_PROCESS_ID)
2445 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002446 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002447 if (pid != LLDB_INVALID_PROCESS_ID)
2448 SetID (pid);
2449 }
2450 BuildDynamicRegisterInfo (true);
2451 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002452 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002453 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002454 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002455 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002456 std::string value;
2457 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002458 std::string reason;
2459 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002460 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002461 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002462 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002463 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2464 std::string queue_name;
2465 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002466 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002467 ExpeditedRegisterMap expedited_register_map;
2468 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002469 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002470 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002471 {
2472 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002473 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002474 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002475 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002476 {
2477 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002478 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002479 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002480 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002481 {
2482 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002483 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002484 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002485 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002486 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002487 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002488 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002489 // A comma separated list of all threads in the current
2490 // process that includes the thread for this stop reply
2491 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002492 size_t comma_pos;
2493 lldb::tid_t tid;
2494 while ((comma_pos = value.find(',')) != std::string::npos)
2495 {
2496 value[comma_pos] = '\0';
2497 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002498 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002499 if (tid != LLDB_INVALID_THREAD_ID)
2500 m_thread_ids.push_back (tid);
2501 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002502 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002503 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002504 if (tid != LLDB_INVALID_THREAD_ID)
2505 m_thread_ids.push_back (tid);
2506 }
Jason Molenda545304d2015-12-18 00:45:35 +00002507 else if (key.compare("thread-pcs") == 0)
2508 {
2509 m_thread_pcs.clear();
2510 // A comma separated list of all threads in the current
2511 // process that includes the thread for this stop reply
2512 // packet
2513 size_t comma_pos;
2514 lldb::addr_t pc;
2515 while ((comma_pos = value.find(',')) != std::string::npos)
2516 {
2517 value[comma_pos] = '\0';
2518 // thread in big endian hex
2519 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2520 if (pc != LLDB_INVALID_ADDRESS)
2521 m_thread_pcs.push_back (pc);
2522 value.erase(0, comma_pos + 1);
2523 }
2524 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2525 if (pc != LLDB_INVALID_ADDRESS)
2526 m_thread_pcs.push_back (pc);
2527 }
Greg Clayton2e309072015-07-17 23:42:28 +00002528 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002529 {
2530 StringExtractor json_extractor;
2531 // Swap "value" over into "name_extractor"
2532 json_extractor.GetStringRef().swap(value);
2533 // Now convert the HEX bytes into a string value
2534 json_extractor.GetHexByteString (value);
2535
2536 // This JSON contains thread IDs and thread stop info for all threads.
2537 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002538 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002539 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002540 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002541 {
2542 StringExtractor name_extractor;
2543 // Swap "value" over into "name_extractor"
2544 name_extractor.GetStringRef().swap(value);
2545 // Now convert the HEX bytes into a string value
2546 name_extractor.GetHexByteString (value);
2547 thread_name.swap (value);
2548 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002549 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002550 {
2551 thread_name.swap (value);
2552 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002553 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002554 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002555 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002556 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002557 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002558 {
2559 queue_vars_valid = true;
2560 StringExtractor name_extractor;
2561 // Swap "value" over into "name_extractor"
2562 name_extractor.GetStringRef().swap(value);
2563 // Now convert the HEX bytes into a string value
2564 name_extractor.GetHexByteString (value);
2565 queue_name.swap (value);
2566 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002567 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002568 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002569 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002570 {
2571 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002572 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002573 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002574 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002575 {
2576 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002577 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002578 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002579 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002580 else if (key.compare("qserialnum") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002581 {
Jason Molenda26d84e82016-01-08 00:20:48 +00002582 queue_serial_number = StringConvert::ToUInt64 (value.c_str(), 0, 0);
2583 if (queue_serial_number != 0)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002584 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002585 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002586 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002587 {
2588 reason.swap(value);
2589 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002590 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002591 {
2592 StringExtractor desc_extractor;
2593 // Swap "value" over into "name_extractor"
2594 desc_extractor.GetStringRef().swap(value);
2595 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002596 desc_extractor.GetHexByteString (value);
2597 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002598 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002599 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002600 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002601 // Expedited memory. GDB servers can choose to send back expedited memory
2602 // that can populate the L1 memory cache in the process so that things like
2603 // the frame pointer backchain can be expedited. This will help stack
2604 // backtracing be more efficient by not having to send as many memory read
2605 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002606
Greg Clayton358cf1e2015-06-25 21:46:34 +00002607 // Key/value pair format: memory:<addr>=<bytes>;
2608 // <addr> is a number whose base will be interpreted by the prefix:
2609 // "0x[0-9a-fA-F]+" for hex
2610 // "0[0-7]+" for octal
2611 // "[1-9]+" for decimal
2612 // <bytes> is native endian ASCII hex bytes just like the register values
2613 llvm::StringRef value_ref(value);
2614 std::pair<llvm::StringRef, llvm::StringRef> pair;
2615 pair = value_ref.split('=');
2616 if (!pair.first.empty() && !pair.second.empty())
2617 {
2618 std::string addr_str(pair.first.str());
2619 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2620 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002621 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002622 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002623 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002624 const size_t byte_size = bytes.GetStringRef().size()/2;
2625 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2626 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2627 if (bytes_copied == byte_size)
2628 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002629 }
2630 }
2631 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002632 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2633 {
2634 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2635 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2636 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2637 uint32_t wp_index = LLDB_INVALID_INDEX32;
2638
2639 if (wp_sp)
2640 wp_index = wp_sp->GetHardwareIndex();
2641
2642 reason = "watchpoint";
2643 StreamString ostr;
2644 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2645 description = ostr.GetString().c_str();
2646 }
Stephane Sezer2618e912015-08-21 16:51:56 +00002647 else if (key.compare("library") == 0)
2648 {
2649 LoadModules();
2650 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002651 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2652 {
2653 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2654 if (reg != UINT32_MAX)
2655 expedited_register_map[reg] = std::move(value);
2656 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002657 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002658
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002659 if (tid == LLDB_INVALID_THREAD_ID)
2660 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00002661 // 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 +00002662 // thread information. So update the thread list and choose the first one.
2663 UpdateThreadIDList ();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002664
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002665 if (!m_thread_ids.empty ())
2666 {
2667 tid = m_thread_ids.front ();
2668 }
2669 }
2670
Greg Clayton358cf1e2015-06-25 21:46:34 +00002671 ThreadSP thread_sp = SetThreadStopInfo (tid,
2672 expedited_register_map,
2673 signo,
2674 thread_name,
2675 reason,
2676 description,
2677 exc_type,
2678 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002679 thread_dispatch_qaddr,
2680 queue_vars_valid,
2681 queue_name,
2682 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002683 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002684
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002685 return eStateStopped;
2686 }
2687 break;
2688
2689 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002690 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002691 // process exited
2692 return eStateExited;
2693
2694 default:
2695 break;
2696 }
2697 return eStateInvalid;
2698}
2699
2700void
2701ProcessGDBRemote::RefreshStateAfterStop ()
2702{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002703 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002704 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00002705 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00002706 // Set the thread stop info. It might have a "threads" key whose value is
2707 // a list of all thread IDs in the current process, so m_thread_ids might
2708 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002709
2710 // Scope for the lock
2711 {
2712 // Lock the thread stack while we access it
2713 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2714 // Get the number of stop packets on the stack
2715 int nItems = m_stop_packet_stack.size();
2716 // Iterate over them
2717 for (int i = 0; i < nItems; i++)
2718 {
2719 // Get the thread stop info
2720 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2721 // Process thread stop info
2722 SetThreadStopInfo(stop_info);
2723 }
2724 // Clear the thread stop stack
2725 m_stop_packet_stack.clear();
2726 }
2727
Greg Clayton9e920902012-04-10 02:25:43 +00002728 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2729 if (m_thread_ids.empty())
2730 {
2731 // No, we need to fetch the thread list manually
2732 UpdateThreadIDList();
2733 }
2734
Ewan Crawford78baa192015-05-13 09:18:18 +00002735 // If we have queried for a default thread id
2736 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2737 {
2738 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2739 m_initial_tid = LLDB_INVALID_THREAD_ID;
2740 }
2741
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002742 // Let all threads recover from stopping and do any clean up based
2743 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002744 m_thread_list_real.RefreshStateAfterStop();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002745
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002746}
2747
2748Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002749ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002750{
2751 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002752
Greg Clayton6ed95942011-01-22 07:12:45 +00002753 bool timed_out = false;
2754 Mutex::Locker locker;
Ed Maste81b4c5f2016-01-04 01:43:47 +00002755
Greg Clayton513c26c2011-01-29 07:10:55 +00002756 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002757 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002758 // We are being asked to halt during an attach. We need to just close
2759 // our file handle and debugserver will go away, and we can be done...
2760 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002761 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002762 else
2763 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002764 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002765 {
2766 if (timed_out)
2767 error.SetErrorString("timed out sending interrupt packet");
2768 else
2769 error.SetErrorString("unknown error sending interrupt packet");
2770 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002771
Greg Clayton2687cd12012-03-29 01:55:41 +00002772 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002773 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002774 return error;
2775}
2776
2777Error
Jim Inghamacff8952013-05-02 00:27:30 +00002778ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002779{
2780 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002781 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002782 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002783 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Ed Maste81b4c5f2016-01-04 01:43:47 +00002784
Jim Inghamacff8952013-05-02 00:27:30 +00002785 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002786 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002787 {
Jim Inghamacff8952013-05-02 00:27:30 +00002788 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002789 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2790 else
Jim Inghamacff8952013-05-02 00:27:30 +00002791 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002792 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002793
Jim Inghamacff8952013-05-02 00:27:30 +00002794 if (!error.Success())
2795 return error;
2796
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002797 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002798 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002799
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002800 SetPrivateState (eStateDetached);
2801 ResumePrivateStateThread();
2802
2803 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002804 return error;
2805}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002806
Eugene Zelenko0722f082015-10-24 01:28:05 +00002807
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002808Error
2809ProcessGDBRemote::DoDestroy ()
2810{
2811 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002812 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813 if (log)
2814 log->Printf ("ProcessGDBRemote::DoDestroy()");
2815
Jim Ingham43c555d2012-07-04 00:35:43 +00002816 // There is a bug in older iOS debugservers where they don't shut down the process
2817 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2818 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2819 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2820 // destroy it again.
2821 //
2822 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2823 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2824 // the debugservers with this bug are equal. There really should be a better way to test this!
2825 //
2826 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2827 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2828 // just do the straight-forward kill.
2829 //
2830 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2831 // necessary (or helpful) to do any of this.
2832
2833 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2834 {
2835 PlatformSP platform_sp = GetTarget().GetPlatform();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002836
Jim Ingham43c555d2012-07-04 00:35:43 +00002837 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2838 if (platform_sp
2839 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002840 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002841 {
2842 if (m_destroy_tried_resuming)
2843 {
2844 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002845 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002846 }
2847 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00002848 {
Jim Ingham43c555d2012-07-04 00:35:43 +00002849 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2850 // but we really need it to happen here and it doesn't matter if we do it twice.
2851 m_thread_list.DiscardThreadPlans();
2852 DisableAllBreakpointSites();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002853
Jim Ingham43c555d2012-07-04 00:35:43 +00002854 bool stop_looks_like_crash = false;
2855 ThreadList &threads = GetThreadList();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002856
Jim Ingham43c555d2012-07-04 00:35:43 +00002857 {
Jim Ingham45350372012-09-11 00:08:52 +00002858 Mutex::Locker locker(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002859
Jim Ingham43c555d2012-07-04 00:35:43 +00002860 size_t num_threads = threads.GetSize();
2861 for (size_t i = 0; i < num_threads; i++)
2862 {
2863 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002864 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002865 StopReason reason = eStopReasonInvalid;
2866 if (stop_info_sp)
2867 reason = stop_info_sp->GetStopReason();
2868 if (reason == eStopReasonBreakpoint
2869 || reason == eStopReasonException)
2870 {
2871 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002872 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2873 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002874 stop_info_sp->GetDescription());
2875 stop_looks_like_crash = true;
2876 break;
2877 }
2878 }
2879 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002880
Jim Ingham43c555d2012-07-04 00:35:43 +00002881 if (stop_looks_like_crash)
2882 {
2883 if (log)
2884 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2885 m_destroy_tried_resuming = true;
Ed Maste81b4c5f2016-01-04 01:43:47 +00002886
2887 // 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 +00002888 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2889 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2890 // have to run the risk of letting those threads proceed a bit.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002891
Jim Ingham43c555d2012-07-04 00:35:43 +00002892 {
Jim Ingham45350372012-09-11 00:08:52 +00002893 Mutex::Locker locker(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002894
Jim Ingham43c555d2012-07-04 00:35:43 +00002895 size_t num_threads = threads.GetSize();
2896 for (size_t i = 0; i < num_threads; i++)
2897 {
2898 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002899 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002900 StopReason reason = eStopReasonInvalid;
2901 if (stop_info_sp)
2902 reason = stop_info_sp->GetStopReason();
2903 if (reason != eStopReasonBreakpoint
2904 && reason != eStopReasonException)
2905 {
2906 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002907 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2908 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002909 thread_sp->SetResumeState(eStateSuspended);
2910 }
2911 }
2912 }
2913 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002914 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002915 }
2916 }
2917 }
2918 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002919
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002920 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002921 int exit_status = SIGABRT;
2922 std::string exit_string;
2923
Greg Clayton6ed95942011-01-22 07:12:45 +00002924 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002925 {
Jim Inghamaab78372011-10-28 01:11:35 +00002926 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002927 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002928 StringExtractorGDBRemote response;
2929 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002930 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002931
Greg Clayton3dedae12013-12-06 21:45:27 +00002932 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002933 {
2934 char packet_cmd = response.GetChar(0);
2935
2936 if (packet_cmd == 'W' || packet_cmd == 'X')
2937 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002938#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002939 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2940 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2941 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2942 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2943 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2944 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2945 // Anyway, so call waitpid here to finally reap it.
2946 PlatformSP platform_sp(GetTarget().GetPlatform());
2947 if (platform_sp && platform_sp->IsHost())
2948 {
2949 int status;
2950 ::pid_t reap_pid;
2951 reap_pid = waitpid (GetID(), &status, WNOHANG);
2952 if (log)
2953 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2954 }
2955#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002956 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002957 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002958 exit_status = response.GetHexU8();
2959 }
2960 else
2961 {
2962 if (log)
2963 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2964 exit_string.assign("got unexpected response to k packet: ");
2965 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002966 }
2967 }
2968 else
2969 {
Jim Inghambabfc382012-06-06 00:32:39 +00002970 if (log)
2971 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2972 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002973 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002974 }
Jim Inghambabfc382012-06-06 00:32:39 +00002975 else
2976 {
2977 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002978 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002979 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002980 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002981 }
Jim Inghambabfc382012-06-06 00:32:39 +00002982 else
2983 {
2984 // If we missed setting the exit status on the way out, do it here.
2985 // NB set exit status can be called multiple times, the first one sets the status.
2986 exit_string.assign("destroying when not connected to debugserver");
2987 }
2988
2989 SetExitStatus(exit_status, exit_string.c_str());
2990
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002991 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002992 KillDebugserverProcess ();
2993 return error;
2994}
2995
Greg Clayton8cda7f02013-05-21 21:55:59 +00002996void
2997ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2998{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002999 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
3000 if (did_exec)
3001 {
3002 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3003 if (log)
3004 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
3005
3006 m_thread_list_real.Clear();
3007 m_thread_list.Clear();
3008 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00003009 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00003010 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00003011
3012 // Scope the lock
3013 {
3014 // Lock the thread stack while we access it
3015 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00003016
3017 // We are are not using non-stop mode, there can only be one last stop
3018 // reply packet, so clear the list.
3019 if (GetTarget().GetNonStopModeEnabled() == false)
3020 m_stop_packet_stack.clear();
3021
Ewan Crawford9aa2da002015-05-27 14:12:34 +00003022 // Add this stop packet to the stop packet stack
3023 // This stack will get popped and examined when we switch to the
3024 // Stopped state
3025 m_stop_packet_stack.push_back(response);
3026 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00003027}
3028
Chaoren Linc963a222015-09-01 16:58:45 +00003029void
3030ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
3031{
3032 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
3033}
3034
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003035//------------------------------------------------------------------
3036// Process Queries
3037//------------------------------------------------------------------
3038
3039bool
3040ProcessGDBRemote::IsAlive ()
3041{
Jason Molenda1d3b3562015-11-05 23:54:29 +00003042 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003043}
3044
3045addr_t
3046ProcessGDBRemote::GetImageInfoAddress()
3047{
Aidan Doddsc0c83852015-05-08 09:36:31 +00003048 // request the link map address via the $qShlibInfoAddr packet
3049 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
3050
3051 // the loaded module list can also provides a link map address
3052 if (addr == LLDB_INVALID_ADDRESS)
3053 {
3054 GDBLoadedModuleInfoList list;
3055 if (GetLoadedModuleList (list).Success())
3056 addr = list.m_link_map;
3057 }
3058
3059 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003060}
3061
Greg Clayton2e309072015-07-17 23:42:28 +00003062void
3063ProcessGDBRemote::WillPublicStop ()
3064{
3065 // See if the GDB remote client supports the JSON threads info.
3066 // If so, we gather stop info for all threads, expedited registers,
3067 // expedited memory, runtime queue information (iOS and MacOSX only),
3068 // and more. Expediting memory will help stack backtracing be much
3069 // faster. Expediting registers will make sure we don't have to read
3070 // the thread registers for GPRs.
3071 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
3072
3073 if (m_jthreadsinfo_sp)
3074 {
3075 // Now set the stop info for each thread and also expedite any registers
3076 // and memory that was in the jThreadsInfo response.
3077 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
3078 if (thread_infos)
3079 {
3080 const size_t n = thread_infos->GetSize();
3081 for (size_t i=0; i<n; ++i)
3082 {
3083 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
3084 if (thread_dict)
3085 SetThreadStopInfo(thread_dict);
3086 }
3087 }
3088 }
3089}
3090
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091//------------------------------------------------------------------
3092// Process Memory
3093//------------------------------------------------------------------
3094size_t
3095ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
3096{
Jason Molenda6076bf42014-05-06 04:34:52 +00003097 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003098 if (size > m_max_memory_size)
3099 {
3100 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003101 // called multiple times in order to complete the task by
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003102 // lldb_private::Process so it is ok to do this.
3103 size = m_max_memory_size;
3104 }
3105
3106 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00003107 int packet_len;
3108 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
Pavel Labath3bf11252015-10-14 12:59:37 +00003109 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
3110 binary_memory_read ? 'x' : 'm', (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00003111 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003112 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003113 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003114 {
Greg Clayton576d8832011-03-22 04:00:09 +00003115 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003116 {
3117 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00003118 if (binary_memory_read)
3119 {
3120 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3121 // 0x7d character escaping that was present in the packet
3122
3123 size_t data_received_size = response.GetBytesLeft();
3124 if (data_received_size > size)
3125 {
3126 // Don't write past the end of BUF if the remote debug server gave us too
3127 // much data for some reason.
3128 data_received_size = size;
3129 }
3130 memcpy (buf, response.GetStringRef().data(), data_received_size);
3131 return data_received_size;
3132 }
3133 else
3134 {
3135 return response.GetHexBytes(buf, size, '\xdd');
3136 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003137 }
Greg Clayton576d8832011-03-22 04:00:09 +00003138 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003139 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003140 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003141 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003142 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003143 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003144 }
3145 else
3146 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003147 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003148 }
3149 return 0;
3150}
3151
3152size_t
3153ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3154{
Jason Molenda6076bf42014-05-06 04:34:52 +00003155 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003156 if (size > m_max_memory_size)
3157 {
3158 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003159 // called multiple times in order to complete the task by
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003160 // lldb_private::Process so it is ok to do this.
3161 size = m_max_memory_size;
3162 }
3163
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003164 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003165 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00003166 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003167 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003168 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003169 {
Greg Clayton576d8832011-03-22 04:00:09 +00003170 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003171 {
3172 error.Clear();
3173 return size;
3174 }
Greg Clayton576d8832011-03-22 04:00:09 +00003175 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003176 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003177 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003178 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003179 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003180 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 +00003181 }
3182 else
3183 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003184 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003185 }
3186 return 0;
3187}
3188
3189lldb::addr_t
3190ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3191{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003192 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003193 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003194
Greg Clayton70b57652011-05-15 01:25:55 +00003195 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003196 switch (supported)
3197 {
3198 case eLazyBoolCalculate:
3199 case eLazyBoolYes:
3200 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3201 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3202 return allocated_addr;
3203
3204 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003205 // Call mmap() to create memory in the inferior..
3206 unsigned prot = 0;
3207 if (permissions & lldb::ePermissionsReadable)
3208 prot |= eMmapProtRead;
3209 if (permissions & lldb::ePermissionsWritable)
3210 prot |= eMmapProtWrite;
3211 if (permissions & lldb::ePermissionsExecutable)
3212 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003213
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003214 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3215 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3216 m_addr_to_mmap_size[allocated_addr] = size;
3217 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003218 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003219 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003220 if (log)
3221 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3222 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003223 break;
3224 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003225
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003226 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003227 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003228 else
3229 error.Clear();
3230 return allocated_addr;
3231}
3232
3233Error
Ed Maste81b4c5f2016-01-04 01:43:47 +00003234ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
Greg Clayton46fb5582011-11-18 07:03:08 +00003235 MemoryRegionInfo &region_info)
3236{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003237
Greg Clayton46fb5582011-11-18 07:03:08 +00003238 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3239 return error;
3240}
3241
3242Error
Johnny Chen64637202012-05-23 21:09:52 +00003243ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3244{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003245
Johnny Chen64637202012-05-23 21:09:52 +00003246 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3247 return error;
3248}
3249
3250Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003251ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3252{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003253 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003254 return error;
3255}
3256
3257Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003258ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3259{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003260 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003261 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3262
3263 switch (supported)
3264 {
3265 case eLazyBoolCalculate:
Ed Maste81b4c5f2016-01-04 01:43:47 +00003266 // We should never be deallocating memory without allocating memory
Greg Clayton70b57652011-05-15 01:25:55 +00003267 // first so we should never get eLazyBoolCalculate
3268 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3269 break;
3270
3271 case eLazyBoolYes:
3272 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003273 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003274 break;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003275
Greg Clayton70b57652011-05-15 01:25:55 +00003276 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003277 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003278 {
3279 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003280 if (pos != m_addr_to_mmap_size.end() &&
3281 InferiorCallMunmap(this, addr, pos->second))
3282 m_addr_to_mmap_size.erase (pos);
3283 else
Daniel Malead01b2952012-11-29 21:49:15 +00003284 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003285 }
3286 break;
3287 }
3288
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003289 return error;
3290}
3291
Eugene Zelenko0722f082015-10-24 01:28:05 +00003292
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003293//------------------------------------------------------------------
3294// Process STDIO
3295//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003296size_t
3297ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3298{
3299 if (m_stdio_communication.IsConnected())
3300 {
3301 ConnectionStatus status;
3302 m_stdio_communication.Write(src, src_len, status, NULL);
3303 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003304 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003305 {
3306 m_gdb_comm.SendStdinNotification(src, src_len);
3307 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003308 return 0;
3309}
3310
3311Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003312ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003313{
3314 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003315 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003316
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003317 // Get logging info
3318 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003319 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003320
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003321 // Get the breakpoint address
3322 const addr_t addr = bp_site->GetLoadAddress();
3323
3324 // Log that a breakpoint was requested
3325 if (log)
3326 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3327
3328 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003329 if (bp_site->IsEnabled())
3330 {
3331 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003332 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 +00003333 return error;
3334 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003335
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003336 // Get the software breakpoint trap opcode size
3337 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3338
3339 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3340 // is supported by the remote stub. These are set to true by default, and later set to false
3341 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3342 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3343 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3344 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3345 // skip over software breakpoints.
3346 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3347 {
3348 // Try to send off a software breakpoint packet ($Z0)
3349 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003350 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003351 // The breakpoint was placed successfully
3352 bp_site->SetEnabled(true);
3353 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003354 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003355 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003356
3357 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3358 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3359 // or if we have learned that this breakpoint type is unsupported. To do this, we
3360 // must test the support boolean for this breakpoint type to see if it now indicates that
3361 // this breakpoint type is unsupported. If they are still supported then we should return
3362 // with the error code. If they are now unsupported, then we would like to fall through
3363 // and try another form of breakpoint.
3364 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3365 return error;
3366
3367 // We reach here when software breakpoints have been found to be unsupported. For future
3368 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3369 // known not to be supported.
3370 if (log)
3371 log->Printf("Software breakpoints are unsupported");
3372
3373 // So we will fall through and try a hardware breakpoint
3374 }
3375
3376 // The process of setting a hardware breakpoint is much the same as above. We check the
3377 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3378 // will try to set this breakpoint with a hardware breakpoint.
3379 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3380 {
3381 // Try to send off a hardware breakpoint packet ($Z1)
3382 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003383 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003384 // The breakpoint was placed successfully
3385 bp_site->SetEnabled(true);
3386 bp_site->SetType(BreakpointSite::eHardware);
3387 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003388 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003389
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003390 // Check if the error was something other then an unsupported breakpoint type
3391 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3392 {
3393 // Unable to set this hardware breakpoint
3394 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3395 return error;
3396 }
3397
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003398 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003399 if (log)
3400 log->Printf("Hardware breakpoints are unsupported");
3401
3402 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003403 }
3404
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003405 // Don't fall through when hardware breakpoints were specifically requested
3406 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003407 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003408 error.SetErrorString("hardware breakpoints are not supported");
3409 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003410 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003411
3412 // As a last resort we want to place a manual breakpoint. An instruction
3413 // is placed into the process memory using memory write packets.
3414 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003415}
3416
3417Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003418ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003419{
3420 Error error;
3421 assert (bp_site != NULL);
3422 addr_t addr = bp_site->GetLoadAddress();
3423 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003424 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003425 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003426 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003427
3428 if (bp_site->IsEnabled())
3429 {
3430 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3431
Greg Clayton8b82f082011-04-12 05:54:46 +00003432 BreakpointSite::Type bp_type = bp_site->GetType();
3433 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003434 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003435 case BreakpointSite::eSoftware:
3436 error = DisableSoftwareBreakpoint (bp_site);
3437 break;
3438
3439 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003440 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003441 error.SetErrorToGenericError();
3442 break;
3443
3444 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003445 {
3446 GDBStoppointType stoppoint_type;
3447 if (bp_site->IsHardware())
3448 stoppoint_type = eBreakpointHardware;
3449 else
3450 stoppoint_type = eBreakpointSoftware;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003451
Jim Inghama04ef752014-03-07 11:18:02 +00003452 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003453 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003454 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003455 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003456 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003457 if (error.Success())
3458 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003459 }
3460 else
3461 {
3462 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003463 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 +00003464 return error;
3465 }
3466
3467 if (error.Success())
3468 error.SetErrorToGenericError();
3469 return error;
3470}
3471
Johnny Chen11309a32011-09-06 22:38:36 +00003472// Pre-requisite: wp != NULL.
3473static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003474GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003475{
3476 assert(wp);
3477 bool watch_read = wp->WatchpointRead();
3478 bool watch_write = wp->WatchpointWrite();
3479
3480 // watch_read and watch_write cannot both be false.
3481 assert(watch_read || watch_write);
3482 if (watch_read && watch_write)
3483 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003484 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003485 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003486 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003487 return eWatchpointWrite;
3488}
3489
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003490Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003491ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003492{
3493 Error error;
3494 if (wp)
3495 {
3496 user_id_t watchID = wp->GetID();
3497 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003498 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003499 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003500 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003501 if (wp->IsEnabled())
3502 {
3503 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003504 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 +00003505 return error;
3506 }
Johnny Chen11309a32011-09-06 22:38:36 +00003507
3508 GDBStoppointType type = GetGDBStoppointType(wp);
3509 // Pass down an appropriate z/Z packet...
3510 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003511 {
Johnny Chen11309a32011-09-06 22:38:36 +00003512 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3513 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003514 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003515 return error;
3516 }
3517 else
3518 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003519 }
Johnny Chen11309a32011-09-06 22:38:36 +00003520 else
3521 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003522 }
3523 else
3524 {
Johnny Chen01a67862011-10-14 00:42:25 +00003525 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003526 }
3527 if (error.Success())
3528 error.SetErrorToGenericError();
3529 return error;
3530}
3531
3532Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003533ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003534{
3535 Error error;
3536 if (wp)
3537 {
3538 user_id_t watchID = wp->GetID();
3539
Greg Clayton5160ce52013-03-27 23:08:40 +00003540 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003541
3542 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003543
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003544 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003545 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003546
Johnny Chen11309a32011-09-06 22:38:36 +00003547 if (!wp->IsEnabled())
3548 {
3549 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003550 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 +00003551 // See also 'class WatchpointSentry' within StopInfo.cpp.
3552 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3553 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003554 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003555 return error;
3556 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003557
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003558 if (wp->IsHardware())
3559 {
Johnny Chen11309a32011-09-06 22:38:36 +00003560 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003561 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003562 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3563 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003564 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003565 return error;
3566 }
3567 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00003568 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003569 }
3570 // TODO: clear software watchpoints if we implement them
3571 }
3572 else
3573 {
Johnny Chen01a67862011-10-14 00:42:25 +00003574 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003575 }
3576 if (error.Success())
3577 error.SetErrorToGenericError();
3578 return error;
3579}
3580
3581void
3582ProcessGDBRemote::Clear()
3583{
3584 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003585 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003586 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003587}
3588
3589Error
3590ProcessGDBRemote::DoSignal (int signo)
3591{
3592 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003593 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003594 if (log)
3595 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3596
3597 if (!m_gdb_comm.SendAsyncSignal (signo))
3598 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3599 return error;
3600}
3601
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003602Error
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003603ProcessGDBRemote::EstablishConnectionIfNeeded (const ProcessInfo &process_info)
3604{
3605 // Make sure we aren't already connected?
3606 if (m_gdb_comm.IsConnected())
3607 return Error();
3608
3609 PlatformSP platform_sp (GetTarget ().GetPlatform ());
3610 if (platform_sp && !platform_sp->IsHost ())
3611 return Error("Lost debug server connection");
3612
3613 auto error = LaunchAndConnectToDebugserver (process_info);
3614 if (error.Fail())
3615 {
3616 const char *error_string = error.AsCString();
3617 if (error_string == nullptr)
3618 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3619 }
3620 return error;
3621}
3622
3623Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003624ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003625{
3626 Error error;
3627 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3628 {
3629 // If we locate debugserver, keep that located version around
3630 static FileSpec g_debugserver_file_spec;
3631
Han Ming Ong84647042012-02-25 01:07:38 +00003632 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003633 // Make debugserver run in its own session so signals generated by
3634 // special terminal key sequences (^C) don't affect debugserver.
3635 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3636
Greg Clayton91a9b2472013-12-04 19:19:12 +00003637 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3638 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003639
Todd Fiala013434e2014-07-09 01:29:05 +00003640#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003641 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003642 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003643 uint16_t port = get_random_port ();
3644#else
3645 // Set hostname being NULL to do the reverse connect where debugserver
3646 // will bind to port zero and it will communicate back to us the port
3647 // that we will connect to
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003648 const char *hostname = nullptr;
Greg Claytonfda4fab2014-01-10 22:24:11 +00003649 uint16_t port = 0;
3650#endif
3651
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003652 StreamString url_str;
3653 const char* url = nullptr;
3654 if (hostname != nullptr)
3655 {
3656 url_str.Printf("%s:%u", hostname, port);
3657 url = url_str.GetData();
3658 }
3659
3660 error = m_gdb_comm.StartDebugserverProcess (url,
Greg Clayton6988abc2015-10-19 20:44:01 +00003661 GetTarget().GetPlatform().get(),
Greg Clayton00fe87b2013-12-05 22:58:22 +00003662 debugserver_launch_info,
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003663 &port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003664
3665 if (error.Success ())
3666 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003667 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003668 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003669
3670 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3671 StartAsyncThread ();
Ed Maste81b4c5f2016-01-04 01:43:47 +00003672
Greg Clayton91a9b2472013-12-04 19:19:12 +00003673 if (error.Fail())
3674 {
3675 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3676
3677 if (log)
3678 log->Printf("failed to start debugserver process: %s", error.AsCString());
3679 return error;
3680 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003681
Greg Clayton00fe87b2013-12-05 22:58:22 +00003682 if (m_gdb_comm.IsConnected())
3683 {
3684 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3685 ConnectToDebugserver (NULL);
3686 }
3687 else
3688 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003689 StreamString connect_url;
3690 connect_url.Printf("connect://%s:%u", hostname, port);
3691 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003692 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003693
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003694 }
3695 return error;
3696}
3697
3698bool
3699ProcessGDBRemote::MonitorDebugserverProcess
3700(
3701 void *callback_baton,
3702 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003703 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003704 int signo, // Zero for no signal
3705 int exit_status // Exit value of process if signal is zero
3706)
3707{
Greg Claytone4e45922011-11-16 05:37:56 +00003708 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3709 // and might not exist anymore, so we need to carefully try to get the
3710 // target for this process first since we have a race condition when
Ed Maste81b4c5f2016-01-04 01:43:47 +00003711 // we are done running between getting the notice that the inferior
Greg Claytone4e45922011-11-16 05:37:56 +00003712 // process has died and the debugserver that was debugging this process.
3713 // In our test suite, we are also continually running process after
3714 // process, so we must be very careful to make sure:
3715 // 1 - process object hasn't been deleted already
3716 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003717
3718 // "debugserver_pid" argument passed in is the process ID for
3719 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003720 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003721
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003722 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003723
Greg Claytone4e45922011-11-16 05:37:56 +00003724 // Get a shared pointer to the target that has a matching process pointer.
3725 // This target could be gone, or the target could already have a new process
3726 // object inside of it
3727 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3728
Greg Clayton6779606a2011-01-22 23:43:18 +00003729 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003730 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 +00003731
Greg Claytone4e45922011-11-16 05:37:56 +00003732 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003733 {
Greg Claytone4e45922011-11-16 05:37:56 +00003734 // We found a process in a target that matches, but another thread
3735 // might be in the process of launching a new process that will
3736 // soon replace it, so get a shared pointer to the process so we
3737 // can keep it alive.
3738 ProcessSP process_sp (target_sp->GetProcessSP());
3739 // Now we have a shared pointer to the process that can't go away on us
3740 // so we now make sure it was the same as the one passed in, and also make
Ed Maste81b4c5f2016-01-04 01:43:47 +00003741 // sure that our previous "process *" didn't get deleted and have a new
Greg Claytone4e45922011-11-16 05:37:56 +00003742 // "process *" created in its place with the same pointer. To verify this
3743 // we make sure the process has our debugserver process ID. If we pass all
3744 // of these tests, then we are sure that this process is the one we were
3745 // looking for.
3746 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003747 {
Greg Claytone4e45922011-11-16 05:37:56 +00003748 // Sleep for a half a second to make sure our inferior process has
3749 // time to set its exit status before we set it incorrectly when
3750 // both the debugserver and the inferior process shut down.
3751 usleep (500000);
3752 // If our process hasn't yet exited, debugserver might have died.
3753 // If the process did exit, the we are reaping it.
3754 const StateType state = process->GetState();
Ed Maste81b4c5f2016-01-04 01:43:47 +00003755
Greg Claytone4e45922011-11-16 05:37:56 +00003756 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3757 state != eStateInvalid &&
3758 state != eStateUnloaded &&
3759 state != eStateExited &&
3760 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003761 {
Greg Claytone4e45922011-11-16 05:37:56 +00003762 char error_str[1024];
3763 if (signo)
3764 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003765 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003766 if (signal_cstr)
3767 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3768 else
3769 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3770 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003771 else
Greg Claytone4e45922011-11-16 05:37:56 +00003772 {
3773 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3774 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003775
Greg Claytone4e45922011-11-16 05:37:56 +00003776 process->SetExitStatus (-1, error_str);
3777 }
3778 // Debugserver has exited we need to let our ProcessGDBRemote
3779 // know that it no longer has a debugserver instance
3780 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003781 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003782 }
3783 return true;
3784}
3785
3786void
3787ProcessGDBRemote::KillDebugserverProcess ()
3788{
Greg Claytonfbb76342013-11-20 21:07:01 +00003789 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003790 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3791 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003792 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003793 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3794 }
3795}
3796
3797void
3798ProcessGDBRemote::Initialize()
3799{
Davide Italianoc8d69822015-04-03 04:24:32 +00003800 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003801
Davide Italianoc8d69822015-04-03 04:24:32 +00003802 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003803 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003804 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3805 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003806 CreateInstance,
3807 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003808 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003809}
3810
Greg Clayton7f982402013-07-15 22:54:20 +00003811void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003812ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003813{
3814 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3815 {
3816 const bool is_global_setting = true;
3817 PluginManager::CreateSettingForProcessPlugin (debugger,
3818 GetGlobalPluginProperties()->GetValueProperties(),
3819 ConstString ("Properties for the gdb-remote process plug-in."),
3820 is_global_setting);
3821 }
3822}
3823
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003824bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003825ProcessGDBRemote::StartAsyncThread ()
3826{
Greg Clayton5160ce52013-03-27 23:08:40 +00003827 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003828
3829 if (log)
3830 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003831
Jim Ingham455fa5c2012-11-01 01:15:33 +00003832 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003833 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003834 {
3835 // Create a thread that watches our internal state and controls which
3836 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003837
3838 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003839 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003840 else if (log)
3841 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003842
Zachary Turneracee96a2014-09-23 18:32:09 +00003843 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003844}
3845
3846void
3847ProcessGDBRemote::StopAsyncThread ()
3848{
Greg Clayton5160ce52013-03-27 23:08:40 +00003849 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003850
3851 if (log)
3852 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3853
Jim Ingham455fa5c2012-11-01 01:15:33 +00003854 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003855 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003856 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003857 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003858
Jim Ingham455fa5c2012-11-01 01:15:33 +00003859 // This will shut down the async thread.
3860 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3861
3862 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003863 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003864 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003865 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003866 else if (log)
3867 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003868}
3869
Ewan Crawford76df2882015-06-23 12:32:06 +00003870bool
3871ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3872{
3873 // get the packet at a string
3874 const std::string &pkt = packet.GetStringRef();
3875 // skip %stop:
3876 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3877
3878 // pass as a thread stop info packet
3879 SetLastStopPacket(stop_info);
3880
3881 // check for more stop reasons
3882 HandleStopReplySequence();
3883
3884 // if the process is stopped then we need to fake a resume
3885 // so that we can stop properly with the new break. This
3886 // is possible due to SetPrivateState() broadcasting the
3887 // state change as a side effect.
3888 if (GetPrivateState() == lldb::StateType::eStateStopped)
3889 {
3890 SetPrivateState(lldb::StateType::eStateRunning);
3891 }
3892
3893 // since we have some stopped packets we can halt the process
3894 SetPrivateState(lldb::StateType::eStateStopped);
3895
3896 return true;
3897}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003898
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003899thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003900ProcessGDBRemote::AsyncThread (void *arg)
3901{
3902 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3903
Greg Clayton5160ce52013-03-27 23:08:40 +00003904 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003905 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003906 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003907
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003908 EventSP event_sp;
Pavel Labath50556852015-09-03 09:36:22 +00003909 bool done = false;
3910 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003911 {
Pavel Labath50556852015-09-03 09:36:22 +00003912 if (log)
3913 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
3914 if (process->m_async_listener.WaitForEvent (NULL, event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003915 {
Pavel Labath50556852015-09-03 09:36:22 +00003916 const uint32_t event_type = event_sp->GetType();
3917 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003918 {
3919 if (log)
Pavel Labath50556852015-09-03 09:36:22 +00003920 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3921
3922 switch (event_type)
3923 {
3924 case eBroadcastBitAsyncContinue:
3925 {
3926 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3927
3928 if (continue_packet)
3929 {
3930 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3931 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3932 if (log)
3933 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3934
3935 if (::strstr (continue_cstr, "vAttach") == NULL)
3936 process->SetPrivateState(eStateRunning);
3937 StringExtractorGDBRemote response;
3938
3939 // If in Non-Stop-Mode
3940 if (process->GetTarget().GetNonStopModeEnabled())
3941 {
3942 // send the vCont packet
3943 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
3944 {
3945 // Something went wrong
3946 done = true;
3947 break;
3948 }
3949 }
3950 // If in All-Stop-Mode
3951 else
3952 {
3953 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3954
3955 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3956 // The thread ID list might be contained within the "response", or the stop reply packet that
3957 // caused the stop. So clear it now before we give the stop reply packet to the process
3958 // using the process->SetLastStopPacket()...
3959 process->ClearThreadIDList ();
3960
3961 switch (stop_state)
3962 {
3963 case eStateStopped:
3964 case eStateCrashed:
3965 case eStateSuspended:
3966 process->SetLastStopPacket (response);
3967 process->SetPrivateState (stop_state);
3968 break;
3969
3970 case eStateExited:
3971 {
3972 process->SetLastStopPacket (response);
3973 process->ClearThreadIDList();
3974 response.SetFilePos(1);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003975
Pavel Labath50556852015-09-03 09:36:22 +00003976 int exit_status = response.GetHexU8();
3977 const char *desc_cstr = NULL;
3978 StringExtractor extractor;
3979 std::string desc_string;
3980 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3981 {
3982 std::string desc_token;
3983 while (response.GetNameColonValue (desc_token, desc_string))
3984 {
3985 if (desc_token == "description")
3986 {
3987 extractor.GetStringRef().swap(desc_string);
3988 extractor.SetFilePos(0);
3989 extractor.GetHexByteString (desc_string);
3990 desc_cstr = desc_string.c_str();
3991 }
3992 }
3993 }
3994 process->SetExitStatus(exit_status, desc_cstr);
3995 done = true;
3996 break;
3997 }
3998 case eStateInvalid:
3999 {
4000 // Check to see if we were trying to attach and if we got back
4001 // the "E87" error code from debugserver -- this indicates that
4002 // the process is not debuggable. Return a slightly more helpful
4003 // error message about why the attach failed.
4004 if (::strstr (continue_cstr, "vAttach") != NULL
4005 && response.GetError() == 0x87)
4006 {
4007 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
4008 }
4009 // E01 code from vAttach means that the attach failed
4010 if (::strstr (continue_cstr, "vAttach") != NULL
4011 && response.GetError() == 0x1)
4012 {
4013 process->SetExitStatus(-1, "unable to attach");
4014 }
4015 else
4016 {
4017 process->SetExitStatus(-1, "lost connection");
4018 }
4019 break;
4020 }
4021
4022 default:
4023 process->SetPrivateState (stop_state);
4024 break;
4025 } // switch(stop_state)
4026 } // else // if in All-stop-mode
4027 } // if (continue_packet)
4028 } // case eBroadcastBitAysncContinue
4029 break;
4030
4031 case eBroadcastBitAsyncThreadShouldExit:
4032 if (log)
4033 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
4034 done = true;
4035 break;
4036
4037 default:
4038 if (log)
4039 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4040 done = true;
4041 break;
4042 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004043 }
Pavel Labath50556852015-09-03 09:36:22 +00004044 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
4045 {
4046 switch (event_type)
4047 {
4048 case Communication::eBroadcastBitReadThreadDidExit:
4049 process->SetExitStatus (-1, "lost connection");
4050 done = true;
4051 break;
4052
4053 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
4054 {
4055 lldb_private::Event *event = event_sp.get();
4056 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
4057 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
4058 // Hand this over to the process to handle
4059 process->HandleNotifyPacket(notify);
4060 break;
4061 }
4062
4063 default:
4064 if (log)
4065 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4066 done = true;
4067 break;
4068 }
4069 }
4070 }
4071 else
4072 {
4073 if (log)
4074 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
4075 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004076 }
4077 }
4078
4079 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004080 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004081
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004082 return NULL;
4083}
4084
Greg Claytone996fd32011-03-08 22:40:15 +00004085//uint32_t
4086//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4087//{
4088// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
4089// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
4090// if (m_local_debugserver)
4091// {
4092// return Host::ListProcessesMatchingName (name, matches, pids);
4093// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004094// else
Greg Claytone996fd32011-03-08 22:40:15 +00004095// {
4096// // FIXME: Implement talking to the remote debugserver.
4097// return 0;
4098// }
4099//
4100//}
4101//
Jim Ingham1c823b42011-01-22 01:33:44 +00004102bool
4103ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004104 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00004105 lldb::user_id_t break_id,
4106 lldb::user_id_t break_loc_id)
4107{
Ed Maste81b4c5f2016-01-04 01:43:47 +00004108 // 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 +00004109 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004110 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00004111 if (log)
4112 log->Printf("Hit New Thread Notification breakpoint.");
4113 return false;
4114}
4115
Eugene Zelenko0722f082015-10-24 01:28:05 +00004116
Jim Ingham1c823b42011-01-22 01:33:44 +00004117bool
4118ProcessGDBRemote::StartNoticingNewThreads()
4119{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004120 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00004121 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004122 {
Greg Clayton4116e932012-05-15 02:33:01 +00004123 if (log && log->GetVerbose())
4124 log->Printf("Enabled noticing new thread breakpoint.");
4125 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004126 }
Greg Clayton4116e932012-05-15 02:33:01 +00004127 else
Jim Ingham1c823b42011-01-22 01:33:44 +00004128 {
Zachary Turner7529df92015-09-01 20:02:29 +00004129 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Clayton4116e932012-05-15 02:33:01 +00004130 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004131 {
Zachary Turner7529df92015-09-01 20:02:29 +00004132 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget());
Greg Clayton4116e932012-05-15 02:33:01 +00004133 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004134 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004135 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00004136 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4137 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004138 }
4139 else
4140 {
4141 if (log)
4142 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00004143 }
4144 }
4145 }
Greg Clayton4116e932012-05-15 02:33:01 +00004146 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004147}
4148
4149bool
4150ProcessGDBRemote::StopNoticingNewThreads()
Ed Maste81b4c5f2016-01-04 01:43:47 +00004151{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004152 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004153 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004154 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004155
4156 if (m_thread_create_bp_sp)
4157 m_thread_create_bp_sp->SetEnabled(false);
4158
Jim Ingham1c823b42011-01-22 01:33:44 +00004159 return true;
4160}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004161
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004162DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004163ProcessGDBRemote::GetDynamicLoader ()
4164{
4165 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004166 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004167 return m_dyld_ap.get();
4168}
Jim Ingham1c823b42011-01-22 01:33:44 +00004169
Jason Molendaa3329782014-03-29 18:54:20 +00004170Error
4171ProcessGDBRemote::SendEventData(const char *data)
4172{
4173 int return_value;
4174 bool was_supported;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004175
Jason Molendaa3329782014-03-29 18:54:20 +00004176 Error error;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004177
Jason Molendaa3329782014-03-29 18:54:20 +00004178 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4179 if (return_value != 0)
4180 {
4181 if (!was_supported)
4182 error.SetErrorString("Sending events is not supported for this process.");
4183 else
4184 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4185 }
4186 return error;
4187}
4188
Steve Pucci03904ac2014-03-04 23:18:46 +00004189const DataBufferSP
4190ProcessGDBRemote::GetAuxvData()
4191{
4192 DataBufferSP buf;
4193 if (m_gdb_comm.GetQXferAuxvReadSupported())
4194 {
4195 std::string response_string;
4196 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4197 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4198 }
4199 return buf;
4200}
4201
Jason Molenda705b1802014-06-13 02:37:02 +00004202StructuredData::ObjectSP
4203ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4204{
4205 StructuredData::ObjectSP object_sp;
4206
4207 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4208 {
4209 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4210 SystemRuntime *runtime = GetSystemRuntime();
4211 if (runtime)
4212 {
4213 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4214 }
4215 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4216
4217 StreamString packet;
4218 packet << "jThreadExtendedInfo:";
4219 args_dict->Dump (packet);
4220
4221 // FIXME the final character of a JSON dictionary, '}', is the escape
4222 // character in gdb-remote binary mode. lldb currently doesn't escape
4223 // these characters in its packet output -- so we add the quoted version
4224 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004225 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004226 packet << (char) (0x7d ^ 0x20);
4227
4228 StringExtractorGDBRemote response;
4229 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4230 {
4231 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4232 if (response_type == StringExtractorGDBRemote::eResponse)
4233 {
4234 if (!response.Empty())
4235 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004236 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4237 }
4238 }
4239 }
4240 }
4241 return object_sp;
4242}
4243
4244StructuredData::ObjectSP
4245ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4246{
4247 StructuredData::ObjectSP object_sp;
4248
4249 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4250 {
Jason Molenda1d3b3562015-11-05 23:54:29 +00004251 // Scope for the scoped timeout object
4252 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
4253
Jason Molenda20ee21b2015-07-10 23:15:22 +00004254 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4255 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4256 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4257
4258 StreamString packet;
4259 packet << "jGetLoadedDynamicLibrariesInfos:";
4260 args_dict->Dump (packet);
4261
4262 // FIXME the final character of a JSON dictionary, '}', is the escape
4263 // character in gdb-remote binary mode. lldb currently doesn't escape
4264 // these characters in its packet output -- so we add the quoted version
4265 // of the } character here manually in case we talk to a debugserver which
4266 // un-escapes the characters at packet read time.
4267 packet << (char) (0x7d ^ 0x20);
4268
4269 StringExtractorGDBRemote response;
4270 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4271 {
4272 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4273 if (response_type == StringExtractorGDBRemote::eResponse)
4274 {
4275 if (!response.Empty())
4276 {
Jason Molenda705b1802014-06-13 02:37:02 +00004277 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4278 }
4279 }
4280 }
4281 }
4282 return object_sp;
4283}
4284
Jason Molenda6076bf42014-05-06 04:34:52 +00004285// Establish the largest memory read/write payloads we should use.
4286// If the remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004287//
4288// If the remote stub's max packet size is crazy large, use a
Jason Molenda6076bf42014-05-06 04:34:52 +00004289// reasonable largeish default.
4290//
4291// If the remote stub doesn't advertise a max packet size, use a
4292// conservative default.
4293
4294void
4295ProcessGDBRemote::GetMaxMemorySize()
4296{
4297 const uint64_t reasonable_largeish_default = 128 * 1024;
4298 const uint64_t conservative_default = 512;
4299
4300 if (m_max_memory_size == 0)
4301 {
4302 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4303 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4304 {
4305 // Save the stub's claimed maximum packet size
4306 m_remote_stub_max_memory_size = stub_max_size;
4307
4308 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004309 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004310 if (stub_max_size > reasonable_largeish_default)
4311 {
4312 stub_max_size = reasonable_largeish_default;
4313 }
4314
4315 m_max_memory_size = stub_max_size;
4316 }
4317 else
4318 {
4319 m_max_memory_size = conservative_default;
4320 }
4321 }
4322}
4323
4324void
4325ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4326{
4327 if (user_specified_max != 0)
4328 {
4329 GetMaxMemorySize ();
4330
4331 if (m_remote_stub_max_memory_size != 0)
4332 {
4333 if (m_remote_stub_max_memory_size < user_specified_max)
4334 {
4335 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4336 // as the remote stub says we can go.
4337 }
4338 else
4339 {
4340 m_max_memory_size = user_specified_max; // user's packet size is good
4341 }
4342 }
4343 else
4344 {
4345 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4346 }
4347 }
4348}
4349
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004350bool
4351ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4352 const ArchSpec& arch,
4353 ModuleSpec &module_spec)
4354{
4355 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4356
4357 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4358 {
4359 if (log)
4360 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4361 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4362 arch.GetTriple ().getTriple ().c_str ());
4363 return false;
4364 }
4365
4366 if (log)
4367 {
4368 StreamString stream;
4369 module_spec.Dump (stream);
4370 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4371 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4372 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4373 }
4374
4375 return true;
4376}
4377
Jim Ingham13c30d22015-11-05 22:33:17 +00004378bool
4379ProcessGDBRemote::GetHostOSVersion(uint32_t &major,
4380 uint32_t &minor,
4381 uint32_t &update)
4382{
4383 if (m_gdb_comm.GetOSVersion(major, minor, update))
4384 return true;
4385 // We failed to get the host OS version, defer to the base
4386 // implementation to correctly invalidate the arguments.
4387 return Process::GetHostOSVersion(major, minor, update);
4388}
4389
Colin Rileyc3c95b22015-04-16 15:51:33 +00004390namespace {
4391
4392typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004393
4394typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004395struct RegisterSetInfo
4396{
4397 ConstString name;
4398};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004399
Greg Claytond04f0ed2015-05-26 18:00:51 +00004400typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004401
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004402struct GdbServerTargetInfo
4403{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004404 std::string arch;
4405 std::string osabi;
4406 stringVec includes;
4407 RegisterSetMap reg_set_map;
4408 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004409};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004410
Colin Rileyc3c95b22015-04-16 15:51:33 +00004411bool
Jason Molenda21586c82015-09-09 03:36:24 +00004412ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004413{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004414 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004415 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004416
Jason Molenda63bd0db2015-09-15 23:20:34 +00004417 uint32_t cur_reg_num = 0;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004418 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004419
Jason Molenda63bd0db2015-09-15 23:20:34 +00004420 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 +00004421 std::string gdb_group;
4422 std::string gdb_type;
4423 ConstString reg_name;
4424 ConstString alt_name;
4425 ConstString set_name;
4426 std::vector<uint32_t> value_regs;
4427 std::vector<uint32_t> invalidate_regs;
4428 bool encoding_set = false;
4429 bool format_set = false;
4430 RegisterInfo reg_info = { NULL, // Name
4431 NULL, // Alt name
4432 0, // byte size
4433 reg_offset, // offset
4434 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +00004435 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004436 {
Jason Molendabf67a302015-09-01 05:17:01 +00004437 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004438 LLDB_INVALID_REGNUM, // DWARF reg num
4439 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +00004440 cur_reg_num, // process plugin reg num
4441 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004442 },
4443 NULL,
4444 NULL
4445 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004446
Jason Molenda63bd0db2015-09-15 23:20:34 +00004447 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 +00004448 if (name == "name")
4449 {
4450 reg_name.SetString(value);
4451 }
4452 else if (name == "bitsize")
4453 {
4454 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4455 }
4456 else if (name == "type")
4457 {
4458 gdb_type = value.str();
4459 }
4460 else if (name == "group")
4461 {
4462 gdb_group = value.str();
4463 }
4464 else if (name == "regnum")
4465 {
4466 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4467 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004468 {
Jason Molenda63bd0db2015-09-15 23:20:34 +00004469 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004470 }
4471 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004472 else if (name == "offset")
4473 {
4474 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4475 }
4476 else if (name == "altname")
4477 {
4478 alt_name.SetString(value);
4479 }
4480 else if (name == "encoding")
4481 {
4482 encoding_set = true;
4483 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4484 }
4485 else if (name == "format")
4486 {
4487 format_set = true;
4488 Format format = eFormatInvalid;
4489 if (Args::StringToFormat (value.data(), format, NULL).Success())
4490 reg_info.format = format;
4491 else if (value == "vector-sint8")
4492 reg_info.format = eFormatVectorOfSInt8;
4493 else if (value == "vector-uint8")
4494 reg_info.format = eFormatVectorOfUInt8;
4495 else if (value == "vector-sint16")
4496 reg_info.format = eFormatVectorOfSInt16;
4497 else if (value == "vector-uint16")
4498 reg_info.format = eFormatVectorOfUInt16;
4499 else if (value == "vector-sint32")
4500 reg_info.format = eFormatVectorOfSInt32;
4501 else if (value == "vector-uint32")
4502 reg_info.format = eFormatVectorOfUInt32;
4503 else if (value == "vector-float32")
4504 reg_info.format = eFormatVectorOfFloat32;
4505 else if (value == "vector-uint128")
4506 reg_info.format = eFormatVectorOfUInt128;
4507 }
4508 else if (name == "group_id")
4509 {
4510 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4511 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4512 if (pos != target_info.reg_set_map.end())
4513 set_name = pos->second.name;
4514 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004515 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004516 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004517 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004518 }
4519 else if (name == "dwarf_regnum")
4520 {
4521 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4522 }
4523 else if (name == "generic")
4524 {
4525 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4526 }
4527 else if (name == "value_regnums")
4528 {
4529 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4530 }
4531 else if (name == "invalidate_regnums")
4532 {
4533 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4534 }
4535 else
4536 {
4537 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4538 }
4539 return true; // Keep iterating through all attributes
4540 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004541
Greg Claytond04f0ed2015-05-26 18:00:51 +00004542 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004543 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004544 if (gdb_type.find("int") == 0)
4545 {
4546 reg_info.format = eFormatHex;
4547 reg_info.encoding = eEncodingUint;
4548 }
4549 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4550 {
4551 reg_info.format = eFormatAddressInfo;
4552 reg_info.encoding = eEncodingUint;
4553 }
4554 else if (gdb_type == "i387_ext" || gdb_type == "float")
4555 {
4556 reg_info.format = eFormatFloat;
4557 reg_info.encoding = eEncodingIEEE754;
4558 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004559 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004560
Greg Claytond04f0ed2015-05-26 18:00:51 +00004561 // Only update the register set name if we didn't get a "reg_set" attribute.
4562 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4563 if (!set_name && !gdb_group.empty())
4564 set_name.SetCString(gdb_group.c_str());
Ed Maste81b4c5f2016-01-04 01:43:47 +00004565
Greg Claytond04f0ed2015-05-26 18:00:51 +00004566 reg_info.byte_offset = reg_offset;
4567 assert (reg_info.byte_size != 0);
4568 reg_offset += reg_info.byte_size;
4569 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004570 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004571 value_regs.push_back(LLDB_INVALID_REGNUM);
4572 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004573 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004574 if (!invalidate_regs.empty())
4575 {
4576 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4577 reg_info.invalidate_regs = invalidate_regs.data();
4578 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004579
Jason Molenda63bd0db2015-09-15 23:20:34 +00004580 ++cur_reg_num;
Jason Molenda21586c82015-09-09 03:36:24 +00004581 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004582 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004583
Greg Claytond04f0ed2015-05-26 18:00:51 +00004584 return true; // Keep iterating through all "reg" elements
4585 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004586 return true;
4587}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004588
Eugene Zelenko0722f082015-10-24 01:28:05 +00004589} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004590
Colin Rileyc3c95b22015-04-16 15:51:33 +00004591
4592// query the target of gdb-remote for extended target information
4593// return: 'true' on success
4594// 'false' on failure
4595bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004596ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004597{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004598 // Make sure LLDB has an XML parser it can use first
4599 if (!XMLDocument::XMLEnabled())
4600 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004601
4602 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004603
4604 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004605
4606 // check that we have extended feature read support
4607 if ( !comm.GetQXferFeaturesReadSupported( ) )
4608 return false;
4609
4610 // request the target xml file
4611 std::string raw;
4612 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004613 if (!comm.ReadExtFeature(ConstString("features"),
4614 ConstString("target.xml"),
4615 raw,
4616 lldberr))
4617 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004618 return false;
4619 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004620
Colin Rileyc3c95b22015-04-16 15:51:33 +00004621
Greg Claytond04f0ed2015-05-26 18:00:51 +00004622 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004623
Greg Claytond04f0ed2015-05-26 18:00:51 +00004624 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004625 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004626 GdbServerTargetInfo target_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004627
Greg Claytond04f0ed2015-05-26 18:00:51 +00004628 XMLNode target_node = xml_document.GetRootElement("target");
4629 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004630 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004631 XMLNode feature_node;
4632 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4633 {
4634 llvm::StringRef name = node.GetName();
4635 if (name == "architecture")
4636 {
4637 node.GetElementText(target_info.arch);
4638 }
4639 else if (name == "osabi")
4640 {
4641 node.GetElementText(target_info.osabi);
4642 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004643 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004644 {
4645 llvm::StringRef href = node.GetAttributeValue("href");
4646 if (!href.empty())
4647 target_info.includes.push_back(href.str());
4648 }
4649 else if (name == "feature")
4650 {
4651 feature_node = node;
4652 }
4653 else if (name == "groups")
4654 {
4655 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4656 uint32_t set_id = UINT32_MAX;
4657 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004658
Greg Claytond04f0ed2015-05-26 18:00:51 +00004659 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4660 if (name == "id")
4661 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4662 if (name == "name")
4663 set_info.name = ConstString(value);
4664 return true; // Keep iterating through all attributes
4665 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004666
Greg Claytond04f0ed2015-05-26 18:00:51 +00004667 if (set_id != UINT32_MAX)
4668 target_info.reg_set_map[set_id] = set_info;
4669 return true; // Keep iterating through all "group" elements
4670 });
4671 }
4672 return true; // Keep iterating through all children of the target_node
4673 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004674
Greg Claytond04f0ed2015-05-26 18:00:51 +00004675 if (feature_node)
4676 {
Jason Molenda21586c82015-09-09 03:36:24 +00004677 ParseRegisters(feature_node, target_info, this->m_register_info, GetABI());
Greg Claytond04f0ed2015-05-26 18:00:51 +00004678 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004679
Greg Claytond04f0ed2015-05-26 18:00:51 +00004680 for (const auto &include : target_info.includes)
4681 {
4682 // request register file
4683 std::string xml_data;
4684 if (!comm.ReadExtFeature(ConstString("features"),
4685 ConstString(include),
4686 xml_data,
4687 lldberr))
4688 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004689
Greg Claytond04f0ed2015-05-26 18:00:51 +00004690 XMLDocument include_xml_document;
4691 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4692 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4693 if (include_feature_node)
4694 {
Jason Molenda21586c82015-09-09 03:36:24 +00004695 ParseRegisters(include_feature_node, target_info, this->m_register_info, GetABI());
Greg Claytond04f0ed2015-05-26 18:00:51 +00004696 }
4697 }
4698 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004699 }
4700 }
4701
Greg Claytond04f0ed2015-05-26 18:00:51 +00004702 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004703}
4704
Aidan Doddsc0c83852015-05-08 09:36:31 +00004705Error
4706ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4707{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004708 // Make sure LLDB has an XML parser it can use first
4709 if (!XMLDocument::XMLEnabled())
4710 return Error (0, ErrorType::eErrorTypeGeneric);
4711
Aidan Doddsc0c83852015-05-08 09:36:31 +00004712 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4713 if (log)
4714 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4715
Aidan Doddsc0c83852015-05-08 09:36:31 +00004716 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004717
4718 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004719 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4720 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004721
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004722 // request the loaded library list
4723 std::string raw;
4724 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004725
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004726 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4727 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004728
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004729 // parse the xml file in memory
4730 if (log)
4731 log->Printf ("parsing: %s", raw.c_str());
4732 XMLDocument doc;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004733
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004734 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4735 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004736
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004737 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4738 if (!root_element)
4739 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004740
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004741 // main link map structure
4742 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4743 if (!main_lm.empty())
4744 {
4745 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4746 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004747
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004748 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004749
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004750 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004751
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004752 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004753
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004754 if (name == "name")
4755 module.set_name (value.str());
4756 else if (name == "lm")
4757 {
4758 // the address of the link_map struct.
4759 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4760 }
4761 else if (name == "l_addr")
4762 {
4763 // the displacement as read from the field 'l_addr' of the link_map struct.
4764 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004765 // base address is always a displacement, not an absolute value.
4766 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004767 }
4768 else if (name == "l_ld")
4769 {
4770 // the memory address of the libraries PT_DYAMIC section.
4771 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4772 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004773
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004774 return true; // Keep iterating over all properties of "library"
4775 });
4776
4777 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004778 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004779 std::string name;
4780 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004781 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004782
4783 module.get_name (name);
4784 module.get_link_map (lm);
4785 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004786 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004787 module.get_dynamic (ld);
4788
Stephane Sezerc6845a02015-08-20 22:07:48 +00004789 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 +00004790 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004791
4792 list.add (module);
4793 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004794 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004795
4796 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004797 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4798 } else if (comm.GetQXferLibrariesReadSupported ()) {
4799 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004800
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004801 // request the loaded library list
4802 std::string raw;
4803 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004804
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004805 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4806 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004807
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004808 if (log)
4809 log->Printf ("parsing: %s", raw.c_str());
4810 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004811
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004812 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4813 return Error (0, ErrorType::eErrorTypeGeneric);
4814
4815 XMLNode root_element = doc.GetRootElement("library-list");
4816 if (!root_element)
4817 return Error();
4818
4819 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4820 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4821
4822 llvm::StringRef name = library.GetAttributeValue("name");
4823 module.set_name(name.str());
4824
4825 // The base address of a given library will be the address of its
4826 // first section. Most remotes send only one section for Windows
4827 // targets for example.
4828 const XMLNode &section = library.FindFirstChildElementWithName("section");
4829 llvm::StringRef address = section.GetAttributeValue("address");
4830 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004831 // These addresses are absolute values.
4832 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004833
4834 if (log)
4835 {
4836 std::string name;
4837 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004838 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004839 module.get_name (name);
4840 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004841 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004842
Stephane Sezerc6845a02015-08-20 22:07:48 +00004843 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 +00004844 }
4845
4846 list.add (module);
4847 return true; // Keep iterating over all "library" elements in the root node
4848 });
4849
4850 if (log)
4851 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4852 } else {
4853 return Error (0, ErrorType::eErrorTypeGeneric);
4854 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004855
4856 return Error();
4857}
4858
Aidan Doddsc0c83852015-05-08 09:36:31 +00004859lldb::ModuleSP
Stephane Sezerc6845a02015-08-20 22:07:48 +00004860ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004861{
4862 Target &target = m_process->GetTarget();
4863 ModuleList &modules = target.GetImages();
4864 ModuleSP module_sp;
4865
4866 bool changed = false;
4867
4868 ModuleSpec module_spec (file, target.GetArchitecture());
4869 if ((module_sp = modules.FindFirstModule (module_spec)))
4870 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004871 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004872 }
4873 else if ((module_sp = target.GetSharedModule (module_spec)))
4874 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004875 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004876 }
4877
4878 return module_sp;
4879}
4880
4881size_t
4882ProcessGDBRemote::LoadModules ()
4883{
4884 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4885
4886 // request a list of loaded libraries from GDBServer
4887 GDBLoadedModuleInfoList module_list;
4888 if (GetLoadedModuleList (module_list).Fail())
4889 return 0;
4890
4891 // get a list of all the modules
4892 ModuleList new_modules;
4893
4894 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4895 {
4896 std::string mod_name;
4897 lldb::addr_t mod_base;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004898 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004899
4900 bool valid = true;
4901 valid &= modInfo.get_name (mod_name);
4902 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004903 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004904 if (!valid)
4905 continue;
4906
4907 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004908 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004909 if (marker == std::string::npos)
4910 marker = 0;
4911 else
4912 marker += 1;
4913
4914 FileSpec file (mod_name.c_str()+marker, true);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004915 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base, mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004916
4917 if (module_sp.get())
4918 new_modules.Append (module_sp);
4919 }
4920
4921 if (new_modules.GetSize() > 0)
4922 {
Zachary Turner7529df92015-09-01 20:02:29 +00004923 Target &target = GetTarget();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004924
4925 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4926 {
4927 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4928 if (!obj)
4929 return true;
4930
4931 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4932 return true;
4933
4934 lldb::ModuleSP module_copy_sp = module_sp;
4935 target.SetExecutableModule (module_copy_sp, false);
4936 return false;
4937 });
4938
4939 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4940 loaded_modules.AppendIfNeeded (new_modules);
4941 m_process->GetTarget().ModulesDidLoad (new_modules);
4942 }
4943
4944 return new_modules.GetSize();
4945}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004946
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004947Error
4948ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4949{
4950 is_loaded = false;
4951 load_addr = LLDB_INVALID_ADDRESS;
4952
4953 std::string file_path = file.GetPath(false);
4954 if (file_path.empty ())
4955 return Error("Empty file name specified");
4956
4957 StreamString packet;
4958 packet.PutCString("qFileLoadAddress:");
4959 packet.PutCStringAsRawHex8(file_path.c_str());
4960
4961 StringExtractorGDBRemote response;
4962 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4963 return Error("Sending qFileLoadAddress packet failed");
4964
4965 if (response.IsErrorResponse())
4966 {
4967 if (response.GetError() == 1)
4968 {
4969 // The file is not loaded into the inferior
4970 is_loaded = false;
4971 load_addr = LLDB_INVALID_ADDRESS;
4972 return Error();
4973 }
4974
4975 return Error("Fetching file load address from remote server returned an error");
4976 }
4977
4978 if (response.IsNormalResponse())
4979 {
4980 is_loaded = true;
4981 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4982 return Error();
4983 }
4984
4985 return Error("Unknown error happened during sending the load address packet");
4986}
4987
Eugene Zelenko0722f082015-10-24 01:28:05 +00004988
Greg Clayton0b90be12015-06-23 21:27:50 +00004989void
4990ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4991{
4992 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4993 Process::ModulesDidLoad (module_list);
4994
4995 // After loading shared libraries, we can ask our remote GDB server if
4996 // it needs any symbols.
4997 m_gdb_comm.ServeSymbolLookups(this);
4998}
4999
Eugene Zelenko0722f082015-10-24 01:28:05 +00005000
Greg Claytone034a042015-05-21 20:52:06 +00005001class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
5002{
5003public:
5004 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
5005 CommandObjectParsed (interpreter,
5006 "process plugin packet speed-test",
5007 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
5008 NULL),
5009 m_option_group (interpreter),
5010 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),
5011 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),
5012 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),
5013 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
5014 {
5015 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5016 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5017 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5018 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5019 m_option_group.Finalize();
5020 }
5021
Eugene Zelenko0722f082015-10-24 01:28:05 +00005022 ~CommandObjectProcessGDBRemoteSpeedTest ()
5023 {
5024 }
5025
Greg Claytone034a042015-05-21 20:52:06 +00005026
5027 Options *
5028 GetOptions () override
5029 {
5030 return &m_option_group;
5031 }
5032
5033 bool
5034 DoExecute (Args& command, CommandReturnObject &result) override
5035 {
5036 const size_t argc = command.GetArgumentCount();
5037 if (argc == 0)
5038 {
5039 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5040 if (process)
5041 {
5042 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
5043 result.SetImmediateOutputStream (output_stream_sp);
5044
5045 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5046 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5047 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5048 const bool json = m_json.GetOptionValue().GetCurrentValue();
5049 if (output_stream_sp)
5050 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
5051 else
5052 {
5053 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
5054 }
5055 result.SetStatus (eReturnStatusSuccessFinishResult);
5056 return true;
5057 }
5058 }
5059 else
5060 {
5061 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5062 }
5063 result.SetStatus (eReturnStatusFailed);
5064 return false;
5065 }
5066protected:
5067 OptionGroupOptions m_option_group;
5068 OptionGroupUInt64 m_num_packets;
5069 OptionGroupUInt64 m_max_send;
5070 OptionGroupUInt64 m_max_recv;
5071 OptionGroupBoolean m_json;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005072
Greg Claytone034a042015-05-21 20:52:06 +00005073};
5074
Greg Clayton02686b82012-10-15 22:42:16 +00005075class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00005076{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005077private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005078
Greg Clayton998255b2012-10-13 02:07:45 +00005079public:
Greg Clayton02686b82012-10-15 22:42:16 +00005080 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00005081 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00005082 "process plugin packet history",
5083 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00005084 NULL)
5085 {
5086 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005087
Eugene Zelenko0722f082015-10-24 01:28:05 +00005088 ~CommandObjectProcessGDBRemotePacketHistory ()
5089 {
5090 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005091
Greg Clayton998255b2012-10-13 02:07:45 +00005092 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005093 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00005094 {
Greg Clayton02686b82012-10-15 22:42:16 +00005095 const size_t argc = command.GetArgumentCount();
5096 if (argc == 0)
5097 {
5098 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5099 if (process)
5100 {
5101 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5102 result.SetStatus (eReturnStatusSuccessFinishResult);
5103 return true;
5104 }
5105 }
5106 else
5107 {
5108 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5109 }
5110 result.SetStatus (eReturnStatusFailed);
5111 return false;
5112 }
5113};
5114
Jason Molenda6076bf42014-05-06 04:34:52 +00005115class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
5116{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005117private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005118
Jason Molenda6076bf42014-05-06 04:34:52 +00005119public:
5120 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
5121 CommandObjectParsed (interpreter,
5122 "process plugin packet xfer-size",
5123 "Maximum size that lldb will try to read/write one one chunk.",
5124 NULL)
5125 {
5126 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005127
Eugene Zelenko0722f082015-10-24 01:28:05 +00005128 ~CommandObjectProcessGDBRemotePacketXferSize ()
5129 {
5130 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005131
Jason Molenda6076bf42014-05-06 04:34:52 +00005132 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005133 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00005134 {
5135 const size_t argc = command.GetArgumentCount();
5136 if (argc == 0)
5137 {
5138 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
5139 result.SetStatus (eReturnStatusFailed);
5140 return false;
5141 }
5142
5143 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5144 if (process)
5145 {
5146 const char *packet_size = command.GetArgumentAtIndex(0);
5147 errno = 0;
5148 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5149 if (errno == 0 && user_specified_max != 0)
5150 {
5151 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5152 result.SetStatus (eReturnStatusSuccessFinishResult);
5153 return true;
5154 }
5155 }
5156 result.SetStatus (eReturnStatusFailed);
5157 return false;
5158 }
5159};
5160
Eugene Zelenko0722f082015-10-24 01:28:05 +00005161
Greg Clayton02686b82012-10-15 22:42:16 +00005162class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5163{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005164private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005165
Greg Clayton02686b82012-10-15 22:42:16 +00005166public:
5167 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5168 CommandObjectParsed (interpreter,
5169 "process plugin packet send",
5170 "Send a custom packet through the GDB remote protocol and print the answer. "
5171 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5172 NULL)
5173 {
5174 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005175
Eugene Zelenko0722f082015-10-24 01:28:05 +00005176 ~CommandObjectProcessGDBRemotePacketSend ()
5177 {
5178 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005179
Greg Clayton02686b82012-10-15 22:42:16 +00005180 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005181 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005182 {
5183 const size_t argc = command.GetArgumentCount();
5184 if (argc == 0)
5185 {
5186 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5187 result.SetStatus (eReturnStatusFailed);
5188 return false;
5189 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005190
Greg Clayton02686b82012-10-15 22:42:16 +00005191 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5192 if (process)
5193 {
Han Ming Ong84145852012-11-26 20:42:03 +00005194 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005195 {
Han Ming Ong84145852012-11-26 20:42:03 +00005196 const char *packet_cstr = command.GetArgumentAtIndex(0);
5197 bool send_async = true;
5198 StringExtractorGDBRemote response;
5199 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5200 result.SetStatus (eReturnStatusSuccessFinishResult);
5201 Stream &output_strm = result.GetOutputStream();
5202 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005203 std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005204
Han Ming Ong399289e2013-06-21 19:56:59 +00005205 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005206 {
5207 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5208 }
5209
Han Ming Ong84145852012-11-26 20:42:03 +00005210 if (response_str.empty())
5211 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5212 else
5213 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005214 }
Greg Clayton02686b82012-10-15 22:42:16 +00005215 }
Greg Clayton998255b2012-10-13 02:07:45 +00005216 return true;
5217 }
5218};
5219
Greg Claytonba4a0a52013-02-01 23:03:47 +00005220class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5221{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005222private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005223
Greg Claytonba4a0a52013-02-01 23:03:47 +00005224public:
5225 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5226 CommandObjectRaw (interpreter,
5227 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005228 "Send a qRcmd packet through the GDB remote protocol and print the response."
5229 "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 +00005230 NULL)
5231 {
5232 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005233
Eugene Zelenko0722f082015-10-24 01:28:05 +00005234 ~CommandObjectProcessGDBRemotePacketMonitor ()
5235 {
5236 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005237
Greg Claytonba4a0a52013-02-01 23:03:47 +00005238 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005239 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005240 {
5241 if (command == NULL || command[0] == '\0')
5242 {
5243 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5244 result.SetStatus (eReturnStatusFailed);
5245 return false;
5246 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005247
Greg Claytonba4a0a52013-02-01 23:03:47 +00005248 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5249 if (process)
5250 {
5251 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005252 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005253 packet.PutBytesAsRawHex8(command, strlen(command));
5254 const char *packet_cstr = packet.GetString().c_str();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005255
Greg Claytonba4a0a52013-02-01 23:03:47 +00005256 bool send_async = true;
5257 StringExtractorGDBRemote response;
5258 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5259 result.SetStatus (eReturnStatusSuccessFinishResult);
5260 Stream &output_strm = result.GetOutputStream();
5261 output_strm.Printf (" packet: %s\n", packet_cstr);
5262 const std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005263
Greg Claytonba4a0a52013-02-01 23:03:47 +00005264 if (response_str.empty())
5265 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5266 else
5267 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5268 }
5269 return true;
5270 }
5271};
5272
Greg Clayton02686b82012-10-15 22:42:16 +00005273class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5274{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005275private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005276
Greg Clayton02686b82012-10-15 22:42:16 +00005277public:
5278 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5279 CommandObjectMultiword (interpreter,
5280 "process plugin packet",
5281 "Commands that deal with GDB remote packets.",
5282 NULL)
5283 {
5284 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5285 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005286 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005287 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005288 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005289 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005290
Eugene Zelenko0722f082015-10-24 01:28:05 +00005291 ~CommandObjectProcessGDBRemotePacket ()
5292 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00005293 }
Greg Clayton02686b82012-10-15 22:42:16 +00005294};
Greg Clayton998255b2012-10-13 02:07:45 +00005295
5296class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5297{
5298public:
5299 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5300 CommandObjectMultiword (interpreter,
5301 "process plugin",
5302 "A set of commands for operating on a ProcessGDBRemote process.",
5303 "process plugin <subcommand> [<subcommand-options>]")
5304 {
5305 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5306 }
5307
Eugene Zelenko0722f082015-10-24 01:28:05 +00005308 ~CommandObjectMultiwordProcessGDBRemote ()
5309 {
5310 }
Greg Clayton998255b2012-10-13 02:07:45 +00005311};
5312
Greg Clayton998255b2012-10-13 02:07:45 +00005313CommandObject *
5314ProcessGDBRemote::GetPluginCommandObject()
5315{
5316 if (!m_command_sp)
5317 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5318 return m_command_sp.get();
5319}