blob: 8ed7e45f1a2834f0799d60a8a7194478937f60d5 [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 };
112
113 enum
114 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000115 ePropertyPacketTimeout,
116 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000117 };
118
119 class PluginProperties : public Properties
120 {
121 public:
Eugene Zelenko0722f082015-10-24 01:28:05 +0000122
Greg Clayton7f982402013-07-15 22:54:20 +0000123 static ConstString
124 GetSettingName ()
125 {
126 return ProcessGDBRemote::GetPluginNameStatic();
127 }
128
129 PluginProperties() :
130 Properties ()
131 {
132 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
133 m_collection_sp->Initialize(g_properties);
134 }
Eugene Zelenko0722f082015-10-24 01:28:05 +0000135
136 virtual
137 ~PluginProperties()
138 {
139 }
140
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 };
162
163 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
164
165 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 }
173
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 (),
Greg Clayton2e309072015-07-17 23:42:28 +0000393 m_jstopinfo_sp (),
394 m_jthreadsinfo_sp (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000395 m_continue_c_tids (),
396 m_continue_C_tids (),
397 m_continue_s_tids (),
398 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000399 m_max_memory_size (0),
400 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000401 m_addr_to_mmap_size (),
402 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000403 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000404 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000405 m_command_sp (),
Ewan Crawford78baa192015-05-13 09:18:18 +0000406 m_breakpoint_pc_offset (0),
407 m_initial_tid (LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000408{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000409 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
410 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000411 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000412
413 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_ASYNC));
414
415 const uint32_t async_event_mask = eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
416
417 if (m_async_listener.StartListeningForEvents(&m_async_broadcaster, async_event_mask) != async_event_mask)
418 {
419 if (log)
420 log->Printf("ProcessGDBRemote::%s failed to listen for m_async_broadcaster events", __FUNCTION__);
421 }
422
423 const uint32_t gdb_event_mask = Communication::eBroadcastBitReadThreadDidExit |
424 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
425 if (m_async_listener.StartListeningForEvents(&m_gdb_comm, gdb_event_mask) != gdb_event_mask)
426 {
427 if (log)
428 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events", __FUNCTION__);
429 }
430
Greg Clayton7f982402013-07-15 22:54:20 +0000431 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
432 if (timeout_seconds > 0)
433 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000434}
435
Eugene Zelenko0722f082015-10-24 01:28:05 +0000436//----------------------------------------------------------------------
437// Destructor
438//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000439ProcessGDBRemote::~ProcessGDBRemote()
440{
441 // m_mach_process.UnregisterNotificationCallbacks (this);
442 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000443 // We need to call finalize on the process before destroying ourselves
444 // to make sure all of the broadcaster cleanup goes as planned. If we
445 // destruct this class, then Process::~Process() might have problems
446 // trying to fully destroy the broadcaster.
447 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000448
449 // The general Finalize is going to try to destroy the process and that SHOULD
450 // shut down the async thread. However, if we don't kill it it will get stranded and
451 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
452 StopAsyncThread();
453 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000454}
455
456//----------------------------------------------------------------------
457// PluginInterface
458//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000459ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000460ProcessGDBRemote::GetPluginName()
461{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000462 return GetPluginNameStatic();
463}
464
465uint32_t
466ProcessGDBRemote::GetPluginVersion()
467{
468 return 1;
469}
470
Greg Claytonef8180a2013-10-15 00:14:28 +0000471bool
472ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
473{
474 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
475 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000476 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000477 if (module_object_sp)
478 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000479 StructuredData::DictionarySP target_definition_sp(
480 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000481
Zachary Turner0641ca12015-03-17 20:04:04 +0000482 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000483 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000484 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
485 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000486 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000487 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000488 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000489 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
490 if (auto triple_string_value = triple_value->GetAsString())
491 {
492 std::string triple_string = triple_string_value->GetValue();
493 ArchSpec host_arch(triple_string.c_str());
494 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
495 {
496 GetTarget().SetArchitecture(host_arch);
497 }
498 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000499 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000500 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000501 m_breakpoint_pc_offset = 0;
502 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
503 if (breakpoint_pc_offset_value)
504 {
505 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
506 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
507 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000508
Greg Claytond04f0ed2015-05-26 18:00:51 +0000509 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000510 {
511 return true;
512 }
513 }
514 }
515 return false;
516}
517
Jason Molenda21586c82015-09-09 03:36:24 +0000518// If the remote stub didn't give us eh_frame or DWARF register numbers for a register,
519// see if the ABI can provide them.
520// DWARF and eh_frame register numbers are defined as a part of the ABI.
521static void
522AugmentRegisterInfoViaABI (RegisterInfo &reg_info, ConstString reg_name, ABISP abi_sp)
523{
524 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM
525 || reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM)
526 {
527 if (abi_sp)
528 {
529 RegisterInfo abi_reg_info;
530 if (abi_sp->GetRegisterInfoByName (reg_name, abi_reg_info))
531 {
532 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM
533 && abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
534 {
535 reg_info.kinds[eRegisterKindEHFrame] = abi_reg_info.kinds[eRegisterKindEHFrame];
536 }
537 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM
538 && abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
539 {
540 reg_info.kinds[eRegisterKindDWARF] = abi_reg_info.kinds[eRegisterKindDWARF];
541 }
542 }
543 }
544 }
545}
546
Greg Claytond04f0ed2015-05-26 18:00:51 +0000547static size_t
548SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
549{
550 regnums.clear();
551 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
552 value_pair.second = comma_separated_regiter_numbers;
553 do
554 {
555 value_pair = value_pair.second.split(',');
556 if (!value_pair.first.empty())
557 {
558 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
559 if (reg != LLDB_INVALID_REGNUM)
560 regnums.push_back (reg);
561 }
562 } while (!value_pair.second.empty());
563 return regnums.size();
564}
565
Eugene Zelenko0722f082015-10-24 01:28:05 +0000566
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000567void
Greg Clayton513c26c2011-01-29 07:10:55 +0000568ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000569{
Greg Clayton513c26c2011-01-29 07:10:55 +0000570 if (!force && m_register_info.GetNumRegisters() > 0)
571 return;
572
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000573 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000574
575 // Check if qHostInfo specified a specific packet timeout for this connection.
576 // If so then lets update our setting so the user knows what the timeout is
577 // and can see it.
578 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
579 if (host_packet_timeout)
580 {
581 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
582 }
583
Ewan Crawford0c996a92015-06-30 13:08:44 +0000584 // Register info search order:
585 // 1 - Use the target definition python file if one is specified.
586 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
587 // 3 - Fall back on the qRegisterInfo packets.
588
589 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Jason Molenda91e468c2015-08-20 04:29:46 +0000590 if (!target_definition_fspec.Exists())
591 {
592 // If the filename doesn't exist, it may be a ~ not having been expanded - try to resolve it.
593 target_definition_fspec.ResolvePath();
594 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000595 if (target_definition_fspec)
596 {
597 // See if we can get register definitions from a python file
598 if (ParsePythonTargetDefinition (target_definition_fspec))
Jason Molenda5543abb2015-08-20 03:05:09 +0000599 {
Ewan Crawford0c996a92015-06-30 13:08:44 +0000600 return;
Jason Molenda5543abb2015-08-20 03:05:09 +0000601 }
602 else
603 {
604 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
605 stream_sp->Printf ("ERROR: target description file %s failed to parse.\n", target_definition_fspec.GetPath().c_str());
606 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000607 }
608
Greg Claytond04f0ed2015-05-26 18:00:51 +0000609 if (GetGDBServerRegisterInfo ())
610 return;
611
612 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000613 uint32_t reg_offset = 0;
614 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000615 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000616 response_type == StringExtractorGDBRemote::eResponse;
617 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000618 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000619 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000620 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000621 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000622 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000623 {
Greg Clayton576d8832011-03-22 04:00:09 +0000624 response_type = response.GetResponseType();
625 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000626 {
627 std::string name;
628 std::string value;
629 ConstString reg_name;
630 ConstString alt_name;
631 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000632 std::vector<uint32_t> value_regs;
633 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000634 RegisterInfo reg_info = { NULL, // Name
635 NULL, // Alt name
636 0, // byte size
637 reg_offset, // offset
638 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +0000639 eFormatHex, // format
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640 {
Jason Molendabf67a302015-09-01 05:17:01 +0000641 LLDB_INVALID_REGNUM, // eh_frame reg num
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000642 LLDB_INVALID_REGNUM, // DWARF reg num
643 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +0000644 reg_num, // process plugin reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000645 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000646 },
647 NULL,
648 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000649 };
650
651 while (response.GetNameColonValue(name, value))
652 {
653 if (name.compare("name") == 0)
654 {
655 reg_name.SetCString(value.c_str());
656 }
657 else if (name.compare("alt-name") == 0)
658 {
659 alt_name.SetCString(value.c_str());
660 }
661 else if (name.compare("bitsize") == 0)
662 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000663 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664 }
665 else if (name.compare("offset") == 0)
666 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000667 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000668 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000669 {
670 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000671 }
672 }
673 else if (name.compare("encoding") == 0)
674 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000675 const Encoding encoding = Args::StringToEncoding (value.c_str());
676 if (encoding != eEncodingInvalid)
677 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000678 }
679 else if (name.compare("format") == 0)
680 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000681 Format format = eFormatInvalid;
682 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
683 reg_info.format = format;
684 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000685 reg_info.format = eFormatBinary;
686 else if (value.compare("decimal") == 0)
687 reg_info.format = eFormatDecimal;
688 else if (value.compare("hex") == 0)
689 reg_info.format = eFormatHex;
690 else if (value.compare("float") == 0)
691 reg_info.format = eFormatFloat;
692 else if (value.compare("vector-sint8") == 0)
693 reg_info.format = eFormatVectorOfSInt8;
694 else if (value.compare("vector-uint8") == 0)
695 reg_info.format = eFormatVectorOfUInt8;
696 else if (value.compare("vector-sint16") == 0)
697 reg_info.format = eFormatVectorOfSInt16;
698 else if (value.compare("vector-uint16") == 0)
699 reg_info.format = eFormatVectorOfUInt16;
700 else if (value.compare("vector-sint32") == 0)
701 reg_info.format = eFormatVectorOfSInt32;
702 else if (value.compare("vector-uint32") == 0)
703 reg_info.format = eFormatVectorOfUInt32;
704 else if (value.compare("vector-float32") == 0)
705 reg_info.format = eFormatVectorOfFloat32;
706 else if (value.compare("vector-uint128") == 0)
707 reg_info.format = eFormatVectorOfUInt128;
708 }
709 else if (name.compare("set") == 0)
710 {
711 set_name.SetCString(value.c_str());
712 }
Jason Molendaa18f7072015-08-15 01:21:01 +0000713 else if (name.compare("gcc") == 0 || name.compare("ehframe") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000714 {
Jason Molendaa18f7072015-08-15 01:21:01 +0000715 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000716 }
717 else if (name.compare("dwarf") == 0)
718 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000719 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000720 }
721 else if (name.compare("generic") == 0)
722 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000723 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000725 else if (name.compare("container-regs") == 0)
726 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000727 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000728 }
729 else if (name.compare("invalidate-regs") == 0)
730 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000731 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000732 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733 }
734
Jason Molenda743e86a2010-06-11 23:44:18 +0000735 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000736 assert (reg_info.byte_size != 0);
737 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000738 if (!value_regs.empty())
739 {
740 value_regs.push_back(LLDB_INVALID_REGNUM);
741 reg_info.value_regs = value_regs.data();
742 }
743 if (!invalidate_regs.empty())
744 {
745 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
746 reg_info.invalidate_regs = invalidate_regs.data();
747 }
748
Jason Molenda21586c82015-09-09 03:36:24 +0000749 AugmentRegisterInfoViaABI (reg_info, reg_name, GetABI ());
750
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000751 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
752 }
Todd Fiala1a634402014-01-08 07:52:40 +0000753 else
754 {
755 break; // ensure exit before reg_num is incremented
756 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000757 }
758 else
759 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000760 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000761 }
762 }
763
Greg Claytond04f0ed2015-05-26 18:00:51 +0000764 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000765 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000766 m_register_info.Finalize(GetTarget().GetArchitecture());
767 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000768 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000769
Johnny Chen2fa9de12012-05-14 18:44:23 +0000770 // We didn't get anything if the accumulated reg_num is zero. See if we are
771 // debugging ARM and fill with a hard coded register set until we can get an
772 // updated debugserver down on the devices.
773 // On the other hand, if the accumulated reg_num is positive, see if we can
774 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000775 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000776
777 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000778 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
779 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
780
781 // Use the process' architecture instead of the host arch, if available
782 ArchSpec remote_arch;
783 if (remote_process_arch.IsValid ())
784 remote_arch = remote_process_arch;
785 else
786 remote_arch = remote_host_arch;
787
Johnny Chen2fa9de12012-05-14 18:44:23 +0000788 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000789 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000790 if (remote_arch.IsValid()
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000791 && (remote_arch.GetMachine() == llvm::Triple::arm || remote_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000792 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
793 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000794 }
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000795 else if (target_arch.GetMachine() == llvm::Triple::arm
796 || target_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000797 {
798 m_register_info.HardcodeARMRegisters(from_scratch);
799 }
800
801 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000802 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000803}
804
805Error
806ProcessGDBRemote::WillLaunch (Module* module)
807{
808 return WillLaunchOrAttach ();
809}
810
811Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000812ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000813{
814 return WillLaunchOrAttach ();
815}
816
817Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000818ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000819{
820 return WillLaunchOrAttach ();
821}
822
823Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000824ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000825{
Todd Fialaaf245d12014-06-30 21:05:18 +0000826 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000827 Error error (WillLaunchOrAttach ());
828
829 if (error.Fail())
830 return error;
831
Greg Clayton2289fa42011-04-30 01:09:13 +0000832 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000833
834 if (error.Fail())
835 return error;
836 StartAsyncThread ();
837
Greg Claytonc574ede2011-03-10 02:26:48 +0000838 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000839 if (pid == LLDB_INVALID_PROCESS_ID)
840 {
841 // We don't have a valid process ID, so note that we are connected
842 // and could now request to launch or attach, or get remote process
843 // listings...
844 SetPrivateState (eStateConnected);
845 }
846 else
847 {
848 // We have a valid process
849 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000850 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000851 StringExtractorGDBRemote response;
852 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000853 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000854 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000855
856 // '?' Packets must be handled differently in non-stop mode
857 if (GetTarget().GetNonStopModeEnabled())
858 HandleStopReplySequence();
859
Zachary Turner7529df92015-09-01 20:02:29 +0000860 Target &target = GetTarget();
861 if (!target.GetArchitecture().IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +0000862 {
863 if (m_gdb_comm.GetProcessArchitecture().IsValid())
864 {
Zachary Turner7529df92015-09-01 20:02:29 +0000865 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000866 }
867 else
868 {
Zachary Turner7529df92015-09-01 20:02:29 +0000869 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000870 }
Carlo Kok74389122013-10-14 07:09:13 +0000871 }
872
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000873 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000874 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000875 {
876 SetPrivateState (state);
877 }
878 else
Daniel Malead01b2952012-11-29 21:49:15 +0000879 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 +0000880 }
881 else
Daniel Malead01b2952012-11-29 21:49:15 +0000882 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 +0000883 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000884
Todd Fialaaf245d12014-06-30 21:05:18 +0000885 if (log)
886 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");
887
888
889 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000890 && !GetTarget().GetArchitecture().IsValid()
891 && m_gdb_comm.GetHostArchitecture().IsValid())
892 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000893 // Prefer the *process'* architecture over that of the *host*, if available.
894 if (m_gdb_comm.GetProcessArchitecture().IsValid())
895 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
896 else
897 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000898 }
899
Todd Fialaaf245d12014-06-30 21:05:18 +0000900 if (log)
901 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
902
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000903 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000904 {
905 PlatformSP platform_sp = GetTarget().GetPlatform();
906 if (platform_sp && platform_sp->IsConnected())
907 SetUnixSignals(platform_sp->GetUnixSignals());
908 else
909 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
910 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000911
Greg Claytonb766a732011-02-04 01:58:07 +0000912 return error;
913}
914
915Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000916ProcessGDBRemote::WillLaunchOrAttach ()
917{
918 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000919 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000920 return error;
921}
922
923//----------------------------------------------------------------------
924// Process Control
925//----------------------------------------------------------------------
926Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000927ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000928{
Todd Fiala75f47c32014-10-11 21:42:09 +0000929 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000930 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000931
Todd Fiala75f47c32014-10-11 21:42:09 +0000932 if (log)
933 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
934
Greg Clayton982c9762011-11-03 21:22:33 +0000935 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000936 FileSpec stdin_file_spec{};
937 FileSpec stdout_file_spec{};
938 FileSpec stderr_file_spec{};
939 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000940
Zachary Turner696b5282014-08-14 16:01:25 +0000941 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000942 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
943 if (file_action)
944 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000945 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000946 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000947 }
948 file_action = launch_info.GetFileActionForFD (STDOUT_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 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000953 }
954 file_action = launch_info.GetFileActionForFD (STDERR_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 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000959 }
960
Todd Fiala75f47c32014-10-11 21:42:09 +0000961 if (log)
962 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000963 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000964 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000965 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000966 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
967 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
968 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000969 else
970 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
971 }
972
Vince Harrondf3f00f2015-02-10 21:09:04 +0000973 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000974 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000975 {
976 // the inferior will be reading stdin from the specified file
977 // or stdio is completely disabled
978 m_stdin_forward = false;
979 }
980 else
981 {
982 m_stdin_forward = true;
983 }
984
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000985 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
986 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
987 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000988
Greg Clayton982c9762011-11-03 21:22:33 +0000989 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000990 if (object_file)
991 {
Greg Clayton71337622011-02-24 22:24:29 +0000992 // Make sure we aren't already connected?
993 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000994 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000995 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000996 }
997
998 if (error.Success())
999 {
1000 lldb_utility::PseudoTerminal pty;
1001 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +00001002
Zachary Turner7529df92015-09-01 20:02:29 +00001003 PlatformSP platform_sp (GetTarget().GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +00001004 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +00001005 {
Vince Harrondf3f00f2015-02-10 21:09:04 +00001006 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +00001007 if (!stdin_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +00001008 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +00001009 if (!stdout_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +00001010 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +00001011 if (!stderr_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +00001012 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
Vince Harrondf3f00f2015-02-10 21:09:04 +00001013 }
1014 else if (platform_sp && platform_sp->IsHost())
1015 {
1016 // If the debugserver is local and we aren't disabling STDIO, lets use
1017 // a pseudo terminal to instead of relying on the 'O' packets for stdio
1018 // since 'O' packets can really slow down debugging if the inferior
1019 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +00001020 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
1021 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001022 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001023 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
1024
1025 if (!stdin_file_spec)
1026 stdin_file_spec = slave_name;
1027
1028 if (!stdout_file_spec)
1029 stdout_file_spec = slave_name;
1030
1031 if (!stderr_file_spec)
1032 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001033 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001034 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +00001035 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 +00001036 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +00001037 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
1038 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
1039 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +00001040 }
1041
Todd Fiala75f47c32014-10-11 21:42:09 +00001042 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +00001043 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +00001044 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +00001045 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
1046 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
1047 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +00001048
Chaoren Lind3173f32015-05-29 19:52:29 +00001049 if (stdin_file_spec)
1050 m_gdb_comm.SetSTDIN(stdin_file_spec);
1051 if (stdout_file_spec)
1052 m_gdb_comm.SetSTDOUT(stdout_file_spec);
1053 if (stderr_file_spec)
1054 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +00001055
1056 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +00001057 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +00001058
Zachary Turner7529df92015-09-01 20:02:29 +00001059 m_gdb_comm.SendLaunchArchPacket (GetTarget().GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +00001060
Jason Molendaa3329782014-03-29 18:54:20 +00001061 const char * launch_event_data = launch_info.GetLaunchEventData();
1062 if (launch_event_data != NULL && *launch_event_data != '\0')
1063 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
1064
Chaoren Lind3173f32015-05-29 19:52:29 +00001065 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +00001066 {
1067 m_gdb_comm.SetWorkingDir (working_dir);
1068 }
1069
1070 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +00001071 const Args &environment = launch_info.GetEnvironmentEntries();
1072 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +00001073 {
Greg Clayton982c9762011-11-03 21:22:33 +00001074 size_t num_environment_entries = environment.GetArgumentCount();
1075 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001076 {
Greg Clayton982c9762011-11-03 21:22:33 +00001077 const char *env_entry = environment.GetArgumentAtIndex(i);
1078 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001079 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001080 }
Greg Clayton71337622011-02-24 22:24:29 +00001081 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001082
Greg Clayton71337622011-02-24 22:24:29 +00001083 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001084 // Scope for the scoped timeout object
1085 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1086
1087 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1088 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001090 std::string error_str;
1091 if (m_gdb_comm.GetLaunchSuccess (error_str))
1092 {
1093 SetID (m_gdb_comm.GetCurrentProcessID ());
1094 }
1095 else
1096 {
1097 error.SetErrorString (error_str.c_str());
1098 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001099 }
1100 else
1101 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001102 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103 }
Greg Clayton71337622011-02-24 22:24:29 +00001104 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001105
Greg Clayton71337622011-02-24 22:24:29 +00001106 if (GetID() == LLDB_INVALID_PROCESS_ID)
1107 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001108 if (log)
1109 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001110 KillDebugserverProcess ();
1111 return error;
1112 }
1113
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001114 StringExtractorGDBRemote response;
1115 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001116 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001117 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001118 // '?' Packets must be handled differently in non-stop mode
1119 if (GetTarget().GetNonStopModeEnabled())
1120 HandleStopReplySequence();
1121
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001122 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1123
1124 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001125 {
Zachary Turner7529df92015-09-01 20:02:29 +00001126 GetTarget().MergeArchitecture(process_arch);
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001127 }
1128 else
1129 {
1130 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1131 if (host_arch.IsValid())
Zachary Turner7529df92015-09-01 20:02:29 +00001132 GetTarget().MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001133 }
1134
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001135 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001136
1137 if (!disable_stdio)
1138 {
1139 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001140 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001141 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001142 }
1143 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001144 else
1145 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001146 if (log)
1147 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001148 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001149 }
1150 else
1151 {
1152 // Set our user ID to an invalid process ID.
1153 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001154 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1155 exe_module->GetFileSpec().GetFilename().AsCString(),
1156 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001157 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001158 return error;
Eugene Zelenko0722f082015-10-24 01:28:05 +00001159
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001160}
1161
Eugene Zelenko0722f082015-10-24 01:28:05 +00001162
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163Error
Greg Claytonb766a732011-02-04 01:58:07 +00001164ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001165{
1166 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001167 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001168 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001169
1170 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001171 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001172 if (log)
1173 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001174 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1175 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001176 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001177 const uint32_t max_retry_count = 50;
1178 uint32_t retry_count = 0;
1179 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001180 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001181 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1182 {
1183 m_gdb_comm.SetConnection (conn_ap.release());
1184 break;
1185 }
1186 else if (error.WasInterrupted())
1187 {
1188 // If we were interrupted, don't keep retrying.
1189 break;
1190 }
1191
1192 retry_count++;
1193
1194 if (retry_count >= max_retry_count)
1195 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001196
Greg Clayton00fe87b2013-12-05 22:58:22 +00001197 usleep (100000);
1198 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199 }
1200 }
1201
1202 if (!m_gdb_comm.IsConnected())
1203 {
1204 if (error.Success())
1205 error.SetErrorString("not connected to remote gdb server");
1206 return error;
1207 }
1208
Eugene Zelenko0722f082015-10-24 01:28:05 +00001209
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001210 // Start the communications read thread so all incoming data can be
1211 // parsed into packets and queued as they arrive.
1212 if (GetTarget().GetNonStopModeEnabled())
1213 m_gdb_comm.StartReadThread();
1214
Greg Clayton32e0a752011-03-30 18:16:51 +00001215 // We always seem to be able to open a connection to a local port
1216 // so we need to make sure we can then send data to it. If we can't
1217 // then we aren't actually connected to anything, so try and do the
1218 // handshake with the remote GDB server and make sure that goes
1219 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001220 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001221 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001222 m_gdb_comm.Disconnect();
1223 if (error.Success())
1224 error.SetErrorString("not connected to remote gdb server");
1225 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001226 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001227
1228 // Send $QNonStop:1 packet on startup if required
1229 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001230 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001231
Greg Claytonb30c50c2015-05-29 00:01:55 +00001232 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001233 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001234 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001235 m_gdb_comm.GetHostInfo ();
1236 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001237 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001238
1239 // Ask the remote server for the default thread id
1240 if (GetTarget().GetNonStopModeEnabled())
1241 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1242
1243
Jim Ingham03afad82012-07-02 05:40:07 +00001244 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1245 for (size_t idx = 0; idx < num_cmds; idx++)
1246 {
1247 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001248 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1249 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001250 return error;
1251}
1252
1253void
Jim Inghambb006ce2014-08-02 00:33:35 +00001254ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001255{
Greg Clayton5160ce52013-03-27 23:08:40 +00001256 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001257 if (log)
1258 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001259 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001260 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001261 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001262
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001263 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001264
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001265
1266 // See if the GDB server supports the qProcessInfo packet, if so
1267 // prefer that over the Host information as it will be more specific
1268 // to our process.
1269
Todd Fiala75f47c32014-10-11 21:42:09 +00001270 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1271 if (remote_process_arch.IsValid())
1272 {
1273 process_arch = remote_process_arch;
1274 if (log)
1275 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1276 __FUNCTION__,
1277 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1278 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1279 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001280 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001281 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001282 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001283 if (log)
1284 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1285 __FUNCTION__,
1286 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1287 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1288 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001289
Jim Inghambb006ce2014-08-02 00:33:35 +00001290 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001291 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001292 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001293 if (target_arch.IsValid())
1294 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001295 if (log)
1296 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1297 __FUNCTION__,
1298 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1299 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1300
1301 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001302 // ARM executables and shared libraries can have mixed ARM architectures.
1303 // You can have an armv6 executable, and if the host is armv7, then the
1304 // system will load the best possible architecture for all shared libraries
1305 // it has, so we really need to take the remote host architecture as our
1306 // defacto architecture in this case.
1307
Jason Molenda6d9fe8c2015-08-21 00:13:37 +00001308 if ((process_arch.GetMachine() == llvm::Triple::arm || process_arch.GetMachine() == llvm::Triple::thumb)
1309 && process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001310 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001311 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001312 if (log)
1313 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1314 __FUNCTION__,
1315 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1316 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001317 }
1318 else
1319 {
1320 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001321 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001322 llvm::Triple new_target_triple = target_arch.GetTriple();
1323 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001324 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001325 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001326
Tamas Berghammere724af12015-03-13 10:32:37 +00001327 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001328 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001329 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001330
Tamas Berghammere724af12015-03-13 10:32:37 +00001331 if (new_target_triple.getEnvironmentName().size() == 0)
1332 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001333 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001334
Tamas Berghammere724af12015-03-13 10:32:37 +00001335 ArchSpec new_target_arch = target_arch;
1336 new_target_arch.SetTriple(new_target_triple);
1337 GetTarget().SetArchitecture(new_target_arch);
1338 }
Greg Claytond314e812011-03-23 00:09:55 +00001339 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001340
1341 if (log)
1342 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1343 __FUNCTION__,
1344 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1345 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001346 }
1347 else
1348 {
1349 // The target doesn't have a valid architecture yet, set it from
1350 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001351 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001352 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001353 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001354 }
1355}
1356
1357void
1358ProcessGDBRemote::DidLaunch ()
1359{
Jim Inghambb006ce2014-08-02 00:33:35 +00001360 ArchSpec process_arch;
1361 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001362}
1363
1364Error
Han Ming Ong84647042012-02-25 01:07:38 +00001365ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1366{
Todd Fiala75f47c32014-10-11 21:42:09 +00001367 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001368 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001369
1370 if (log)
1371 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1372
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001373 // Clear out and clean up from any current state
1374 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001375 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1376 {
Greg Clayton71337622011-02-24 22:24:29 +00001377 // Make sure we aren't already connected?
1378 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001379 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001380 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001381
1382 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001383 {
Greg Clayton71337622011-02-24 22:24:29 +00001384 const char *error_string = error.AsCString();
1385 if (error_string == NULL)
1386 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1387
1388 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001389 }
Greg Clayton71337622011-02-24 22:24:29 +00001390 }
1391
1392 if (error.Success())
1393 {
Jim Ingham106d0282014-06-25 02:32:56 +00001394 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001395
Greg Clayton71337622011-02-24 22:24:29 +00001396 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001397 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001398 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001399 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400 }
1401 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001402
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001403 return error;
1404}
1405
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001406Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001407ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001408{
1409 Error error;
1410 // Clear out and clean up from any current state
1411 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001412
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001413 if (process_name && process_name[0])
1414 {
Greg Clayton71337622011-02-24 22:24:29 +00001415 // Make sure we aren't already connected?
1416 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001417 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001418 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001419
Greg Clayton71337622011-02-24 22:24:29 +00001420 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001421 {
Greg Clayton71337622011-02-24 22:24:29 +00001422 const char *error_string = error.AsCString();
1423 if (error_string == NULL)
1424 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001425
Greg Clayton71337622011-02-24 22:24:29 +00001426 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001427 }
Greg Clayton71337622011-02-24 22:24:29 +00001428 }
1429
1430 if (error.Success())
1431 {
1432 StreamString packet;
1433
Jim Ingham106d0282014-06-25 02:32:56 +00001434 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1435
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001436 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001437 {
1438 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1439 {
1440 packet.PutCString ("vAttachWait");
1441 }
1442 else
1443 {
1444 if (attach_info.GetIgnoreExisting())
1445 packet.PutCString("vAttachWait");
1446 else
1447 packet.PutCString ("vAttachOrWait");
1448 }
1449 }
Greg Clayton71337622011-02-24 22:24:29 +00001450 else
1451 packet.PutCString("vAttachName");
1452 packet.PutChar(';');
1453 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1454
1455 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1456
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001457 }
1458 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001459 return error;
1460}
1461
Greg Clayton5df78fa2015-05-23 03:54:53 +00001462void
1463ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001464{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001465 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001466 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001467}
1468
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001469void
Jim Inghambb006ce2014-08-02 00:33:35 +00001470ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001471{
Jim Inghambb006ce2014-08-02 00:33:35 +00001472 // If you can figure out what the architecture is, fill it in here.
1473 process_arch.Clear();
1474 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001475}
1476
Eugene Zelenko0722f082015-10-24 01:28:05 +00001477
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001478Error
1479ProcessGDBRemote::WillResume ()
1480{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001481 m_continue_c_tids.clear();
1482 m_continue_C_tids.clear();
1483 m_continue_s_tids.clear();
1484 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001485 m_jstopinfo_sp.reset();
1486 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001487 return Error();
1488}
1489
1490Error
1491ProcessGDBRemote::DoResume ()
1492{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001493 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001494 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001495 if (log)
1496 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001497
1498 Listener listener ("gdb-remote.resume-packet-sent");
1499 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1500 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001501 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1502
Greg Claytond1d06e42013-04-20 00:27:58 +00001503 const size_t num_threads = GetThreadList().GetSize();
1504
Greg Clayton71fc2a32011-02-12 06:28:37 +00001505 StreamString continue_packet;
1506 bool continue_packet_error = false;
1507 if (m_gdb_comm.HasAnyVContSupport ())
1508 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001509 if (!GetTarget().GetNonStopModeEnabled() &&
1510 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001511 (m_continue_c_tids.empty() &&
1512 m_continue_C_tids.empty() &&
1513 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001514 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001515 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001516 // All threads are continuing, just send a "c" packet
1517 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001518 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001519 else
1520 {
1521 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001522
Greg Claytond1d06e42013-04-20 00:27:58 +00001523 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001524 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001525 if (m_gdb_comm.GetVContSupported ('c'))
1526 {
1527 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)
1528 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1529 }
1530 else
1531 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001532 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001533
1534 if (!continue_packet_error && !m_continue_C_tids.empty())
1535 {
1536 if (m_gdb_comm.GetVContSupported ('C'))
1537 {
1538 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)
1539 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1540 }
1541 else
1542 continue_packet_error = true;
1543 }
Greg Claytone5219662010-12-03 06:02:24 +00001544
Greg Claytond1d06e42013-04-20 00:27:58 +00001545 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001546 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001547 if (m_gdb_comm.GetVContSupported ('s'))
1548 {
1549 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)
1550 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1551 }
1552 else
1553 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001554 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001555
1556 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001557 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001558 if (m_gdb_comm.GetVContSupported ('S'))
1559 {
1560 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)
1561 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1562 }
1563 else
1564 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001565 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001566
1567 if (continue_packet_error)
1568 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001569 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001570 }
1571 else
1572 continue_packet_error = true;
1573
1574 if (continue_packet_error)
1575 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001576 // Either no vCont support, or we tried to use part of the vCont
1577 // packet that wasn't supported by the remote GDB server.
1578 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001579 const size_t num_continue_c_tids = m_continue_c_tids.size();
1580 const size_t num_continue_C_tids = m_continue_C_tids.size();
1581 const size_t num_continue_s_tids = m_continue_s_tids.size();
1582 const size_t num_continue_S_tids = m_continue_S_tids.size();
1583 if (num_continue_c_tids > 0)
1584 {
1585 if (num_continue_c_tids == num_threads)
1586 {
1587 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001588 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001589 continue_packet.PutChar ('c');
1590 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001591 }
1592 else if (num_continue_c_tids == 1 &&
1593 num_continue_C_tids == 0 &&
1594 num_continue_s_tids == 0 &&
1595 num_continue_S_tids == 0 )
1596 {
1597 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001598 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001599 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001600 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001601 }
1602 }
1603
Greg Clayton0c74e782011-06-24 03:21:43 +00001604 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001605 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001606 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1607 num_continue_C_tids > 0 &&
1608 num_continue_s_tids == 0 &&
1609 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001610 {
1611 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001612 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001613 if (num_continue_C_tids > 1)
1614 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001615 // More that one thread with a signal, yet we don't have
1616 // vCont support and we are being asked to resume each
1617 // thread with a signal, we need to make sure they are
1618 // all the same signal, or we can't issue the continue
1619 // accurately with the current support...
1620 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001621 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001622 continue_packet_error = false;
1623 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1624 {
1625 if (m_continue_C_tids[i].second != continue_signo)
1626 continue_packet_error = true;
1627 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001628 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001629 if (!continue_packet_error)
1630 m_gdb_comm.SetCurrentThreadForRun (-1);
1631 }
1632 else
1633 {
1634 // Set the continue thread ID
1635 continue_packet_error = false;
1636 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001637 }
1638 if (!continue_packet_error)
1639 {
1640 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001641 continue_packet.Printf("C%2.2x", continue_signo);
1642 }
1643 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001644 }
1645
Greg Clayton0c74e782011-06-24 03:21:43 +00001646 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001647 {
1648 if (num_continue_s_tids == num_threads)
1649 {
1650 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001651 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001652
1653 // If in Non-Stop-Mode use vCont when stepping
1654 if (GetTarget().GetNonStopModeEnabled())
1655 {
1656 if (m_gdb_comm.GetVContSupported('s'))
1657 continue_packet.PutCString("vCont;s");
1658 else
1659 continue_packet.PutChar('s');
1660 }
1661 else
1662 continue_packet.PutChar('s');
1663
Greg Clayton0c74e782011-06-24 03:21:43 +00001664 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001665 }
1666 else if (num_continue_c_tids == 0 &&
1667 num_continue_C_tids == 0 &&
1668 num_continue_s_tids == 1 &&
1669 num_continue_S_tids == 0 )
1670 {
1671 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001672 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001673 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001674 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001675 }
1676 }
1677
1678 if (!continue_packet_error && num_continue_S_tids > 0)
1679 {
1680 if (num_continue_S_tids == num_threads)
1681 {
1682 const int step_signo = m_continue_S_tids.front().second;
1683 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001684 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001685 if (num_continue_S_tids > 1)
1686 {
1687 for (size_t i=1; i<num_threads; ++i)
1688 {
1689 if (m_continue_S_tids[i].second != step_signo)
1690 continue_packet_error = true;
1691 }
1692 }
1693 if (!continue_packet_error)
1694 {
1695 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001696 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001697 continue_packet.Printf("S%2.2x", step_signo);
1698 }
1699 }
1700 else if (num_continue_c_tids == 0 &&
1701 num_continue_C_tids == 0 &&
1702 num_continue_s_tids == 0 &&
1703 num_continue_S_tids == 1 )
1704 {
1705 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001706 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001707 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001708 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001709 }
1710 }
1711 }
1712
1713 if (continue_packet_error)
1714 {
1715 error.SetErrorString ("can't make continue packet for this resume");
1716 }
1717 else
1718 {
1719 EventSP event_sp;
1720 TimeValue timeout;
1721 timeout = TimeValue::Now();
1722 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001723 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001724 {
1725 error.SetErrorString ("Trying to resume but the async thread is dead.");
1726 if (log)
1727 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1728 return error;
1729 }
1730
Greg Clayton71fc2a32011-02-12 06:28:37 +00001731 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1732
1733 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001734 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001735 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001736 if (log)
1737 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1738 }
1739 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1740 {
1741 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1742 if (log)
1743 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1744 return error;
1745 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001746 }
Greg Claytone5219662010-12-03 06:02:24 +00001747 }
1748
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001749 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001750}
1751
Greg Clayton9e920902012-04-10 02:25:43 +00001752void
Ewan Crawford78baa192015-05-13 09:18:18 +00001753ProcessGDBRemote::HandleStopReplySequence ()
1754{
1755 while(true)
1756 {
1757 // Send vStopped
1758 StringExtractorGDBRemote response;
1759 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1760
1761 // OK represents end of signal list
1762 if (response.IsOKResponse())
1763 break;
1764
1765 // If not OK or a normal packet we have a problem
1766 if (!response.IsNormalResponse())
1767 break;
1768
1769 SetLastStopPacket(response);
1770 }
1771}
1772
1773void
Greg Clayton9e920902012-04-10 02:25:43 +00001774ProcessGDBRemote::ClearThreadIDList ()
1775{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001776 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001777 m_thread_ids.clear();
1778}
1779
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001780size_t
1781ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1782{
1783 m_thread_ids.clear();
1784 size_t comma_pos;
1785 lldb::tid_t tid;
1786 while ((comma_pos = value.find(',')) != std::string::npos)
1787 {
1788 value[comma_pos] = '\0';
1789 // thread in big endian hex
1790 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1791 if (tid != LLDB_INVALID_THREAD_ID)
1792 m_thread_ids.push_back (tid);
1793 value.erase(0, comma_pos + 1);
1794 }
1795 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1796 if (tid != LLDB_INVALID_THREAD_ID)
1797 m_thread_ids.push_back (tid);
1798 return m_thread_ids.size();
1799}
1800
Greg Clayton9e920902012-04-10 02:25:43 +00001801bool
1802ProcessGDBRemote::UpdateThreadIDList ()
1803{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001804 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001805
Greg Clayton2e309072015-07-17 23:42:28 +00001806 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001807 {
1808 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001809 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001810 if (thread_infos && thread_infos->GetSize() > 0)
1811 {
1812 m_thread_ids.clear();
1813 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
1835 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1836 // Get the number of stop packets on the stack
1837 int nItems = m_stop_packet_stack.size();
1838 // Iterate over them
1839 for (int i = 0; i < nItems; i++)
1840 {
1841 // Get the thread stop info
1842 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1843 const std::string &stop_info_str = stop_info.GetStringRef();
1844 const size_t threads_pos = stop_info_str.find(";threads:");
1845 if (threads_pos != std::string::npos)
1846 {
1847 const size_t start = threads_pos + strlen(";threads:");
1848 const size_t end = stop_info_str.find(';', start);
1849 if (end != std::string::npos)
1850 {
1851 std::string value = stop_info_str.substr(start, end - start);
1852 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1853 return true;
1854 }
1855 }
1856 }
1857 }
1858
Greg Clayton9e920902012-04-10 02:25:43 +00001859 bool sequence_mutex_unavailable = false;
1860 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1861 if (sequence_mutex_unavailable)
1862 {
Greg Clayton9e920902012-04-10 02:25:43 +00001863 return false; // We just didn't get the list
1864 }
1865 return true;
1866}
1867
Greg Clayton9fc13552012-04-10 00:18:59 +00001868bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001869ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001870{
1871 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001872 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001873 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001874 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001875
1876 size_t num_thread_ids = m_thread_ids.size();
1877 // The "m_thread_ids" thread ID list should always be updated after each stop
1878 // reply packet, but in case it isn't, update it here.
1879 if (num_thread_ids == 0)
1880 {
1881 if (!UpdateThreadIDList ())
1882 return false;
1883 num_thread_ids = m_thread_ids.size();
1884 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001885
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001886 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001887 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001888 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001889 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001890 {
Greg Clayton9e920902012-04-10 02:25:43 +00001891 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001892 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001893 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001894 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001895 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001896 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1897 log->Printf(
1898 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001899 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001900 thread_sp->GetID());
1901 }
1902 else
1903 {
1904 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1905 log->Printf(
1906 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001907 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001908 thread_sp->GetID());
1909 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001910 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001911 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001912 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001913
1914 // Whatever that is left in old_thread_list_copy are not
1915 // present in new_thread_list. Remove non-existent threads from internal id table.
1916 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1917 for (size_t i=0; i<old_num_thread_ids; i++)
1918 {
1919 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1920 if (old_thread_sp)
1921 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001922 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001923 m_thread_id_to_index_id_map.erase(old_thread_id);
1924 }
1925 }
1926
Greg Clayton9fc13552012-04-10 00:18:59 +00001927 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001928}
1929
Eugene Zelenko0722f082015-10-24 01:28:05 +00001930
Greg Clayton358cf1e2015-06-25 21:46:34 +00001931bool
Greg Clayton2e309072015-07-17 23:42:28 +00001932ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001933{
1934 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001935 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001936 {
Greg Clayton2e309072015-07-17 23:42:28 +00001937 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001938 if (thread_infos)
1939 {
1940 lldb::tid_t tid;
1941 const size_t n = thread_infos->GetSize();
1942 for (size_t i=0; i<n; ++i)
1943 {
1944 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1945 if (thread_dict)
1946 {
1947 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1948 {
1949 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001950 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001951 }
1952 }
1953 }
1954 }
1955 }
Greg Clayton2e309072015-07-17 23:42:28 +00001956 return false;
1957}
1958
1959bool
1960ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1961{
1962 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1963 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1964 return true;
1965
1966 // See if we got thread stop info for any threads valid stop info reasons threads
1967 // via the "jstopinfo" packet stop reply packet key/value pair?
1968 if (m_jstopinfo_sp)
1969 {
1970 // If we have "jstopinfo" then we have stop descriptions for all threads
1971 // that have stop reasons, and if there is no entry for a thread, then
1972 // it has no stop reason.
1973 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1974 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1975 {
1976 thread->SetStopInfo (StopInfoSP());
1977 }
1978 return true;
1979 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001980
1981 // Fall back to using the qThreadStopInfo packet
1982 StringExtractorGDBRemote stop_packet;
1983 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1984 return SetThreadStopInfo (stop_packet) == eStateStopped;
1985 return false;
1986}
1987
Eugene Zelenko0722f082015-10-24 01:28:05 +00001988
Greg Clayton358cf1e2015-06-25 21:46:34 +00001989ThreadSP
1990ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1991 ExpeditedRegisterMap &expedited_register_map,
1992 uint8_t signo,
1993 const std::string &thread_name,
1994 const std::string &reason,
1995 const std::string &description,
1996 uint32_t exc_type,
1997 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001998 addr_t thread_dispatch_qaddr,
1999 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
2000 std::string &queue_name,
2001 QueueKind queue_kind,
2002 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002003{
2004 ThreadSP thread_sp;
2005 if (tid != LLDB_INVALID_THREAD_ID)
2006 {
2007 // Scope for "locker" below
2008 {
2009 // m_thread_list_real does have its own mutex, but we need to
2010 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
2011 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
2012 Mutex::Locker locker (m_thread_list_real.GetMutex ());
2013 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
2014
2015 if (!thread_sp)
2016 {
2017 // Create the thread if we need to
2018 thread_sp.reset (new ThreadGDBRemote (*this, tid));
2019 m_thread_list_real.AddThread(thread_sp);
2020 }
2021 }
2022
2023 if (thread_sp)
2024 {
2025 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
2026 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002027
Greg Clayton358cf1e2015-06-25 21:46:34 +00002028 for (const auto &pair : expedited_register_map)
2029 {
2030 StringExtractor reg_value_extractor;
2031 reg_value_extractor.GetStringRef() = pair.second;
2032 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
2033 }
2034
Greg Clayton358cf1e2015-06-25 21:46:34 +00002035 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
2036
2037 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002038 // Check if the GDB server was able to provide the queue name, kind and serial number
2039 if (queue_vars_valid)
2040 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
2041 else
2042 gdb_thread->ClearQueueInfo();
2043
Greg Clayton2e309072015-07-17 23:42:28 +00002044 // Make sure we update our thread stop reason just once
2045 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002046 {
Greg Clayton2e309072015-07-17 23:42:28 +00002047 thread_sp->SetStopInfo (StopInfoSP());
Ryan Brown65d4d5c2015-09-16 21:20:44 +00002048 // If there's a memory thread backed by this thread, we need to use it to calcualte StopInfo.
2049 ThreadSP memory_thread_sp = m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
2050 if (memory_thread_sp)
2051 thread_sp = memory_thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002052
Greg Clayton2e309072015-07-17 23:42:28 +00002053 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002054 {
Greg Clayton2e309072015-07-17 23:42:28 +00002055 const size_t exc_data_size = exc_data.size();
2056
2057 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
2058 exc_type,
2059 exc_data_size,
2060 exc_data_size >= 1 ? exc_data[0] : 0,
2061 exc_data_size >= 2 ? exc_data[1] : 0,
2062 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002063 }
Greg Clayton2e309072015-07-17 23:42:28 +00002064 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002065 {
Greg Clayton2e309072015-07-17 23:42:28 +00002066 bool handled = false;
2067 bool did_exec = false;
2068 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002069 {
Greg Clayton2e309072015-07-17 23:42:28 +00002070 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002071 {
Greg Clayton2e309072015-07-17 23:42:28 +00002072 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2073 handled = true;
2074 }
2075 else if (reason.compare("breakpoint") == 0)
2076 {
2077 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2078 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2079 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002080 {
Greg Clayton2e309072015-07-17 23:42:28 +00002081 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2082 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2083 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2084 handled = true;
2085 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2086 {
2087 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2088 }
2089 else
2090 {
2091 StopInfoSP invalid_stop_info_sp;
2092 thread_sp->SetStopInfo (invalid_stop_info_sp);
2093 }
2094 }
2095 }
2096 else if (reason.compare("trap") == 0)
2097 {
2098 // Let the trap just use the standard signal stop reason below...
2099 }
2100 else if (reason.compare("watchpoint") == 0)
2101 {
2102 StringExtractor desc_extractor(description.c_str());
2103 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2104 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002105 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002106 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2107 if (wp_addr != LLDB_INVALID_ADDRESS)
2108 {
Mohit K. Bhakkad5df85ce2015-10-09 15:05:45 +00002109 if (wp_hit_addr != LLDB_INVALID_ADDRESS)
2110 wp_addr = wp_hit_addr;
Greg Clayton2e309072015-07-17 23:42:28 +00002111 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2112 if (wp_sp)
2113 {
2114 wp_sp->SetHardwareIndex(wp_index);
2115 watch_id = wp_sp->GetID();
2116 }
2117 }
2118 if (watch_id == LLDB_INVALID_WATCH_ID)
2119 {
2120 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2121 if (log) log->Printf ("failed to find watchpoint");
2122 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002123 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002124 handled = true;
2125 }
2126 else if (reason.compare("exception") == 0)
2127 {
2128 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2129 handled = true;
2130 }
2131 else if (reason.compare("exec") == 0)
2132 {
2133 did_exec = true;
2134 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2135 handled = true;
2136 }
2137 }
2138
2139 if (!handled && signo && did_exec == false)
2140 {
2141 if (signo == SIGTRAP)
2142 {
2143 // Currently we are going to assume SIGTRAP means we are either
2144 // hitting a breakpoint or hardware single stepping.
2145 handled = true;
2146 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2147 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2148
2149 if (bp_site_sp)
2150 {
2151 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2152 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2153 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2154 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2155 {
2156 if(m_breakpoint_pc_offset != 0)
2157 thread_sp->GetRegisterContext()->SetPC(pc);
2158 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2159 }
2160 else
2161 {
2162 StopInfoSP invalid_stop_info_sp;
2163 thread_sp->SetStopInfo (invalid_stop_info_sp);
2164 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002165 }
2166 else
2167 {
Greg Clayton2e309072015-07-17 23:42:28 +00002168 // If we were stepping then assume the stop was the result of the trace. If we were
2169 // not stepping then report the SIGTRAP.
2170 // FIXME: We are still missing the case where we single step over a trap instruction.
2171 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2172 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2173 else
2174 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002175 }
2176 }
Greg Clayton2e309072015-07-17 23:42:28 +00002177 if (!handled)
2178 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2179 }
2180
2181 if (!description.empty())
2182 {
2183 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2184 if (stop_info_sp)
2185 {
2186 const char *stop_info_desc = stop_info_sp->GetDescription();
2187 if (!stop_info_desc || !stop_info_desc[0])
2188 stop_info_sp->SetDescription (description.c_str());
2189 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002190 else
2191 {
Greg Clayton2e309072015-07-17 23:42:28 +00002192 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002193 }
2194 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002195 }
2196 }
2197 }
2198 }
2199 return thread_sp;
2200}
2201
Greg Clayton2e309072015-07-17 23:42:28 +00002202lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002203ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2204{
2205 static ConstString g_key_tid("tid");
2206 static ConstString g_key_name("name");
2207 static ConstString g_key_reason("reason");
2208 static ConstString g_key_metype("metype");
2209 static ConstString g_key_medata("medata");
2210 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002211 static ConstString g_key_queue_name("qname");
2212 static ConstString g_key_queue_kind("qkind");
2213 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002214 static ConstString g_key_registers("registers");
2215 static ConstString g_key_memory("memory");
2216 static ConstString g_key_address("address");
2217 static ConstString g_key_bytes("bytes");
2218 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002219 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002220
2221 // Stop with signal and thread info
2222 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2223 uint8_t signo = 0;
2224 std::string value;
2225 std::string thread_name;
2226 std::string reason;
2227 std::string description;
2228 uint32_t exc_type = 0;
2229 std::vector<addr_t> exc_data;
2230 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2231 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002232 bool queue_vars_valid = false;
2233 std::string queue_name;
2234 QueueKind queue_kind = eQueueKindUnknown;
2235 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002236 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2237
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002238 thread_dict->ForEach([this,
2239 &tid,
2240 &expedited_register_map,
2241 &thread_name,
2242 &signo,
2243 &reason,
2244 &description,
2245 &exc_type,
2246 &exc_data,
2247 &thread_dispatch_qaddr,
2248 &queue_vars_valid,
2249 &queue_name,
2250 &queue_kind,
2251 &queue_serial]
2252 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002253 {
2254 if (key == g_key_tid)
2255 {
2256 // thread in big endian hex
2257 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2258 }
2259 else if (key == g_key_metype)
2260 {
2261 // exception type in big endian hex
2262 exc_type = object->GetIntegerValue(0);
2263 }
2264 else if (key == g_key_medata)
2265 {
2266 // exception data in big endian hex
2267 StructuredData::Array *array = object->GetAsArray();
2268 if (array)
2269 {
2270 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2271 exc_data.push_back(object->GetIntegerValue());
2272 return true; // Keep iterating through all array items
2273 });
2274 }
2275 }
2276 else if (key == g_key_name)
2277 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002278 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002279 }
2280 else if (key == g_key_qaddr)
2281 {
2282 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2283 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002284 else if (key == g_key_queue_name)
2285 {
2286 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002287 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002288 }
2289 else if (key == g_key_queue_kind)
2290 {
2291 std::string queue_kind_str = object->GetStringValue();
2292 if (queue_kind_str == "serial")
2293 {
2294 queue_vars_valid = true;
2295 queue_kind = eQueueKindSerial;
2296 }
2297 else if (queue_kind_str == "concurrent")
2298 {
2299 queue_vars_valid = true;
2300 queue_kind = eQueueKindConcurrent;
2301 }
2302 }
2303 else if (key == g_key_queue_serial)
2304 {
2305 queue_serial = object->GetIntegerValue(0);
2306 if (queue_serial != 0)
2307 queue_vars_valid = true;
2308 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002309 else if (key == g_key_reason)
2310 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002311 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002312 }
2313 else if (key == g_key_description)
2314 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002315 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002316 }
2317 else if (key == g_key_registers)
2318 {
2319 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2320
2321 if (registers_dict)
2322 {
2323 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2324 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2325 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002326 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002327 return true; // Keep iterating through all array items
2328 });
2329 }
2330 }
2331 else if (key == g_key_memory)
2332 {
2333 StructuredData::Array *array = object->GetAsArray();
2334 if (array)
2335 {
2336 array->ForEach([this](StructuredData::Object* object) -> bool {
2337 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2338 if (mem_cache_dict)
2339 {
2340 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2341 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2342 {
2343 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2344 {
2345 StringExtractor bytes;
2346 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2347 {
2348 bytes.SetFilePos(0);
2349
2350 const size_t byte_size = bytes.GetStringRef().size()/2;
2351 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2352 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2353 if (bytes_copied == byte_size)
2354 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2355 }
2356 }
2357 }
2358 }
2359 return true; // Keep iterating through all array items
2360 });
2361 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00002362
Greg Clayton358cf1e2015-06-25 21:46:34 +00002363 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002364 else if (key == g_key_signal)
2365 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002366 return true; // Keep iterating through all dictionary key/value pairs
2367 });
2368
Greg Clayton2e309072015-07-17 23:42:28 +00002369 return SetThreadStopInfo (tid,
2370 expedited_register_map,
2371 signo,
2372 thread_name,
2373 reason,
2374 description,
2375 exc_type,
2376 exc_data,
2377 thread_dispatch_qaddr,
2378 queue_vars_valid,
2379 queue_name,
2380 queue_kind,
2381 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002382}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002383
2384StateType
2385ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2386{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002387 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002388 const char stop_type = stop_packet.GetChar();
2389 switch (stop_type)
2390 {
2391 case 'T':
2392 case 'S':
2393 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002394 // This is a bit of a hack, but is is required. If we did exec, we
2395 // need to clear our thread lists and also know to rebuild our dynamic
2396 // register info before we lookup and threads and populate the expedited
2397 // register values so we need to know this right away so we can cleanup
2398 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002399 const uint32_t stop_id = GetStopID();
2400 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002401 {
2402 // Our first stop, make sure we have a process ID, and also make
2403 // sure we know about our registers
2404 if (GetID() == LLDB_INVALID_PROCESS_ID)
2405 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002406 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002407 if (pid != LLDB_INVALID_PROCESS_ID)
2408 SetID (pid);
2409 }
2410 BuildDynamicRegisterInfo (true);
2411 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002412 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002413 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002414 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002415 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002416 std::string value;
2417 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002418 std::string reason;
2419 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002420 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002421 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002422 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002423 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2424 std::string queue_name;
2425 QueueKind queue_kind = eQueueKindUnknown;
2426 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002427 ExpeditedRegisterMap expedited_register_map;
2428 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002430 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002431 {
2432 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002433 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002434 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002435 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002436 {
2437 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002438 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002439 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002440 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002441 {
2442 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002443 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002444 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002445 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002446 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002447 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002448 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002449 // A comma separated list of all threads in the current
2450 // process that includes the thread for this stop reply
2451 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002452 size_t comma_pos;
2453 lldb::tid_t tid;
2454 while ((comma_pos = value.find(',')) != std::string::npos)
2455 {
2456 value[comma_pos] = '\0';
2457 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002458 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002459 if (tid != LLDB_INVALID_THREAD_ID)
2460 m_thread_ids.push_back (tid);
2461 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002462 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002463 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002464 if (tid != LLDB_INVALID_THREAD_ID)
2465 m_thread_ids.push_back (tid);
2466 }
Greg Clayton2e309072015-07-17 23:42:28 +00002467 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002468 {
2469 StringExtractor json_extractor;
2470 // Swap "value" over into "name_extractor"
2471 json_extractor.GetStringRef().swap(value);
2472 // Now convert the HEX bytes into a string value
2473 json_extractor.GetHexByteString (value);
2474
2475 // This JSON contains thread IDs and thread stop info for all threads.
2476 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002477 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002478 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002479 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002480 {
2481 StringExtractor name_extractor;
2482 // Swap "value" over into "name_extractor"
2483 name_extractor.GetStringRef().swap(value);
2484 // Now convert the HEX bytes into a string value
2485 name_extractor.GetHexByteString (value);
2486 thread_name.swap (value);
2487 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002488 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002489 {
2490 thread_name.swap (value);
2491 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002492 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002493 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002494 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002495 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002496 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002497 {
2498 queue_vars_valid = true;
2499 StringExtractor name_extractor;
2500 // Swap "value" over into "name_extractor"
2501 name_extractor.GetStringRef().swap(value);
2502 // Now convert the HEX bytes into a string value
2503 name_extractor.GetHexByteString (value);
2504 queue_name.swap (value);
2505 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002506 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002507 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002508 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002509 {
2510 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002511 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002512 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002513 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002514 {
2515 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002516 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002517 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002518 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002519 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002520 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002521 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002522 if (queue_serial != 0)
2523 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002524 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002525 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002526 {
2527 reason.swap(value);
2528 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002529 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002530 {
2531 StringExtractor desc_extractor;
2532 // Swap "value" over into "name_extractor"
2533 desc_extractor.GetStringRef().swap(value);
2534 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002535 desc_extractor.GetHexByteString (value);
2536 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002537 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002538 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002539 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002540 // Expedited memory. GDB servers can choose to send back expedited memory
2541 // that can populate the L1 memory cache in the process so that things like
2542 // the frame pointer backchain can be expedited. This will help stack
2543 // backtracing be more efficient by not having to send as many memory read
2544 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002545
Greg Clayton358cf1e2015-06-25 21:46:34 +00002546 // Key/value pair format: memory:<addr>=<bytes>;
2547 // <addr> is a number whose base will be interpreted by the prefix:
2548 // "0x[0-9a-fA-F]+" for hex
2549 // "0[0-7]+" for octal
2550 // "[1-9]+" for decimal
2551 // <bytes> is native endian ASCII hex bytes just like the register values
2552 llvm::StringRef value_ref(value);
2553 std::pair<llvm::StringRef, llvm::StringRef> pair;
2554 pair = value_ref.split('=');
2555 if (!pair.first.empty() && !pair.second.empty())
2556 {
2557 std::string addr_str(pair.first.str());
2558 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2559 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002560 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002561 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002562 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002563 const size_t byte_size = bytes.GetStringRef().size()/2;
2564 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2565 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2566 if (bytes_copied == byte_size)
2567 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002568 }
2569 }
2570 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002571 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2572 {
2573 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2574 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2575 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2576 uint32_t wp_index = LLDB_INVALID_INDEX32;
2577
2578 if (wp_sp)
2579 wp_index = wp_sp->GetHardwareIndex();
2580
2581 reason = "watchpoint";
2582 StreamString ostr;
2583 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2584 description = ostr.GetString().c_str();
2585 }
Stephane Sezer2618e912015-08-21 16:51:56 +00002586 else if (key.compare("library") == 0)
2587 {
2588 LoadModules();
2589 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002590 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2591 {
2592 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2593 if (reg != UINT32_MAX)
2594 expedited_register_map[reg] = std::move(value);
2595 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002596 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002597
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002598 if (tid == LLDB_INVALID_THREAD_ID)
2599 {
2600 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2601 // thread information. So update the thread list and choose the first one.
2602 UpdateThreadIDList ();
2603
2604 if (!m_thread_ids.empty ())
2605 {
2606 tid = m_thread_ids.front ();
2607 }
2608 }
2609
Greg Clayton358cf1e2015-06-25 21:46:34 +00002610 ThreadSP thread_sp = SetThreadStopInfo (tid,
2611 expedited_register_map,
2612 signo,
2613 thread_name,
2614 reason,
2615 description,
2616 exc_type,
2617 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002618 thread_dispatch_qaddr,
2619 queue_vars_valid,
2620 queue_name,
2621 queue_kind,
2622 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002623
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002624 return eStateStopped;
2625 }
2626 break;
2627
2628 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002629 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002630 // process exited
2631 return eStateExited;
2632
2633 default:
2634 break;
2635 }
2636 return eStateInvalid;
2637}
2638
2639void
2640ProcessGDBRemote::RefreshStateAfterStop ()
2641{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002642 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002643 m_thread_ids.clear();
2644 // Set the thread stop info. It might have a "threads" key whose value is
2645 // a list of all thread IDs in the current process, so m_thread_ids might
2646 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002647
2648 // Scope for the lock
2649 {
2650 // Lock the thread stack while we access it
2651 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2652 // Get the number of stop packets on the stack
2653 int nItems = m_stop_packet_stack.size();
2654 // Iterate over them
2655 for (int i = 0; i < nItems; i++)
2656 {
2657 // Get the thread stop info
2658 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2659 // Process thread stop info
2660 SetThreadStopInfo(stop_info);
2661 }
2662 // Clear the thread stop stack
2663 m_stop_packet_stack.clear();
2664 }
2665
Greg Clayton9e920902012-04-10 02:25:43 +00002666 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2667 if (m_thread_ids.empty())
2668 {
2669 // No, we need to fetch the thread list manually
2670 UpdateThreadIDList();
2671 }
2672
Ewan Crawford78baa192015-05-13 09:18:18 +00002673 // If we have queried for a default thread id
2674 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2675 {
2676 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2677 m_initial_tid = LLDB_INVALID_THREAD_ID;
2678 }
2679
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002680 // Let all threads recover from stopping and do any clean up based
2681 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002682 m_thread_list_real.RefreshStateAfterStop();
Eugene Zelenko0722f082015-10-24 01:28:05 +00002683
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002684}
2685
2686Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002687ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002688{
2689 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002690
Greg Clayton6ed95942011-01-22 07:12:45 +00002691 bool timed_out = false;
2692 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002693
2694 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002695 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002696 // We are being asked to halt during an attach. We need to just close
2697 // our file handle and debugserver will go away, and we can be done...
2698 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002699 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002700 else
2701 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002702 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002703 {
2704 if (timed_out)
2705 error.SetErrorString("timed out sending interrupt packet");
2706 else
2707 error.SetErrorString("unknown error sending interrupt packet");
2708 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002709
2710 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002711 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002712 return error;
2713}
2714
2715Error
Jim Inghamacff8952013-05-02 00:27:30 +00002716ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002717{
2718 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002719 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002720 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002721 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2722
Jim Inghamacff8952013-05-02 00:27:30 +00002723 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002724 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002725 {
Jim Inghamacff8952013-05-02 00:27:30 +00002726 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002727 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2728 else
Jim Inghamacff8952013-05-02 00:27:30 +00002729 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002730 }
Jim Inghamacff8952013-05-02 00:27:30 +00002731
2732 if (!error.Success())
2733 return error;
2734
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002735 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002736 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002737
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002738 SetPrivateState (eStateDetached);
2739 ResumePrivateStateThread();
2740
2741 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002742 return error;
2743}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002744
Eugene Zelenko0722f082015-10-24 01:28:05 +00002745
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002746Error
2747ProcessGDBRemote::DoDestroy ()
2748{
2749 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002750 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002751 if (log)
2752 log->Printf ("ProcessGDBRemote::DoDestroy()");
2753
Jim Ingham43c555d2012-07-04 00:35:43 +00002754 // There is a bug in older iOS debugservers where they don't shut down the process
2755 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2756 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2757 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2758 // destroy it again.
2759 //
2760 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2761 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2762 // the debugservers with this bug are equal. There really should be a better way to test this!
2763 //
2764 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2765 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2766 // just do the straight-forward kill.
2767 //
2768 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2769 // necessary (or helpful) to do any of this.
2770
2771 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2772 {
2773 PlatformSP platform_sp = GetTarget().GetPlatform();
2774
2775 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2776 if (platform_sp
2777 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002778 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002779 {
2780 if (m_destroy_tried_resuming)
2781 {
2782 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002783 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002784 }
2785 else
2786 {
2787 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2788 // but we really need it to happen here and it doesn't matter if we do it twice.
2789 m_thread_list.DiscardThreadPlans();
2790 DisableAllBreakpointSites();
2791
2792 bool stop_looks_like_crash = false;
2793 ThreadList &threads = GetThreadList();
2794
2795 {
Jim Ingham45350372012-09-11 00:08:52 +00002796 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002797
2798 size_t num_threads = threads.GetSize();
2799 for (size_t i = 0; i < num_threads; i++)
2800 {
2801 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002802 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002803 StopReason reason = eStopReasonInvalid;
2804 if (stop_info_sp)
2805 reason = stop_info_sp->GetStopReason();
2806 if (reason == eStopReasonBreakpoint
2807 || reason == eStopReasonException)
2808 {
2809 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002810 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2811 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002812 stop_info_sp->GetDescription());
2813 stop_looks_like_crash = true;
2814 break;
2815 }
2816 }
2817 }
2818
2819 if (stop_looks_like_crash)
2820 {
2821 if (log)
2822 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2823 m_destroy_tried_resuming = true;
2824
2825 // If we are going to run again before killing, it would be good to suspend all the threads
2826 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2827 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2828 // have to run the risk of letting those threads proceed a bit.
2829
2830 {
Jim Ingham45350372012-09-11 00:08:52 +00002831 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002832
2833 size_t num_threads = threads.GetSize();
2834 for (size_t i = 0; i < num_threads; i++)
2835 {
2836 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002837 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002838 StopReason reason = eStopReasonInvalid;
2839 if (stop_info_sp)
2840 reason = stop_info_sp->GetStopReason();
2841 if (reason != eStopReasonBreakpoint
2842 && reason != eStopReasonException)
2843 {
2844 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002845 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2846 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002847 thread_sp->SetResumeState(eStateSuspended);
2848 }
2849 }
2850 }
2851 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002852 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002853 }
2854 }
2855 }
2856 }
2857
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002858 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002859 int exit_status = SIGABRT;
2860 std::string exit_string;
2861
Greg Clayton6ed95942011-01-22 07:12:45 +00002862 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002863 {
Jim Inghamaab78372011-10-28 01:11:35 +00002864 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002865 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002866 StringExtractorGDBRemote response;
2867 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002868 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002869
Greg Clayton3dedae12013-12-06 21:45:27 +00002870 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002871 {
2872 char packet_cmd = response.GetChar(0);
2873
2874 if (packet_cmd == 'W' || packet_cmd == 'X')
2875 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002876#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002877 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2878 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2879 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2880 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2881 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2882 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2883 // Anyway, so call waitpid here to finally reap it.
2884 PlatformSP platform_sp(GetTarget().GetPlatform());
2885 if (platform_sp && platform_sp->IsHost())
2886 {
2887 int status;
2888 ::pid_t reap_pid;
2889 reap_pid = waitpid (GetID(), &status, WNOHANG);
2890 if (log)
2891 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2892 }
2893#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002894 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002895 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002896 exit_status = response.GetHexU8();
2897 }
2898 else
2899 {
2900 if (log)
2901 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2902 exit_string.assign("got unexpected response to k packet: ");
2903 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002904 }
2905 }
2906 else
2907 {
Jim Inghambabfc382012-06-06 00:32:39 +00002908 if (log)
2909 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2910 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002911 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002912 }
Jim Inghambabfc382012-06-06 00:32:39 +00002913 else
2914 {
2915 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002916 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002917 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002918 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002919 }
Jim Inghambabfc382012-06-06 00:32:39 +00002920 else
2921 {
2922 // If we missed setting the exit status on the way out, do it here.
2923 // NB set exit status can be called multiple times, the first one sets the status.
2924 exit_string.assign("destroying when not connected to debugserver");
2925 }
2926
2927 SetExitStatus(exit_status, exit_string.c_str());
2928
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002929 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002930 KillDebugserverProcess ();
2931 return error;
2932}
2933
Greg Clayton8cda7f02013-05-21 21:55:59 +00002934void
2935ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2936{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002937 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2938 if (did_exec)
2939 {
2940 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2941 if (log)
2942 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2943
2944 m_thread_list_real.Clear();
2945 m_thread_list.Clear();
2946 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002947 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002948 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002949
2950 // Scope the lock
2951 {
2952 // Lock the thread stack while we access it
2953 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002954
2955 // We are are not using non-stop mode, there can only be one last stop
2956 // reply packet, so clear the list.
2957 if (GetTarget().GetNonStopModeEnabled() == false)
2958 m_stop_packet_stack.clear();
2959
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002960 // Add this stop packet to the stop packet stack
2961 // This stack will get popped and examined when we switch to the
2962 // Stopped state
2963 m_stop_packet_stack.push_back(response);
2964 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002965}
2966
Chaoren Linc963a222015-09-01 16:58:45 +00002967void
2968ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
2969{
2970 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2971}
2972
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002973//------------------------------------------------------------------
2974// Process Queries
2975//------------------------------------------------------------------
2976
2977bool
2978ProcessGDBRemote::IsAlive ()
2979{
Greg Clayton10177aa2010-12-08 05:08:21 +00002980 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002981}
2982
2983addr_t
2984ProcessGDBRemote::GetImageInfoAddress()
2985{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002986 // request the link map address via the $qShlibInfoAddr packet
2987 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2988
2989 // the loaded module list can also provides a link map address
2990 if (addr == LLDB_INVALID_ADDRESS)
2991 {
2992 GDBLoadedModuleInfoList list;
2993 if (GetLoadedModuleList (list).Success())
2994 addr = list.m_link_map;
2995 }
2996
2997 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002998}
2999
Greg Clayton2e309072015-07-17 23:42:28 +00003000void
3001ProcessGDBRemote::WillPublicStop ()
3002{
3003 // See if the GDB remote client supports the JSON threads info.
3004 // If so, we gather stop info for all threads, expedited registers,
3005 // expedited memory, runtime queue information (iOS and MacOSX only),
3006 // and more. Expediting memory will help stack backtracing be much
3007 // faster. Expediting registers will make sure we don't have to read
3008 // the thread registers for GPRs.
3009 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
3010
3011 if (m_jthreadsinfo_sp)
3012 {
3013 // Now set the stop info for each thread and also expedite any registers
3014 // and memory that was in the jThreadsInfo response.
3015 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
3016 if (thread_infos)
3017 {
3018 const size_t n = thread_infos->GetSize();
3019 for (size_t i=0; i<n; ++i)
3020 {
3021 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
3022 if (thread_dict)
3023 SetThreadStopInfo(thread_dict);
3024 }
3025 }
3026 }
3027}
3028
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003029//------------------------------------------------------------------
3030// Process Memory
3031//------------------------------------------------------------------
3032size_t
3033ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
3034{
Jason Molenda6076bf42014-05-06 04:34:52 +00003035 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036 if (size > m_max_memory_size)
3037 {
3038 // Keep memory read sizes down to a sane limit. This function will be
3039 // called multiple times in order to complete the task by
3040 // lldb_private::Process so it is ok to do this.
3041 size = m_max_memory_size;
3042 }
3043
3044 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00003045 int packet_len;
3046 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
Pavel Labath3bf11252015-10-14 12:59:37 +00003047 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
3048 binary_memory_read ? 'x' : 'm', (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00003049 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003050 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003051 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003052 {
Greg Clayton576d8832011-03-22 04:00:09 +00003053 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003054 {
3055 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00003056 if (binary_memory_read)
3057 {
3058 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3059 // 0x7d character escaping that was present in the packet
3060
3061 size_t data_received_size = response.GetBytesLeft();
3062 if (data_received_size > size)
3063 {
3064 // Don't write past the end of BUF if the remote debug server gave us too
3065 // much data for some reason.
3066 data_received_size = size;
3067 }
3068 memcpy (buf, response.GetStringRef().data(), data_received_size);
3069 return data_received_size;
3070 }
3071 else
3072 {
3073 return response.GetHexBytes(buf, size, '\xdd');
3074 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003075 }
Greg Clayton576d8832011-03-22 04:00:09 +00003076 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003077 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003078 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003079 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003080 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003081 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003082 }
3083 else
3084 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003085 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003086 }
3087 return 0;
3088}
3089
3090size_t
3091ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3092{
Jason Molenda6076bf42014-05-06 04:34:52 +00003093 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003094 if (size > m_max_memory_size)
3095 {
3096 // Keep memory read sizes down to a sane limit. This function will be
3097 // called multiple times in order to complete the task by
3098 // lldb_private::Process so it is ok to do this.
3099 size = m_max_memory_size;
3100 }
3101
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003102 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003103 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00003104 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003105 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003106 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003107 {
Greg Clayton576d8832011-03-22 04:00:09 +00003108 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003109 {
3110 error.Clear();
3111 return size;
3112 }
Greg Clayton576d8832011-03-22 04:00:09 +00003113 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003114 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003115 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003116 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003117 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003118 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 +00003119 }
3120 else
3121 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003122 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003123 }
3124 return 0;
3125}
3126
3127lldb::addr_t
3128ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3129{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003130 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003131 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3132
Greg Clayton70b57652011-05-15 01:25:55 +00003133 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003134 switch (supported)
3135 {
3136 case eLazyBoolCalculate:
3137 case eLazyBoolYes:
3138 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3139 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3140 return allocated_addr;
3141
3142 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003143 // Call mmap() to create memory in the inferior..
3144 unsigned prot = 0;
3145 if (permissions & lldb::ePermissionsReadable)
3146 prot |= eMmapProtRead;
3147 if (permissions & lldb::ePermissionsWritable)
3148 prot |= eMmapProtWrite;
3149 if (permissions & lldb::ePermissionsExecutable)
3150 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003151
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003152 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3153 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3154 m_addr_to_mmap_size[allocated_addr] = size;
3155 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003156 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003157 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003158 if (log)
3159 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3160 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003161 break;
3162 }
3163
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003164 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003165 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003166 else
3167 error.Clear();
3168 return allocated_addr;
3169}
3170
3171Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003172ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3173 MemoryRegionInfo &region_info)
3174{
Eugene Zelenko0722f082015-10-24 01:28:05 +00003175
Greg Clayton46fb5582011-11-18 07:03:08 +00003176 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3177 return error;
3178}
3179
3180Error
Johnny Chen64637202012-05-23 21:09:52 +00003181ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3182{
Eugene Zelenko0722f082015-10-24 01:28:05 +00003183
Johnny Chen64637202012-05-23 21:09:52 +00003184 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3185 return error;
3186}
3187
3188Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003189ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3190{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003191 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003192 return error;
3193}
3194
3195Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003196ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3197{
3198 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003199 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3200
3201 switch (supported)
3202 {
3203 case eLazyBoolCalculate:
3204 // We should never be deallocating memory without allocating memory
3205 // first so we should never get eLazyBoolCalculate
3206 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3207 break;
3208
3209 case eLazyBoolYes:
3210 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003211 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003212 break;
3213
3214 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003215 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003216 {
3217 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003218 if (pos != m_addr_to_mmap_size.end() &&
3219 InferiorCallMunmap(this, addr, pos->second))
3220 m_addr_to_mmap_size.erase (pos);
3221 else
Daniel Malead01b2952012-11-29 21:49:15 +00003222 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003223 }
3224 break;
3225 }
3226
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003227 return error;
3228}
3229
Eugene Zelenko0722f082015-10-24 01:28:05 +00003230
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003231//------------------------------------------------------------------
3232// Process STDIO
3233//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003234size_t
3235ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3236{
3237 if (m_stdio_communication.IsConnected())
3238 {
3239 ConnectionStatus status;
3240 m_stdio_communication.Write(src, src_len, status, NULL);
3241 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003242 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003243 {
3244 m_gdb_comm.SendStdinNotification(src, src_len);
3245 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003246 return 0;
3247}
3248
3249Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003250ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003251{
3252 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003253 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003254
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003255 // Get logging info
3256 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003257 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003258
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003259 // Get the breakpoint address
3260 const addr_t addr = bp_site->GetLoadAddress();
3261
3262 // Log that a breakpoint was requested
3263 if (log)
3264 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3265
3266 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003267 if (bp_site->IsEnabled())
3268 {
3269 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003270 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 +00003271 return error;
3272 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003273
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003274 // Get the software breakpoint trap opcode size
3275 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3276
3277 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3278 // is supported by the remote stub. These are set to true by default, and later set to false
3279 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3280 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3281 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3282 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3283 // skip over software breakpoints.
3284 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3285 {
3286 // Try to send off a software breakpoint packet ($Z0)
3287 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003288 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003289 // The breakpoint was placed successfully
3290 bp_site->SetEnabled(true);
3291 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003292 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003293 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003294
3295 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3296 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3297 // or if we have learned that this breakpoint type is unsupported. To do this, we
3298 // must test the support boolean for this breakpoint type to see if it now indicates that
3299 // this breakpoint type is unsupported. If they are still supported then we should return
3300 // with the error code. If they are now unsupported, then we would like to fall through
3301 // and try another form of breakpoint.
3302 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3303 return error;
3304
3305 // We reach here when software breakpoints have been found to be unsupported. For future
3306 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3307 // known not to be supported.
3308 if (log)
3309 log->Printf("Software breakpoints are unsupported");
3310
3311 // So we will fall through and try a hardware breakpoint
3312 }
3313
3314 // The process of setting a hardware breakpoint is much the same as above. We check the
3315 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3316 // will try to set this breakpoint with a hardware breakpoint.
3317 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3318 {
3319 // Try to send off a hardware breakpoint packet ($Z1)
3320 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003321 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003322 // The breakpoint was placed successfully
3323 bp_site->SetEnabled(true);
3324 bp_site->SetType(BreakpointSite::eHardware);
3325 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003326 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003327
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003328 // Check if the error was something other then an unsupported breakpoint type
3329 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3330 {
3331 // Unable to set this hardware breakpoint
3332 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3333 return error;
3334 }
3335
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003336 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003337 if (log)
3338 log->Printf("Hardware breakpoints are unsupported");
3339
3340 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003341 }
3342
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003343 // Don't fall through when hardware breakpoints were specifically requested
3344 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003345 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003346 error.SetErrorString("hardware breakpoints are not supported");
3347 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003348 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003349
3350 // As a last resort we want to place a manual breakpoint. An instruction
3351 // is placed into the process memory using memory write packets.
3352 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003353}
3354
3355Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003356ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003357{
3358 Error error;
3359 assert (bp_site != NULL);
3360 addr_t addr = bp_site->GetLoadAddress();
3361 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003362 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003363 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003364 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003365
3366 if (bp_site->IsEnabled())
3367 {
3368 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3369
Greg Clayton8b82f082011-04-12 05:54:46 +00003370 BreakpointSite::Type bp_type = bp_site->GetType();
3371 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003372 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003373 case BreakpointSite::eSoftware:
3374 error = DisableSoftwareBreakpoint (bp_site);
3375 break;
3376
3377 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003378 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003379 error.SetErrorToGenericError();
3380 break;
3381
3382 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003383 {
3384 GDBStoppointType stoppoint_type;
3385 if (bp_site->IsHardware())
3386 stoppoint_type = eBreakpointHardware;
3387 else
3388 stoppoint_type = eBreakpointSoftware;
3389
3390 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003391 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003392 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003393 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003394 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003395 if (error.Success())
3396 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003397 }
3398 else
3399 {
3400 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003401 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 +00003402 return error;
3403 }
3404
3405 if (error.Success())
3406 error.SetErrorToGenericError();
3407 return error;
3408}
3409
Johnny Chen11309a32011-09-06 22:38:36 +00003410// Pre-requisite: wp != NULL.
3411static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003412GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003413{
3414 assert(wp);
3415 bool watch_read = wp->WatchpointRead();
3416 bool watch_write = wp->WatchpointWrite();
3417
3418 // watch_read and watch_write cannot both be false.
3419 assert(watch_read || watch_write);
3420 if (watch_read && watch_write)
3421 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003422 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003423 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003424 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003425 return eWatchpointWrite;
3426}
3427
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003428Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003429ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003430{
3431 Error error;
3432 if (wp)
3433 {
3434 user_id_t watchID = wp->GetID();
3435 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003436 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003437 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003438 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003439 if (wp->IsEnabled())
3440 {
3441 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003442 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 +00003443 return error;
3444 }
Johnny Chen11309a32011-09-06 22:38:36 +00003445
3446 GDBStoppointType type = GetGDBStoppointType(wp);
3447 // Pass down an appropriate z/Z packet...
3448 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003449 {
Johnny Chen11309a32011-09-06 22:38:36 +00003450 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3451 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003452 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003453 return error;
3454 }
3455 else
3456 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003457 }
Johnny Chen11309a32011-09-06 22:38:36 +00003458 else
3459 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003460 }
3461 else
3462 {
Johnny Chen01a67862011-10-14 00:42:25 +00003463 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003464 }
3465 if (error.Success())
3466 error.SetErrorToGenericError();
3467 return error;
3468}
3469
3470Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003471ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003472{
3473 Error error;
3474 if (wp)
3475 {
3476 user_id_t watchID = wp->GetID();
3477
Greg Clayton5160ce52013-03-27 23:08:40 +00003478 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003479
3480 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003481
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003482 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003483 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003484
Johnny Chen11309a32011-09-06 22:38:36 +00003485 if (!wp->IsEnabled())
3486 {
3487 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003488 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 +00003489 // See also 'class WatchpointSentry' within StopInfo.cpp.
3490 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3491 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003492 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003493 return error;
3494 }
3495
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003496 if (wp->IsHardware())
3497 {
Johnny Chen11309a32011-09-06 22:38:36 +00003498 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003499 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003500 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3501 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003502 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003503 return error;
3504 }
3505 else
3506 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003507 }
3508 // TODO: clear software watchpoints if we implement them
3509 }
3510 else
3511 {
Johnny Chen01a67862011-10-14 00:42:25 +00003512 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003513 }
3514 if (error.Success())
3515 error.SetErrorToGenericError();
3516 return error;
3517}
3518
3519void
3520ProcessGDBRemote::Clear()
3521{
3522 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003523 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003524 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003525}
3526
3527Error
3528ProcessGDBRemote::DoSignal (int signo)
3529{
3530 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003531 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003532 if (log)
3533 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3534
3535 if (!m_gdb_comm.SendAsyncSignal (signo))
3536 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3537 return error;
3538}
3539
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003540Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003541ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003542{
3543 Error error;
3544 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3545 {
3546 // If we locate debugserver, keep that located version around
3547 static FileSpec g_debugserver_file_spec;
3548
Han Ming Ong84647042012-02-25 01:07:38 +00003549 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003550 // Make debugserver run in its own session so signals generated by
3551 // special terminal key sequences (^C) don't affect debugserver.
3552 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3553
Greg Clayton91a9b2472013-12-04 19:19:12 +00003554 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3555 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003556
Todd Fiala013434e2014-07-09 01:29:05 +00003557#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003558 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003559 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003560 uint16_t port = get_random_port ();
3561#else
3562 // Set hostname being NULL to do the reverse connect where debugserver
3563 // will bind to port zero and it will communicate back to us the port
3564 // that we will connect to
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003565 const char *hostname = nullptr;
Greg Claytonfda4fab2014-01-10 22:24:11 +00003566 uint16_t port = 0;
3567#endif
3568
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003569 StreamString url_str;
3570 const char* url = nullptr;
3571 if (hostname != nullptr)
3572 {
3573 url_str.Printf("%s:%u", hostname, port);
3574 url = url_str.GetData();
3575 }
3576
3577 error = m_gdb_comm.StartDebugserverProcess (url,
Greg Clayton6988abc2015-10-19 20:44:01 +00003578 GetTarget().GetPlatform().get(),
Greg Clayton00fe87b2013-12-05 22:58:22 +00003579 debugserver_launch_info,
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003580 &port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003581
3582 if (error.Success ())
3583 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003584 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003585 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003586
3587 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3588 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003589
3590 if (error.Fail())
3591 {
3592 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3593
3594 if (log)
3595 log->Printf("failed to start debugserver process: %s", error.AsCString());
3596 return error;
3597 }
3598
Greg Clayton00fe87b2013-12-05 22:58:22 +00003599 if (m_gdb_comm.IsConnected())
3600 {
3601 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3602 ConnectToDebugserver (NULL);
3603 }
3604 else
3605 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003606 StreamString connect_url;
3607 connect_url.Printf("connect://%s:%u", hostname, port);
3608 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003609 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003610
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003611 }
3612 return error;
3613}
3614
3615bool
3616ProcessGDBRemote::MonitorDebugserverProcess
3617(
3618 void *callback_baton,
3619 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003620 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003621 int signo, // Zero for no signal
3622 int exit_status // Exit value of process if signal is zero
3623)
3624{
Greg Claytone4e45922011-11-16 05:37:56 +00003625 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3626 // and might not exist anymore, so we need to carefully try to get the
3627 // target for this process first since we have a race condition when
3628 // we are done running between getting the notice that the inferior
3629 // process has died and the debugserver that was debugging this process.
3630 // In our test suite, we are also continually running process after
3631 // process, so we must be very careful to make sure:
3632 // 1 - process object hasn't been deleted already
3633 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003634
3635 // "debugserver_pid" argument passed in is the process ID for
3636 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003637 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003638
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003639 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003640
Greg Claytone4e45922011-11-16 05:37:56 +00003641 // Get a shared pointer to the target that has a matching process pointer.
3642 // This target could be gone, or the target could already have a new process
3643 // object inside of it
3644 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3645
Greg Clayton6779606a2011-01-22 23:43:18 +00003646 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003647 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 +00003648
Greg Claytone4e45922011-11-16 05:37:56 +00003649 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003650 {
Greg Claytone4e45922011-11-16 05:37:56 +00003651 // We found a process in a target that matches, but another thread
3652 // might be in the process of launching a new process that will
3653 // soon replace it, so get a shared pointer to the process so we
3654 // can keep it alive.
3655 ProcessSP process_sp (target_sp->GetProcessSP());
3656 // Now we have a shared pointer to the process that can't go away on us
3657 // so we now make sure it was the same as the one passed in, and also make
3658 // sure that our previous "process *" didn't get deleted and have a new
3659 // "process *" created in its place with the same pointer. To verify this
3660 // we make sure the process has our debugserver process ID. If we pass all
3661 // of these tests, then we are sure that this process is the one we were
3662 // looking for.
3663 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003664 {
Greg Claytone4e45922011-11-16 05:37:56 +00003665 // Sleep for a half a second to make sure our inferior process has
3666 // time to set its exit status before we set it incorrectly when
3667 // both the debugserver and the inferior process shut down.
3668 usleep (500000);
3669 // If our process hasn't yet exited, debugserver might have died.
3670 // If the process did exit, the we are reaping it.
3671 const StateType state = process->GetState();
3672
3673 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3674 state != eStateInvalid &&
3675 state != eStateUnloaded &&
3676 state != eStateExited &&
3677 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003678 {
Greg Claytone4e45922011-11-16 05:37:56 +00003679 char error_str[1024];
3680 if (signo)
3681 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003682 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003683 if (signal_cstr)
3684 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3685 else
3686 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3687 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003688 else
Greg Claytone4e45922011-11-16 05:37:56 +00003689 {
3690 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3691 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003692
Greg Claytone4e45922011-11-16 05:37:56 +00003693 process->SetExitStatus (-1, error_str);
3694 }
3695 // Debugserver has exited we need to let our ProcessGDBRemote
3696 // know that it no longer has a debugserver instance
3697 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003698 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003699 }
3700 return true;
3701}
3702
3703void
3704ProcessGDBRemote::KillDebugserverProcess ()
3705{
Greg Claytonfbb76342013-11-20 21:07:01 +00003706 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003707 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3708 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003709 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003710 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3711 }
3712}
3713
3714void
3715ProcessGDBRemote::Initialize()
3716{
Davide Italianoc8d69822015-04-03 04:24:32 +00003717 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003718
Davide Italianoc8d69822015-04-03 04:24:32 +00003719 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003720 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003721 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3722 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003723 CreateInstance,
3724 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003725 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726}
3727
Greg Clayton7f982402013-07-15 22:54:20 +00003728void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003729ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003730{
3731 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3732 {
3733 const bool is_global_setting = true;
3734 PluginManager::CreateSettingForProcessPlugin (debugger,
3735 GetGlobalPluginProperties()->GetValueProperties(),
3736 ConstString ("Properties for the gdb-remote process plug-in."),
3737 is_global_setting);
3738 }
3739}
3740
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003741bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003742ProcessGDBRemote::StartAsyncThread ()
3743{
Greg Clayton5160ce52013-03-27 23:08:40 +00003744 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003745
3746 if (log)
3747 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003748
3749 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003750 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003751 {
3752 // Create a thread that watches our internal state and controls which
3753 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003754
3755 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003756 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003757 else if (log)
3758 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003759
Zachary Turneracee96a2014-09-23 18:32:09 +00003760 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003761}
3762
3763void
3764ProcessGDBRemote::StopAsyncThread ()
3765{
Greg Clayton5160ce52013-03-27 23:08:40 +00003766 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003767
3768 if (log)
3769 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3770
Jim Ingham455fa5c2012-11-01 01:15:33 +00003771 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003772 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003773 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003774 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3775
3776 // This will shut down the async thread.
3777 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3778
3779 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003780 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003781 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003782 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003783 else if (log)
3784 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003785}
3786
Ewan Crawford76df2882015-06-23 12:32:06 +00003787bool
3788ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3789{
3790 // get the packet at a string
3791 const std::string &pkt = packet.GetStringRef();
3792 // skip %stop:
3793 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3794
3795 // pass as a thread stop info packet
3796 SetLastStopPacket(stop_info);
3797
3798 // check for more stop reasons
3799 HandleStopReplySequence();
3800
3801 // if the process is stopped then we need to fake a resume
3802 // so that we can stop properly with the new break. This
3803 // is possible due to SetPrivateState() broadcasting the
3804 // state change as a side effect.
3805 if (GetPrivateState() == lldb::StateType::eStateStopped)
3806 {
3807 SetPrivateState(lldb::StateType::eStateRunning);
3808 }
3809
3810 // since we have some stopped packets we can halt the process
3811 SetPrivateState(lldb::StateType::eStateStopped);
3812
3813 return true;
3814}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003815
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003816thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003817ProcessGDBRemote::AsyncThread (void *arg)
3818{
3819 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3820
Greg Clayton5160ce52013-03-27 23:08:40 +00003821 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003822 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003823 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003824
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003825 EventSP event_sp;
Pavel Labath50556852015-09-03 09:36:22 +00003826 bool done = false;
3827 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003828 {
Pavel Labath50556852015-09-03 09:36:22 +00003829 if (log)
3830 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
3831 if (process->m_async_listener.WaitForEvent (NULL, event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003832 {
Pavel Labath50556852015-09-03 09:36:22 +00003833 const uint32_t event_type = event_sp->GetType();
3834 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003835 {
3836 if (log)
Pavel Labath50556852015-09-03 09:36:22 +00003837 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3838
3839 switch (event_type)
3840 {
3841 case eBroadcastBitAsyncContinue:
3842 {
3843 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3844
3845 if (continue_packet)
3846 {
3847 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3848 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3849 if (log)
3850 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3851
3852 if (::strstr (continue_cstr, "vAttach") == NULL)
3853 process->SetPrivateState(eStateRunning);
3854 StringExtractorGDBRemote response;
3855
3856 // If in Non-Stop-Mode
3857 if (process->GetTarget().GetNonStopModeEnabled())
3858 {
3859 // send the vCont packet
3860 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
3861 {
3862 // Something went wrong
3863 done = true;
3864 break;
3865 }
3866 }
3867 // If in All-Stop-Mode
3868 else
3869 {
3870 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3871
3872 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3873 // The thread ID list might be contained within the "response", or the stop reply packet that
3874 // caused the stop. So clear it now before we give the stop reply packet to the process
3875 // using the process->SetLastStopPacket()...
3876 process->ClearThreadIDList ();
3877
3878 switch (stop_state)
3879 {
3880 case eStateStopped:
3881 case eStateCrashed:
3882 case eStateSuspended:
3883 process->SetLastStopPacket (response);
3884 process->SetPrivateState (stop_state);
3885 break;
3886
3887 case eStateExited:
3888 {
3889 process->SetLastStopPacket (response);
3890 process->ClearThreadIDList();
3891 response.SetFilePos(1);
3892
3893 int exit_status = response.GetHexU8();
3894 const char *desc_cstr = NULL;
3895 StringExtractor extractor;
3896 std::string desc_string;
3897 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3898 {
3899 std::string desc_token;
3900 while (response.GetNameColonValue (desc_token, desc_string))
3901 {
3902 if (desc_token == "description")
3903 {
3904 extractor.GetStringRef().swap(desc_string);
3905 extractor.SetFilePos(0);
3906 extractor.GetHexByteString (desc_string);
3907 desc_cstr = desc_string.c_str();
3908 }
3909 }
3910 }
3911 process->SetExitStatus(exit_status, desc_cstr);
3912 done = true;
3913 break;
3914 }
3915 case eStateInvalid:
3916 {
3917 // Check to see if we were trying to attach and if we got back
3918 // the "E87" error code from debugserver -- this indicates that
3919 // the process is not debuggable. Return a slightly more helpful
3920 // error message about why the attach failed.
3921 if (::strstr (continue_cstr, "vAttach") != NULL
3922 && response.GetError() == 0x87)
3923 {
3924 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3925 }
3926 // E01 code from vAttach means that the attach failed
3927 if (::strstr (continue_cstr, "vAttach") != NULL
3928 && response.GetError() == 0x1)
3929 {
3930 process->SetExitStatus(-1, "unable to attach");
3931 }
3932 else
3933 {
3934 process->SetExitStatus(-1, "lost connection");
3935 }
3936 break;
3937 }
3938
3939 default:
3940 process->SetPrivateState (stop_state);
3941 break;
3942 } // switch(stop_state)
3943 } // else // if in All-stop-mode
3944 } // if (continue_packet)
3945 } // case eBroadcastBitAysncContinue
3946 break;
3947
3948 case eBroadcastBitAsyncThreadShouldExit:
3949 if (log)
3950 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
3951 done = true;
3952 break;
3953
3954 default:
3955 if (log)
3956 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3957 done = true;
3958 break;
3959 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003960 }
Pavel Labath50556852015-09-03 09:36:22 +00003961 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3962 {
3963 switch (event_type)
3964 {
3965 case Communication::eBroadcastBitReadThreadDidExit:
3966 process->SetExitStatus (-1, "lost connection");
3967 done = true;
3968 break;
3969
3970 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3971 {
3972 lldb_private::Event *event = event_sp.get();
3973 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3974 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3975 // Hand this over to the process to handle
3976 process->HandleNotifyPacket(notify);
3977 break;
3978 }
3979
3980 default:
3981 if (log)
3982 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3983 done = true;
3984 break;
3985 }
3986 }
3987 }
3988 else
3989 {
3990 if (log)
3991 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
3992 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003993 }
3994 }
3995
3996 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003997 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003998
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003999 return NULL;
4000}
4001
Greg Claytone996fd32011-03-08 22:40:15 +00004002//uint32_t
4003//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4004//{
4005// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
4006// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
4007// if (m_local_debugserver)
4008// {
4009// return Host::ListProcessesMatchingName (name, matches, pids);
4010// }
4011// else
4012// {
4013// // FIXME: Implement talking to the remote debugserver.
4014// return 0;
4015// }
4016//
4017//}
4018//
Jim Ingham1c823b42011-01-22 01:33:44 +00004019bool
4020ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004021 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00004022 lldb::user_id_t break_id,
4023 lldb::user_id_t break_loc_id)
4024{
4025 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
4026 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004027 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00004028 if (log)
4029 log->Printf("Hit New Thread Notification breakpoint.");
4030 return false;
4031}
4032
Eugene Zelenko0722f082015-10-24 01:28:05 +00004033
Jim Ingham1c823b42011-01-22 01:33:44 +00004034bool
4035ProcessGDBRemote::StartNoticingNewThreads()
4036{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004037 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00004038 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004039 {
Greg Clayton4116e932012-05-15 02:33:01 +00004040 if (log && log->GetVerbose())
4041 log->Printf("Enabled noticing new thread breakpoint.");
4042 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004043 }
Greg Clayton4116e932012-05-15 02:33:01 +00004044 else
Jim Ingham1c823b42011-01-22 01:33:44 +00004045 {
Zachary Turner7529df92015-09-01 20:02:29 +00004046 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Clayton4116e932012-05-15 02:33:01 +00004047 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004048 {
Zachary Turner7529df92015-09-01 20:02:29 +00004049 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget());
Greg Clayton4116e932012-05-15 02:33:01 +00004050 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004051 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004052 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00004053 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4054 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004055 }
4056 else
4057 {
4058 if (log)
4059 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00004060 }
4061 }
4062 }
Greg Clayton4116e932012-05-15 02:33:01 +00004063 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004064}
4065
4066bool
4067ProcessGDBRemote::StopNoticingNewThreads()
4068{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004069 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004070 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004071 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004072
4073 if (m_thread_create_bp_sp)
4074 m_thread_create_bp_sp->SetEnabled(false);
4075
Jim Ingham1c823b42011-01-22 01:33:44 +00004076 return true;
4077}
4078
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004079DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004080ProcessGDBRemote::GetDynamicLoader ()
4081{
4082 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004083 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004084 return m_dyld_ap.get();
4085}
Jim Ingham1c823b42011-01-22 01:33:44 +00004086
Jason Molendaa3329782014-03-29 18:54:20 +00004087Error
4088ProcessGDBRemote::SendEventData(const char *data)
4089{
4090 int return_value;
4091 bool was_supported;
4092
4093 Error error;
4094
4095 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4096 if (return_value != 0)
4097 {
4098 if (!was_supported)
4099 error.SetErrorString("Sending events is not supported for this process.");
4100 else
4101 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4102 }
4103 return error;
4104}
4105
Steve Pucci03904ac2014-03-04 23:18:46 +00004106const DataBufferSP
4107ProcessGDBRemote::GetAuxvData()
4108{
4109 DataBufferSP buf;
4110 if (m_gdb_comm.GetQXferAuxvReadSupported())
4111 {
4112 std::string response_string;
4113 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4114 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4115 }
4116 return buf;
4117}
4118
Jason Molenda705b1802014-06-13 02:37:02 +00004119StructuredData::ObjectSP
4120ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4121{
4122 StructuredData::ObjectSP object_sp;
4123
4124 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4125 {
4126 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4127 SystemRuntime *runtime = GetSystemRuntime();
4128 if (runtime)
4129 {
4130 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4131 }
4132 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4133
4134 StreamString packet;
4135 packet << "jThreadExtendedInfo:";
4136 args_dict->Dump (packet);
4137
4138 // FIXME the final character of a JSON dictionary, '}', is the escape
4139 // character in gdb-remote binary mode. lldb currently doesn't escape
4140 // these characters in its packet output -- so we add the quoted version
4141 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004142 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004143 packet << (char) (0x7d ^ 0x20);
4144
4145 StringExtractorGDBRemote response;
4146 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4147 {
4148 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4149 if (response_type == StringExtractorGDBRemote::eResponse)
4150 {
4151 if (!response.Empty())
4152 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004153 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4154 }
4155 }
4156 }
4157 }
4158 return object_sp;
4159}
4160
4161StructuredData::ObjectSP
4162ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4163{
4164 StructuredData::ObjectSP object_sp;
4165
4166 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4167 {
4168 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4169 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4170 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4171
4172 StreamString packet;
4173 packet << "jGetLoadedDynamicLibrariesInfos:";
4174 args_dict->Dump (packet);
4175
4176 // FIXME the final character of a JSON dictionary, '}', is the escape
4177 // character in gdb-remote binary mode. lldb currently doesn't escape
4178 // these characters in its packet output -- so we add the quoted version
4179 // of the } character here manually in case we talk to a debugserver which
4180 // un-escapes the characters at packet read time.
4181 packet << (char) (0x7d ^ 0x20);
4182
4183 StringExtractorGDBRemote response;
4184 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4185 {
4186 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4187 if (response_type == StringExtractorGDBRemote::eResponse)
4188 {
4189 if (!response.Empty())
4190 {
Jason Molenda705b1802014-06-13 02:37:02 +00004191 // The packet has already had the 0x7d xor quoting stripped out at the
4192 // GDBRemoteCommunication packet receive level.
4193 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4194 }
4195 }
4196 }
4197 }
4198 return object_sp;
4199}
4200
Eugene Zelenko0722f082015-10-24 01:28:05 +00004201
Jason Molenda6076bf42014-05-06 04:34:52 +00004202// Establish the largest memory read/write payloads we should use.
4203// If the remote stub has a max packet size, stay under that size.
4204//
4205// If the remote stub's max packet size is crazy large, use a
4206// reasonable largeish default.
4207//
4208// If the remote stub doesn't advertise a max packet size, use a
4209// conservative default.
4210
4211void
4212ProcessGDBRemote::GetMaxMemorySize()
4213{
4214 const uint64_t reasonable_largeish_default = 128 * 1024;
4215 const uint64_t conservative_default = 512;
4216
4217 if (m_max_memory_size == 0)
4218 {
4219 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4220 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4221 {
4222 // Save the stub's claimed maximum packet size
4223 m_remote_stub_max_memory_size = stub_max_size;
4224
4225 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004226 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004227 if (stub_max_size > reasonable_largeish_default)
4228 {
4229 stub_max_size = reasonable_largeish_default;
4230 }
4231
4232 m_max_memory_size = stub_max_size;
4233 }
4234 else
4235 {
4236 m_max_memory_size = conservative_default;
4237 }
4238 }
4239}
4240
4241void
4242ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4243{
4244 if (user_specified_max != 0)
4245 {
4246 GetMaxMemorySize ();
4247
4248 if (m_remote_stub_max_memory_size != 0)
4249 {
4250 if (m_remote_stub_max_memory_size < user_specified_max)
4251 {
4252 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4253 // as the remote stub says we can go.
4254 }
4255 else
4256 {
4257 m_max_memory_size = user_specified_max; // user's packet size is good
4258 }
4259 }
4260 else
4261 {
4262 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4263 }
4264 }
4265}
4266
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004267bool
4268ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4269 const ArchSpec& arch,
4270 ModuleSpec &module_spec)
4271{
4272 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4273
4274 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4275 {
4276 if (log)
4277 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4278 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4279 arch.GetTriple ().getTriple ().c_str ());
4280 return false;
4281 }
4282
4283 if (log)
4284 {
4285 StreamString stream;
4286 module_spec.Dump (stream);
4287 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4288 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4289 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4290 }
4291
4292 return true;
4293}
4294
Colin Rileyc3c95b22015-04-16 15:51:33 +00004295namespace {
4296
4297typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004298
4299typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004300struct RegisterSetInfo
4301{
4302 ConstString name;
4303};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004304
Greg Claytond04f0ed2015-05-26 18:00:51 +00004305typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4306
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004307struct GdbServerTargetInfo
4308{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004309 std::string arch;
4310 std::string osabi;
4311 stringVec includes;
4312 RegisterSetMap reg_set_map;
4313 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004314};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004315
Colin Rileyc3c95b22015-04-16 15:51:33 +00004316bool
Jason Molenda21586c82015-09-09 03:36:24 +00004317ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004318{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004319 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004320 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004321
Jason Molenda63bd0db2015-09-15 23:20:34 +00004322 uint32_t cur_reg_num = 0;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004323 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004324
Jason Molenda63bd0db2015-09-15 23:20:34 +00004325 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 +00004326 std::string gdb_group;
4327 std::string gdb_type;
4328 ConstString reg_name;
4329 ConstString alt_name;
4330 ConstString set_name;
4331 std::vector<uint32_t> value_regs;
4332 std::vector<uint32_t> invalidate_regs;
4333 bool encoding_set = false;
4334 bool format_set = false;
4335 RegisterInfo reg_info = { NULL, // Name
4336 NULL, // Alt name
4337 0, // byte size
4338 reg_offset, // offset
4339 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +00004340 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004341 {
Jason Molendabf67a302015-09-01 05:17:01 +00004342 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004343 LLDB_INVALID_REGNUM, // DWARF reg num
4344 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +00004345 cur_reg_num, // process plugin reg num
4346 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004347 },
4348 NULL,
4349 NULL
4350 };
4351
Jason Molenda63bd0db2015-09-15 23:20:34 +00004352 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 +00004353 if (name == "name")
4354 {
4355 reg_name.SetString(value);
4356 }
4357 else if (name == "bitsize")
4358 {
4359 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4360 }
4361 else if (name == "type")
4362 {
4363 gdb_type = value.str();
4364 }
4365 else if (name == "group")
4366 {
4367 gdb_group = value.str();
4368 }
4369 else if (name == "regnum")
4370 {
4371 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4372 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004373 {
Jason Molenda63bd0db2015-09-15 23:20:34 +00004374 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004375 }
4376 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004377 else if (name == "offset")
4378 {
4379 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4380 }
4381 else if (name == "altname")
4382 {
4383 alt_name.SetString(value);
4384 }
4385 else if (name == "encoding")
4386 {
4387 encoding_set = true;
4388 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4389 }
4390 else if (name == "format")
4391 {
4392 format_set = true;
4393 Format format = eFormatInvalid;
4394 if (Args::StringToFormat (value.data(), format, NULL).Success())
4395 reg_info.format = format;
4396 else if (value == "vector-sint8")
4397 reg_info.format = eFormatVectorOfSInt8;
4398 else if (value == "vector-uint8")
4399 reg_info.format = eFormatVectorOfUInt8;
4400 else if (value == "vector-sint16")
4401 reg_info.format = eFormatVectorOfSInt16;
4402 else if (value == "vector-uint16")
4403 reg_info.format = eFormatVectorOfUInt16;
4404 else if (value == "vector-sint32")
4405 reg_info.format = eFormatVectorOfSInt32;
4406 else if (value == "vector-uint32")
4407 reg_info.format = eFormatVectorOfUInt32;
4408 else if (value == "vector-float32")
4409 reg_info.format = eFormatVectorOfFloat32;
4410 else if (value == "vector-uint128")
4411 reg_info.format = eFormatVectorOfUInt128;
4412 }
4413 else if (name == "group_id")
4414 {
4415 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4416 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4417 if (pos != target_info.reg_set_map.end())
4418 set_name = pos->second.name;
4419 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004420 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004421 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004422 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004423 }
4424 else if (name == "dwarf_regnum")
4425 {
4426 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4427 }
4428 else if (name == "generic")
4429 {
4430 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4431 }
4432 else if (name == "value_regnums")
4433 {
4434 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4435 }
4436 else if (name == "invalidate_regnums")
4437 {
4438 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4439 }
4440 else
4441 {
4442 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4443 }
4444 return true; // Keep iterating through all attributes
4445 });
4446
4447 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004448 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004449 if (gdb_type.find("int") == 0)
4450 {
4451 reg_info.format = eFormatHex;
4452 reg_info.encoding = eEncodingUint;
4453 }
4454 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4455 {
4456 reg_info.format = eFormatAddressInfo;
4457 reg_info.encoding = eEncodingUint;
4458 }
4459 else if (gdb_type == "i387_ext" || gdb_type == "float")
4460 {
4461 reg_info.format = eFormatFloat;
4462 reg_info.encoding = eEncodingIEEE754;
4463 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004464 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004465
4466 // Only update the register set name if we didn't get a "reg_set" attribute.
4467 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4468 if (!set_name && !gdb_group.empty())
4469 set_name.SetCString(gdb_group.c_str());
4470
4471 reg_info.byte_offset = reg_offset;
4472 assert (reg_info.byte_size != 0);
4473 reg_offset += reg_info.byte_size;
4474 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004475 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004476 value_regs.push_back(LLDB_INVALID_REGNUM);
4477 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004478 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004479 if (!invalidate_regs.empty())
4480 {
4481 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4482 reg_info.invalidate_regs = invalidate_regs.data();
4483 }
4484
Jason Molenda63bd0db2015-09-15 23:20:34 +00004485 ++cur_reg_num;
Jason Molenda21586c82015-09-09 03:36:24 +00004486 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004487 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4488
4489 return true; // Keep iterating through all "reg" elements
4490 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004491 return true;
4492}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004493
Eugene Zelenko0722f082015-10-24 01:28:05 +00004494} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004495
Colin Rileyc3c95b22015-04-16 15:51:33 +00004496
4497// query the target of gdb-remote for extended target information
4498// return: 'true' on success
4499// 'false' on failure
4500bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004501ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004502{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004503 // Make sure LLDB has an XML parser it can use first
4504 if (!XMLDocument::XMLEnabled())
4505 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004506
4507 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004508
4509 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004510
4511 // check that we have extended feature read support
4512 if ( !comm.GetQXferFeaturesReadSupported( ) )
4513 return false;
4514
4515 // request the target xml file
4516 std::string raw;
4517 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004518 if (!comm.ReadExtFeature(ConstString("features"),
4519 ConstString("target.xml"),
4520 raw,
4521 lldberr))
4522 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004523 return false;
4524 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00004525
Colin Rileyc3c95b22015-04-16 15:51:33 +00004526
Greg Claytond04f0ed2015-05-26 18:00:51 +00004527 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004528
Greg Claytond04f0ed2015-05-26 18:00:51 +00004529 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004530 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004531 GdbServerTargetInfo target_info;
4532
4533 XMLNode target_node = xml_document.GetRootElement("target");
4534 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004535 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004536 XMLNode feature_node;
4537 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4538 {
4539 llvm::StringRef name = node.GetName();
4540 if (name == "architecture")
4541 {
4542 node.GetElementText(target_info.arch);
4543 }
4544 else if (name == "osabi")
4545 {
4546 node.GetElementText(target_info.osabi);
4547 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004548 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004549 {
4550 llvm::StringRef href = node.GetAttributeValue("href");
4551 if (!href.empty())
4552 target_info.includes.push_back(href.str());
4553 }
4554 else if (name == "feature")
4555 {
4556 feature_node = node;
4557 }
4558 else if (name == "groups")
4559 {
4560 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4561 uint32_t set_id = UINT32_MAX;
4562 RegisterSetInfo set_info;
4563
4564 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4565 if (name == "id")
4566 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4567 if (name == "name")
4568 set_info.name = ConstString(value);
4569 return true; // Keep iterating through all attributes
4570 });
4571
4572 if (set_id != UINT32_MAX)
4573 target_info.reg_set_map[set_id] = set_info;
4574 return true; // Keep iterating through all "group" elements
4575 });
4576 }
4577 return true; // Keep iterating through all children of the target_node
4578 });
4579
4580 if (feature_node)
4581 {
Jason Molenda21586c82015-09-09 03:36:24 +00004582 ParseRegisters(feature_node, target_info, this->m_register_info, GetABI());
Greg Claytond04f0ed2015-05-26 18:00:51 +00004583 }
4584
4585 for (const auto &include : target_info.includes)
4586 {
4587 // request register file
4588 std::string xml_data;
4589 if (!comm.ReadExtFeature(ConstString("features"),
4590 ConstString(include),
4591 xml_data,
4592 lldberr))
4593 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004594
Greg Claytond04f0ed2015-05-26 18:00:51 +00004595 XMLDocument include_xml_document;
4596 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4597 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4598 if (include_feature_node)
4599 {
Jason Molenda21586c82015-09-09 03:36:24 +00004600 ParseRegisters(include_feature_node, target_info, this->m_register_info, GetABI());
Greg Claytond04f0ed2015-05-26 18:00:51 +00004601 }
4602 }
4603 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004604 }
4605 }
4606
Greg Claytond04f0ed2015-05-26 18:00:51 +00004607 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004608}
4609
Aidan Doddsc0c83852015-05-08 09:36:31 +00004610Error
4611ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4612{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004613 // Make sure LLDB has an XML parser it can use first
4614 if (!XMLDocument::XMLEnabled())
4615 return Error (0, ErrorType::eErrorTypeGeneric);
4616
Aidan Doddsc0c83852015-05-08 09:36:31 +00004617 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4618 if (log)
4619 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4620
Aidan Doddsc0c83852015-05-08 09:36:31 +00004621 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004622
4623 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004624 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4625 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004626
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004627 // request the loaded library list
4628 std::string raw;
4629 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004630
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004631 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4632 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004633
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004634 // parse the xml file in memory
4635 if (log)
4636 log->Printf ("parsing: %s", raw.c_str());
4637 XMLDocument doc;
4638
4639 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4640 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004641
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004642 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4643 if (!root_element)
4644 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004645
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004646 // main link map structure
4647 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4648 if (!main_lm.empty())
4649 {
4650 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4651 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004652
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004653 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004654
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004655 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004656
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004657 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004658
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004659 if (name == "name")
4660 module.set_name (value.str());
4661 else if (name == "lm")
4662 {
4663 // the address of the link_map struct.
4664 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4665 }
4666 else if (name == "l_addr")
4667 {
4668 // the displacement as read from the field 'l_addr' of the link_map struct.
4669 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004670 // base address is always a displacement, not an absolute value.
4671 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004672 }
4673 else if (name == "l_ld")
4674 {
4675 // the memory address of the libraries PT_DYAMIC section.
4676 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4677 }
4678
4679 return true; // Keep iterating over all properties of "library"
4680 });
4681
4682 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004683 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004684 std::string name;
4685 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004686 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004687
4688 module.get_name (name);
4689 module.get_link_map (lm);
4690 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004691 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004692 module.get_dynamic (ld);
4693
Stephane Sezerc6845a02015-08-20 22:07:48 +00004694 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 +00004695 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004696
4697 list.add (module);
4698 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004699 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004700
4701 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004702 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4703 } else if (comm.GetQXferLibrariesReadSupported ()) {
4704 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004705
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004706 // request the loaded library list
4707 std::string raw;
4708 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004709
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004710 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4711 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004712
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004713 if (log)
4714 log->Printf ("parsing: %s", raw.c_str());
4715 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004716
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004717 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4718 return Error (0, ErrorType::eErrorTypeGeneric);
4719
4720 XMLNode root_element = doc.GetRootElement("library-list");
4721 if (!root_element)
4722 return Error();
4723
4724 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4725 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4726
4727 llvm::StringRef name = library.GetAttributeValue("name");
4728 module.set_name(name.str());
4729
4730 // The base address of a given library will be the address of its
4731 // first section. Most remotes send only one section for Windows
4732 // targets for example.
4733 const XMLNode &section = library.FindFirstChildElementWithName("section");
4734 llvm::StringRef address = section.GetAttributeValue("address");
4735 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004736 // These addresses are absolute values.
4737 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004738
4739 if (log)
4740 {
4741 std::string name;
4742 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004743 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004744 module.get_name (name);
4745 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004746 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004747
Stephane Sezerc6845a02015-08-20 22:07:48 +00004748 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 +00004749 }
4750
4751 list.add (module);
4752 return true; // Keep iterating over all "library" elements in the root node
4753 });
4754
4755 if (log)
4756 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4757 } else {
4758 return Error (0, ErrorType::eErrorTypeGeneric);
4759 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004760
4761 return Error();
4762}
4763
Aidan Doddsc0c83852015-05-08 09:36:31 +00004764lldb::ModuleSP
Stephane Sezerc6845a02015-08-20 22:07:48 +00004765ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004766{
4767 Target &target = m_process->GetTarget();
4768 ModuleList &modules = target.GetImages();
4769 ModuleSP module_sp;
4770
4771 bool changed = false;
4772
4773 ModuleSpec module_spec (file, target.GetArchitecture());
4774 if ((module_sp = modules.FindFirstModule (module_spec)))
4775 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004776 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004777 }
4778 else if ((module_sp = target.GetSharedModule (module_spec)))
4779 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004780 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004781 }
4782
4783 return module_sp;
4784}
4785
4786size_t
4787ProcessGDBRemote::LoadModules ()
4788{
4789 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4790
4791 // request a list of loaded libraries from GDBServer
4792 GDBLoadedModuleInfoList module_list;
4793 if (GetLoadedModuleList (module_list).Fail())
4794 return 0;
4795
4796 // get a list of all the modules
4797 ModuleList new_modules;
4798
4799 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4800 {
4801 std::string mod_name;
4802 lldb::addr_t mod_base;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004803 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004804
4805 bool valid = true;
4806 valid &= modInfo.get_name (mod_name);
4807 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004808 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004809 if (!valid)
4810 continue;
4811
4812 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004813 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004814 if (marker == std::string::npos)
4815 marker = 0;
4816 else
4817 marker += 1;
4818
4819 FileSpec file (mod_name.c_str()+marker, true);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004820 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base, mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004821
4822 if (module_sp.get())
4823 new_modules.Append (module_sp);
4824 }
4825
4826 if (new_modules.GetSize() > 0)
4827 {
Zachary Turner7529df92015-09-01 20:02:29 +00004828 Target &target = GetTarget();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004829
4830 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4831 {
4832 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4833 if (!obj)
4834 return true;
4835
4836 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4837 return true;
4838
4839 lldb::ModuleSP module_copy_sp = module_sp;
4840 target.SetExecutableModule (module_copy_sp, false);
4841 return false;
4842 });
4843
4844 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4845 loaded_modules.AppendIfNeeded (new_modules);
4846 m_process->GetTarget().ModulesDidLoad (new_modules);
4847 }
4848
4849 return new_modules.GetSize();
4850}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004851
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004852Error
4853ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4854{
4855 is_loaded = false;
4856 load_addr = LLDB_INVALID_ADDRESS;
4857
4858 std::string file_path = file.GetPath(false);
4859 if (file_path.empty ())
4860 return Error("Empty file name specified");
4861
4862 StreamString packet;
4863 packet.PutCString("qFileLoadAddress:");
4864 packet.PutCStringAsRawHex8(file_path.c_str());
4865
4866 StringExtractorGDBRemote response;
4867 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4868 return Error("Sending qFileLoadAddress packet failed");
4869
4870 if (response.IsErrorResponse())
4871 {
4872 if (response.GetError() == 1)
4873 {
4874 // The file is not loaded into the inferior
4875 is_loaded = false;
4876 load_addr = LLDB_INVALID_ADDRESS;
4877 return Error();
4878 }
4879
4880 return Error("Fetching file load address from remote server returned an error");
4881 }
4882
4883 if (response.IsNormalResponse())
4884 {
4885 is_loaded = true;
4886 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4887 return Error();
4888 }
4889
4890 return Error("Unknown error happened during sending the load address packet");
4891}
4892
Eugene Zelenko0722f082015-10-24 01:28:05 +00004893
Greg Clayton0b90be12015-06-23 21:27:50 +00004894void
4895ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4896{
4897 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4898 Process::ModulesDidLoad (module_list);
4899
4900 // After loading shared libraries, we can ask our remote GDB server if
4901 // it needs any symbols.
4902 m_gdb_comm.ServeSymbolLookups(this);
4903}
4904
Eugene Zelenko0722f082015-10-24 01:28:05 +00004905
Greg Claytone034a042015-05-21 20:52:06 +00004906class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4907{
4908public:
4909 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4910 CommandObjectParsed (interpreter,
4911 "process plugin packet speed-test",
4912 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4913 NULL),
4914 m_option_group (interpreter),
4915 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),
4916 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),
4917 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),
4918 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4919 {
4920 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4921 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4922 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4923 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4924 m_option_group.Finalize();
4925 }
4926
Eugene Zelenko0722f082015-10-24 01:28:05 +00004927 ~CommandObjectProcessGDBRemoteSpeedTest ()
4928 {
4929 }
4930
Greg Claytone034a042015-05-21 20:52:06 +00004931
4932 Options *
4933 GetOptions () override
4934 {
4935 return &m_option_group;
4936 }
4937
4938 bool
4939 DoExecute (Args& command, CommandReturnObject &result) override
4940 {
4941 const size_t argc = command.GetArgumentCount();
4942 if (argc == 0)
4943 {
4944 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4945 if (process)
4946 {
4947 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4948 result.SetImmediateOutputStream (output_stream_sp);
4949
4950 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4951 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4952 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4953 const bool json = m_json.GetOptionValue().GetCurrentValue();
4954 if (output_stream_sp)
4955 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4956 else
4957 {
4958 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4959 }
4960 result.SetStatus (eReturnStatusSuccessFinishResult);
4961 return true;
4962 }
4963 }
4964 else
4965 {
4966 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4967 }
4968 result.SetStatus (eReturnStatusFailed);
4969 return false;
4970 }
4971protected:
4972 OptionGroupOptions m_option_group;
4973 OptionGroupUInt64 m_num_packets;
4974 OptionGroupUInt64 m_max_send;
4975 OptionGroupUInt64 m_max_recv;
4976 OptionGroupBoolean m_json;
Eugene Zelenko0722f082015-10-24 01:28:05 +00004977
Greg Claytone034a042015-05-21 20:52:06 +00004978};
4979
Greg Clayton02686b82012-10-15 22:42:16 +00004980class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004981{
Eugene Zelenko0722f082015-10-24 01:28:05 +00004982private:
4983
Greg Clayton998255b2012-10-13 02:07:45 +00004984public:
Greg Clayton02686b82012-10-15 22:42:16 +00004985 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004986 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004987 "process plugin packet history",
4988 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004989 NULL)
4990 {
4991 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00004992
4993 ~CommandObjectProcessGDBRemotePacketHistory ()
4994 {
4995 }
4996
Greg Clayton998255b2012-10-13 02:07:45 +00004997 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004998 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004999 {
Greg Clayton02686b82012-10-15 22:42:16 +00005000 const size_t argc = command.GetArgumentCount();
5001 if (argc == 0)
5002 {
5003 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5004 if (process)
5005 {
5006 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5007 result.SetStatus (eReturnStatusSuccessFinishResult);
5008 return true;
5009 }
5010 }
5011 else
5012 {
5013 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5014 }
5015 result.SetStatus (eReturnStatusFailed);
5016 return false;
5017 }
5018};
5019
Jason Molenda6076bf42014-05-06 04:34:52 +00005020class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
5021{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005022private:
5023
Jason Molenda6076bf42014-05-06 04:34:52 +00005024public:
5025 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
5026 CommandObjectParsed (interpreter,
5027 "process plugin packet xfer-size",
5028 "Maximum size that lldb will try to read/write one one chunk.",
5029 NULL)
5030 {
5031 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00005032
5033 ~CommandObjectProcessGDBRemotePacketXferSize ()
5034 {
5035 }
5036
Jason Molenda6076bf42014-05-06 04:34:52 +00005037 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005038 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00005039 {
5040 const size_t argc = command.GetArgumentCount();
5041 if (argc == 0)
5042 {
5043 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
5044 result.SetStatus (eReturnStatusFailed);
5045 return false;
5046 }
5047
5048 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5049 if (process)
5050 {
5051 const char *packet_size = command.GetArgumentAtIndex(0);
5052 errno = 0;
5053 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5054 if (errno == 0 && user_specified_max != 0)
5055 {
5056 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5057 result.SetStatus (eReturnStatusSuccessFinishResult);
5058 return true;
5059 }
5060 }
5061 result.SetStatus (eReturnStatusFailed);
5062 return false;
5063 }
5064};
5065
Eugene Zelenko0722f082015-10-24 01:28:05 +00005066
Greg Clayton02686b82012-10-15 22:42:16 +00005067class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5068{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005069private:
5070
Greg Clayton02686b82012-10-15 22:42:16 +00005071public:
5072 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5073 CommandObjectParsed (interpreter,
5074 "process plugin packet send",
5075 "Send a custom packet through the GDB remote protocol and print the answer. "
5076 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5077 NULL)
5078 {
5079 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00005080
5081 ~CommandObjectProcessGDBRemotePacketSend ()
5082 {
5083 }
5084
Greg Clayton02686b82012-10-15 22:42:16 +00005085 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005086 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005087 {
5088 const size_t argc = command.GetArgumentCount();
5089 if (argc == 0)
5090 {
5091 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5092 result.SetStatus (eReturnStatusFailed);
5093 return false;
5094 }
5095
5096 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5097 if (process)
5098 {
Han Ming Ong84145852012-11-26 20:42:03 +00005099 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005100 {
Han Ming Ong84145852012-11-26 20:42:03 +00005101 const char *packet_cstr = command.GetArgumentAtIndex(0);
5102 bool send_async = true;
5103 StringExtractorGDBRemote response;
5104 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5105 result.SetStatus (eReturnStatusSuccessFinishResult);
5106 Stream &output_strm = result.GetOutputStream();
5107 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005108 std::string &response_str = response.GetStringRef();
5109
Han Ming Ong399289e2013-06-21 19:56:59 +00005110 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005111 {
5112 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5113 }
5114
Han Ming Ong84145852012-11-26 20:42:03 +00005115 if (response_str.empty())
5116 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5117 else
5118 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005119 }
Greg Clayton02686b82012-10-15 22:42:16 +00005120 }
Greg Clayton998255b2012-10-13 02:07:45 +00005121 return true;
5122 }
5123};
5124
Greg Claytonba4a0a52013-02-01 23:03:47 +00005125class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5126{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005127private:
5128
Greg Claytonba4a0a52013-02-01 23:03:47 +00005129public:
5130 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5131 CommandObjectRaw (interpreter,
5132 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005133 "Send a qRcmd packet through the GDB remote protocol and print the response."
5134 "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 +00005135 NULL)
5136 {
5137 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00005138
5139 ~CommandObjectProcessGDBRemotePacketMonitor ()
5140 {
5141 }
5142
Greg Claytonba4a0a52013-02-01 23:03:47 +00005143 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005144 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005145 {
5146 if (command == NULL || command[0] == '\0')
5147 {
5148 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5149 result.SetStatus (eReturnStatusFailed);
5150 return false;
5151 }
5152
5153 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5154 if (process)
5155 {
5156 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005157 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005158 packet.PutBytesAsRawHex8(command, strlen(command));
5159 const char *packet_cstr = packet.GetString().c_str();
5160
5161 bool send_async = true;
5162 StringExtractorGDBRemote response;
5163 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5164 result.SetStatus (eReturnStatusSuccessFinishResult);
5165 Stream &output_strm = result.GetOutputStream();
5166 output_strm.Printf (" packet: %s\n", packet_cstr);
5167 const std::string &response_str = response.GetStringRef();
5168
5169 if (response_str.empty())
5170 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5171 else
5172 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5173 }
5174 return true;
5175 }
5176};
5177
Greg Clayton02686b82012-10-15 22:42:16 +00005178class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5179{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005180private:
5181
Greg Clayton02686b82012-10-15 22:42:16 +00005182public:
5183 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5184 CommandObjectMultiword (interpreter,
5185 "process plugin packet",
5186 "Commands that deal with GDB remote packets.",
5187 NULL)
5188 {
5189 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5190 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005191 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005192 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005193 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005194 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00005195
5196 ~CommandObjectProcessGDBRemotePacket ()
5197 {
5198 }
Greg Clayton02686b82012-10-15 22:42:16 +00005199};
Greg Clayton998255b2012-10-13 02:07:45 +00005200
5201class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5202{
5203public:
5204 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5205 CommandObjectMultiword (interpreter,
5206 "process plugin",
5207 "A set of commands for operating on a ProcessGDBRemote process.",
5208 "process plugin <subcommand> [<subcommand-options>]")
5209 {
5210 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5211 }
5212
Eugene Zelenko0722f082015-10-24 01:28:05 +00005213 ~CommandObjectMultiwordProcessGDBRemote ()
5214 {
5215 }
Greg Clayton998255b2012-10-13 02:07:45 +00005216};
5217
Greg Clayton998255b2012-10-13 02:07:45 +00005218CommandObject *
5219ProcessGDBRemote::GetPluginCommandObject()
5220{
5221 if (!m_command_sp)
5222 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5223 return m_command_sp.get();
5224}