blob: 5b2d084a0d36306c74649b6b854e9196612145f9 [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>
Kate Stoneb9c1b512016-09-06 20:57:50 +000017#include <sys/mman.h> // for mmap
Greg Claytonc6c420f2016-08-12 16:46:18 +000018#include <sys/socket.h>
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000019#include <unistd.h>
Zachary Turnerbd22bf22016-08-12 16:52:31 +000020#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000022#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000023#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024
25// C++ Includes
26#include <algorithm>
27#include <map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000028#include <mutex>
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000029#include <sstream>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030
Johnny Chen01a67862011-10-14 00:42:25 +000031#include "lldb/Breakpoint/Watchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000034#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Core/PluginManager.h"
36#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000037#include "lldb/Core/StreamFile.h"
Greg Clayton70b57652011-05-15 01:25:55 +000038#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000039#include "lldb/DataFormatters/FormatManager.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000040#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000041#include "lldb/Host/FileSystem.h"
Zachary Turner39de3112014-09-09 20:54:56 +000042#include "lldb/Host/HostThread.h"
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000043#include "lldb/Host/PosixApi.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000044#include "lldb/Host/PseudoTerminal.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"
Greg Claytond04f0ed2015-05-26 18:00:51 +000048#include "lldb/Host/XML.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000049#include "lldb/Interpreter/Args.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"
Greg Claytone034a042015-05-21 20:52:06 +000054#include "lldb/Interpreter/OptionGroupBoolean.h"
55#include "lldb/Interpreter/OptionGroupUInt64.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000056#include "lldb/Interpreter/OptionValueProperties.h"
57#include "lldb/Interpreter/Options.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"
Kate Stoneb9c1b512016-09-06 20:57:50 +000062#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000063#include "lldb/Target/Target.h"
64#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000065#include "lldb/Target/ThreadPlanCallFunction.h"
Greg Claytonc6c420f2016-08-12 16:46:18 +000066#include "lldb/Utility/CleanUp.h"
Zachary Turner5713a052017-03-22 18:40:07 +000067#include "lldb/Utility/FileSpec.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000068#include "lldb/Utility/StreamString.h"
Pavel Labath38d06322017-06-29 14:32:17 +000069#include "lldb/Utility/Timer.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070
Eugene Zelenko0722f082015-10-24 01:28:05 +000071// Project includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000072#include "GDBRemoteRegisterContext.h"
73#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000074#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000075#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000076#include "Plugins/Process/Utility/StopInfoMachException.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000077#include "ProcessGDBRemote.h"
78#include "ProcessGDBRemoteLog.h"
79#include "ThreadGDBRemote.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000080#include "Utility/StringExtractorGDBRemote.h"
81#include "lldb/Host/Host.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000082
Zachary Turner54695a32016-08-29 19:58:14 +000083#include "llvm/ADT/StringSwitch.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000084#include "llvm/Support/Threading.h"
Eugene Zemtsov7993cc52017-03-07 21:34:40 +000085#include "llvm/Support/raw_ostream.h"
Zachary Turner54695a32016-08-29 19:58:14 +000086
Kate Stoneb9c1b512016-09-06 20:57:50 +000087#define DEBUGSERVER_BASENAME "debugserver"
Tamas Berghammerdb264a62015-03-31 09:52:22 +000088using namespace lldb;
89using namespace lldb_private;
90using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000091
Kate Stoneb9c1b512016-09-06 20:57:50 +000092namespace lldb {
93// Provide a function that can easily dump the packet history if we know a
94// ProcessGDBRemote * value (which we can get from logs or from debugging).
95// We need the function in the lldb namespace so it makes it into the final
96// executable since the LLDB shared library only exports stuff in the lldb
97// namespace. This allows you to attach with a debugger and call this
98// function and get the packet history dumped to a file.
99void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
100 StreamFile strm;
Zachary Turner97206d52017-05-12 04:51:55 +0000101 Status error(strm.GetFile().Open(path, File::eOpenOptionWrite |
102 File::eOpenOptionCanCreate));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103 if (error.Success())
104 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(strm);
105}
Eugene Zelenko0722f082015-10-24 01:28:05 +0000106}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000107
Greg Clayton7f982402013-07-15 22:54:20 +0000108namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000109
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110static PropertyDefinition g_properties[] = {
111 {"packet-timeout", OptionValue::eTypeUInt64, true, 1, NULL, NULL,
112 "Specify the default packet timeout in seconds."},
113 {"target-definition-file", OptionValue::eTypeFileSpec, true, 0, NULL, NULL,
114 "The file that provides the description for remote target registers."},
115 {NULL, OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL}};
Ed Maste81b4c5f2016-01-04 01:43:47 +0000116
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117enum { ePropertyPacketTimeout, ePropertyTargetDefinitionFile };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000118
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119class PluginProperties : public Properties {
120public:
121 static ConstString GetSettingName() {
122 return ProcessGDBRemote::GetPluginNameStatic();
123 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 PluginProperties() : Properties() {
126 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
127 m_collection_sp->Initialize(g_properties);
128 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000129
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130 virtual ~PluginProperties() {}
Ed Maste81b4c5f2016-01-04 01:43:47 +0000131
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 uint64_t GetPacketTimeout() {
133 const uint32_t idx = ePropertyPacketTimeout;
134 return m_collection_sp->GetPropertyAtIndexAsUInt64(
135 NULL, idx, g_properties[idx].default_uint_value);
136 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000137
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138 bool SetPacketTimeout(uint64_t timeout) {
139 const uint32_t idx = ePropertyPacketTimeout;
140 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
141 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000142
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 FileSpec GetTargetDefinitionFile() const {
144 const uint32_t idx = ePropertyTargetDefinitionFile;
145 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
146 }
147};
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
152 static ProcessKDPPropertiesSP g_settings_sp;
153 if (!g_settings_sp)
154 g_settings_sp.reset(new PluginProperties());
155 return g_settings_sp;
156}
Ed Maste81b4c5f2016-01-04 01:43:47 +0000157
Eugene Zelenko0722f082015-10-24 01:28:05 +0000158} // anonymous namespace end
Greg Clayton7f982402013-07-15 22:54:20 +0000159
Greg Claytonfda4fab2014-01-10 22:24:11 +0000160// TODO Randomly assigning a port is unsafe. We should get an unused
161// ephemeral port from the kernel and make sure we reserve it before passing
162// it to debugserver.
163
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164#if defined(__APPLE__)
165#define LOW_PORT (IPPORT_RESERVED)
166#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
Greg Claytonfda4fab2014-01-10 22:24:11 +0000167#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168#define LOW_PORT (1024u)
169#define HIGH_PORT (49151u)
Greg Claytonfda4fab2014-01-10 22:24:11 +0000170#endif
171
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172#if defined(__APPLE__) && \
173 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000174static bool rand_initialized = false;
175
Kate Stoneb9c1b512016-09-06 20:57:50 +0000176static inline uint16_t get_random_port() {
177 if (!rand_initialized) {
178 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180 rand_initialized = true;
181 srand(seed);
182 }
183 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Greg Claytonfda4fab2014-01-10 22:24:11 +0000184}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000185#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000186
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187ConstString ProcessGDBRemote::GetPluginNameStatic() {
188 static ConstString g_name("gdb-remote");
189 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000190}
191
Kate Stoneb9c1b512016-09-06 20:57:50 +0000192const char *ProcessGDBRemote::GetPluginDescriptionStatic() {
193 return "GDB Remote protocol based debugging plug-in.";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000194}
195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196void ProcessGDBRemote::Terminate() {
197 PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000198}
199
Greg Claytonc3776bf2012-02-09 06:16:32 +0000200lldb::ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
202 ListenerSP listener_sp,
203 const FileSpec *crash_file_path) {
204 lldb::ProcessSP process_sp;
205 if (crash_file_path == NULL)
206 process_sp.reset(new ProcessGDBRemote(target_sp, listener_sp));
207 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000208}
209
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
211 bool plugin_specified_by_name) {
212 if (plugin_specified_by_name)
Jim Ingham5aee1622010-08-09 23:31:02 +0000213 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214
215 // For now we are just making sure the file exists for a given module
216 Module *exe_module = target_sp->GetExecutableModulePointer();
217 if (exe_module) {
218 ObjectFile *exe_objfile = exe_module->GetObjectFile();
219 // We can't debug core files...
220 switch (exe_objfile->GetType()) {
221 case ObjectFile::eTypeInvalid:
222 case ObjectFile::eTypeCoreFile:
223 case ObjectFile::eTypeDebugInfo:
224 case ObjectFile::eTypeObjectFile:
225 case ObjectFile::eTypeSharedLibrary:
226 case ObjectFile::eTypeStubLibrary:
227 case ObjectFile::eTypeJIT:
228 return false;
229 case ObjectFile::eTypeExecutable:
230 case ObjectFile::eTypeDynamicLinker:
231 case ObjectFile::eTypeUnknown:
232 break;
233 }
234 return exe_module->GetFileSpec().Exists();
235 }
236 // However, if there is no executable module, we return true since we might be
237 // preparing to attach.
238 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000239}
240
Eugene Zelenko0722f082015-10-24 01:28:05 +0000241//----------------------------------------------------------------------
242// ProcessGDBRemote constructor
243//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
245 ListenerSP listener_sp)
Pavel Labatha9640122017-11-03 22:12:50 +0000246 : Process(target_sp, listener_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247 m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_last_stop_packet_mutex(),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000248 m_register_info(),
249 m_async_broadcaster(NULL, "lldb.process.gdb-remote.async-broadcaster"),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 m_async_listener_sp(
251 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
252 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
253 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
254 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
255 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
256 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
257 m_waiting_for_attach(false), m_destroy_tried_resuming(false),
258 m_command_sp(), m_breakpoint_pc_offset(0),
259 m_initial_tid(LLDB_INVALID_THREAD_ID) {
260 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
261 "async thread should exit");
262 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
263 "async thread continue");
264 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
265 "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000266
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
Pavel Labath50556852015-09-03 09:36:22 +0000268
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269 const uint32_t async_event_mask =
270 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
Pavel Labath50556852015-09-03 09:36:22 +0000271
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 if (m_async_listener_sp->StartListeningForEvents(
273 &m_async_broadcaster, async_event_mask) != async_event_mask) {
274 if (log)
275 log->Printf("ProcessGDBRemote::%s failed to listen for "
276 "m_async_broadcaster events",
277 __FUNCTION__);
278 }
Pavel Labath50556852015-09-03 09:36:22 +0000279
Kate Stoneb9c1b512016-09-06 20:57:50 +0000280 const uint32_t gdb_event_mask =
281 Communication::eBroadcastBitReadThreadDidExit |
282 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
283 if (m_async_listener_sp->StartListeningForEvents(
284 &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
285 if (log)
286 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
287 __FUNCTION__);
288 }
Pavel Labath50556852015-09-03 09:36:22 +0000289
Kate Stoneb9c1b512016-09-06 20:57:50 +0000290 const uint64_t timeout_seconds =
291 GetGlobalPluginProperties()->GetPacketTimeout();
292 if (timeout_seconds > 0)
Pavel Labath3aa04912016-10-31 17:19:42 +0000293 m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000294}
295
Eugene Zelenko0722f082015-10-24 01:28:05 +0000296//----------------------------------------------------------------------
297// Destructor
298//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299ProcessGDBRemote::~ProcessGDBRemote() {
300 // m_mach_process.UnregisterNotificationCallbacks (this);
301 Clear();
302 // We need to call finalize on the process before destroying ourselves
303 // to make sure all of the broadcaster cleanup goes as planned. If we
304 // destruct this class, then Process::~Process() might have problems
305 // trying to fully destroy the broadcaster.
306 Finalize();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000307
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308 // The general Finalize is going to try to destroy the process and that SHOULD
309 // shut down the async thread. However, if we don't kill it it will get
310 // stranded and
311 // its connection will go away so when it wakes up it will crash. So kill it
312 // for sure here.
313 StopAsyncThread();
314 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000315}
316
317//----------------------------------------------------------------------
318// PluginInterface
319//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000321
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000323
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324bool ProcessGDBRemote::ParsePythonTargetDefinition(
325 const FileSpec &target_definition_fspec) {
326 ScriptInterpreter *interpreter =
327 GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Zachary Turner97206d52017-05-12 04:51:55 +0000328 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 StructuredData::ObjectSP module_object_sp(
330 interpreter->LoadPluginModule(target_definition_fspec, error));
331 if (module_object_sp) {
332 StructuredData::DictionarySP target_definition_sp(
333 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
334 "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000335
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 if (target_definition_sp) {
337 StructuredData::ObjectSP target_object(
338 target_definition_sp->GetValueForKey("host-info"));
339 if (target_object) {
340 if (auto host_info_dict = target_object->GetAsDictionary()) {
341 StructuredData::ObjectSP triple_value =
342 host_info_dict->GetValueForKey("triple");
343 if (auto triple_string_value = triple_value->GetAsString()) {
344 std::string triple_string = triple_string_value->GetValue();
345 ArchSpec host_arch(triple_string.c_str());
346 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
347 GetTarget().SetArchitecture(host_arch);
Greg Clayton312bcbe2013-10-17 01:10:23 +0000348 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 }
Greg Claytonef8180a2013-10-15 00:14:28 +0000350 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 }
352 m_breakpoint_pc_offset = 0;
353 StructuredData::ObjectSP breakpoint_pc_offset_value =
354 target_definition_sp->GetValueForKey("breakpoint-pc-offset");
355 if (breakpoint_pc_offset_value) {
356 if (auto breakpoint_pc_int_value =
357 breakpoint_pc_offset_value->GetAsInteger())
358 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
359 }
360
361 if (m_register_info.SetRegisterInfo(*target_definition_sp,
362 GetTarget().GetArchitecture()) > 0) {
363 return true;
364 }
Greg Claytonef8180a2013-10-15 00:14:28 +0000365 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 }
367 return false;
Greg Claytonef8180a2013-10-15 00:14:28 +0000368}
369
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370// If the remote stub didn't give us eh_frame or DWARF register numbers for a
371// register,
Jason Molenda21586c82015-09-09 03:36:24 +0000372// see if the ABI can provide them.
373// DWARF and eh_frame register numbers are defined as a part of the ABI.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374static void AugmentRegisterInfoViaABI(RegisterInfo &reg_info,
375 ConstString reg_name, ABISP abi_sp) {
376 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM ||
377 reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM) {
378 if (abi_sp) {
379 RegisterInfo abi_reg_info;
380 if (abi_sp->GetRegisterInfoByName(reg_name, abi_reg_info)) {
381 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM &&
382 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM) {
383 reg_info.kinds[eRegisterKindEHFrame] =
384 abi_reg_info.kinds[eRegisterKindEHFrame];
385 }
386 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM &&
387 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM) {
388 reg_info.kinds[eRegisterKindDWARF] =
389 abi_reg_info.kinds[eRegisterKindDWARF];
390 }
391 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM &&
392 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM) {
393 reg_info.kinds[eRegisterKindGeneric] =
394 abi_reg_info.kinds[eRegisterKindGeneric];
395 }
396 }
397 }
398 }
399}
400
401static size_t SplitCommaSeparatedRegisterNumberString(
402 const llvm::StringRef &comma_separated_regiter_numbers,
403 std::vector<uint32_t> &regnums, int base) {
404 regnums.clear();
405 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
406 value_pair.second = comma_separated_regiter_numbers;
407 do {
408 value_pair = value_pair.second.split(',');
409 if (!value_pair.first.empty()) {
410 uint32_t reg = StringConvert::ToUInt32(value_pair.first.str().c_str(),
411 LLDB_INVALID_REGNUM, base);
412 if (reg != LLDB_INVALID_REGNUM)
413 regnums.push_back(reg);
414 }
415 } while (!value_pair.second.empty());
416 return regnums.size();
417}
418
419void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
420 if (!force && m_register_info.GetNumRegisters() > 0)
421 return;
422
423 m_register_info.Clear();
424
425 // Check if qHostInfo specified a specific packet timeout for this connection.
426 // If so then lets update our setting so the user knows what the timeout is
427 // and can see it.
Pavel Labath3aa04912016-10-31 17:19:42 +0000428 const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
429 if (host_packet_timeout > std::chrono::seconds(0)) {
430 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout.count());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000431 }
432
433 // Register info search order:
434 // 1 - Use the target definition python file if one is specified.
435 // 2 - If the target definition doesn't have any of the info from the
436 // target.xml (registers) then proceed to read the target.xml.
437 // 3 - Fall back on the qRegisterInfo packets.
438
439 FileSpec target_definition_fspec =
440 GetGlobalPluginProperties()->GetTargetDefinitionFile();
441 if (!target_definition_fspec.Exists()) {
442 // If the filename doesn't exist, it may be a ~ not having been expanded -
443 // try to resolve it.
444 target_definition_fspec.ResolvePath();
445 }
446 if (target_definition_fspec) {
447 // See if we can get register definitions from a python file
448 if (ParsePythonTargetDefinition(target_definition_fspec)) {
449 return;
450 } else {
451 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
452 stream_sp->Printf("ERROR: target description file %s failed to parse.\n",
453 target_definition_fspec.GetPath().c_str());
454 }
455 }
456
457 const ArchSpec &target_arch = GetTarget().GetArchitecture();
458 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
459 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
460
461 // Use the process' architecture instead of the host arch, if available
462 ArchSpec arch_to_use;
463 if (remote_process_arch.IsValid())
464 arch_to_use = remote_process_arch;
465 else
466 arch_to_use = remote_host_arch;
467
468 if (!arch_to_use.IsValid())
469 arch_to_use = target_arch;
470
471 if (GetGDBServerRegisterInfo(arch_to_use))
472 return;
473
474 char packet[128];
475 uint32_t reg_offset = 0;
476 uint32_t reg_num = 0;
477 for (StringExtractorGDBRemote::ResponseType response_type =
478 StringExtractorGDBRemote::eResponse;
479 response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
480 const int packet_len =
481 ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
482 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000483 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000485 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 GDBRemoteCommunication::PacketResult::Success) {
487 response_type = response.GetResponseType();
488 if (response_type == StringExtractorGDBRemote::eResponse) {
489 llvm::StringRef name;
490 llvm::StringRef value;
491 ConstString reg_name;
492 ConstString alt_name;
493 ConstString set_name;
494 std::vector<uint32_t> value_regs;
495 std::vector<uint32_t> invalidate_regs;
496 std::vector<uint8_t> dwarf_opcode_bytes;
497 RegisterInfo reg_info = {
498 NULL, // Name
499 NULL, // Alt name
500 0, // byte size
501 reg_offset, // offset
502 eEncodingUint, // encoding
503 eFormatHex, // format
Jason Molenda21586c82015-09-09 03:36:24 +0000504 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 LLDB_INVALID_REGNUM, // eh_frame reg num
506 LLDB_INVALID_REGNUM, // DWARF reg num
507 LLDB_INVALID_REGNUM, // generic reg num
508 reg_num, // process plugin reg num
509 reg_num // native register number
510 },
511 NULL,
512 NULL,
513 NULL, // Dwarf expression opcode bytes pointer
514 0 // Dwarf expression opcode bytes length
515 };
516
517 while (response.GetNameColonValue(name, value)) {
518 if (name.equals("name")) {
519 reg_name.SetString(value);
520 } else if (name.equals("alt-name")) {
521 alt_name.SetString(value);
522 } else if (name.equals("bitsize")) {
523 value.getAsInteger(0, reg_info.byte_size);
524 reg_info.byte_size /= CHAR_BIT;
525 } else if (name.equals("offset")) {
526 if (value.getAsInteger(0, reg_offset))
527 reg_offset = UINT32_MAX;
528 } else if (name.equals("encoding")) {
529 const Encoding encoding = Args::StringToEncoding(value);
530 if (encoding != eEncodingInvalid)
531 reg_info.encoding = encoding;
532 } else if (name.equals("format")) {
533 Format format = eFormatInvalid;
534 if (Args::StringToFormat(value.str().c_str(), format, NULL)
535 .Success())
536 reg_info.format = format;
537 else {
538 reg_info.format =
539 llvm::StringSwitch<Format>(value)
540 .Case("binary", eFormatBinary)
541 .Case("decimal", eFormatDecimal)
542 .Case("hex", eFormatHex)
543 .Case("float", eFormatFloat)
544 .Case("vector-sint8", eFormatVectorOfSInt8)
545 .Case("vector-uint8", eFormatVectorOfUInt8)
546 .Case("vector-sint16", eFormatVectorOfSInt16)
547 .Case("vector-uint16", eFormatVectorOfUInt16)
548 .Case("vector-sint32", eFormatVectorOfSInt32)
549 .Case("vector-uint32", eFormatVectorOfUInt32)
550 .Case("vector-float32", eFormatVectorOfFloat32)
Valentina Giusticda0ae42016-09-08 14:16:45 +0000551 .Case("vector-uint64", eFormatVectorOfUInt64)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 .Case("vector-uint128", eFormatVectorOfUInt128)
553 .Default(eFormatInvalid);
Jason Molenda21586c82015-09-09 03:36:24 +0000554 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 } else if (name.equals("set")) {
556 set_name.SetString(value);
557 } else if (name.equals("gcc") || name.equals("ehframe")) {
558 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame]))
559 reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM;
560 } else if (name.equals("dwarf")) {
561 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF]))
562 reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM;
563 } else if (name.equals("generic")) {
564 reg_info.kinds[eRegisterKindGeneric] =
565 Args::StringToGenericRegister(value);
566 } else if (name.equals("container-regs")) {
567 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
568 } else if (name.equals("invalidate-regs")) {
569 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
570 } else if (name.equals("dynamic_size_dwarf_expr_bytes")) {
571 size_t dwarf_opcode_len = value.size() / 2;
572 assert(dwarf_opcode_len > 0);
573
574 dwarf_opcode_bytes.resize(dwarf_opcode_len);
575 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
576
577 StringExtractor opcode_extractor(value);
578 uint32_t ret_val =
579 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
580 assert(dwarf_opcode_len == ret_val);
Hafiz Abid Qadeer05008ca2017-01-19 15:11:01 +0000581 UNUSED_IF_ASSERT_DISABLED(ret_val);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
583 }
Jason Molenda21586c82015-09-09 03:36:24 +0000584 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585
586 reg_info.byte_offset = reg_offset;
587 assert(reg_info.byte_size != 0);
588 reg_offset += reg_info.byte_size;
589 if (!value_regs.empty()) {
590 value_regs.push_back(LLDB_INVALID_REGNUM);
591 reg_info.value_regs = value_regs.data();
592 }
593 if (!invalidate_regs.empty()) {
594 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
595 reg_info.invalidate_regs = invalidate_regs.data();
596 }
597
598 // We have to make a temporary ABI here, and not use the GetABI because
599 // this code
600 // gets called in DidAttach, when the target architecture (and
601 // consequently the ABI we'll get from
602 // the process) may be wrong.
Jason Molenda43294c92017-06-29 02:57:03 +0000603 ABISP abi_to_use = ABI::FindPlugin(shared_from_this(), arch_to_use);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604
605 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_to_use);
606
607 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
608 } else {
609 break; // ensure exit before reg_num is incremented
610 }
611 } else {
612 break;
Jason Molenda21586c82015-09-09 03:36:24 +0000613 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 }
615
616 if (m_register_info.GetNumRegisters() > 0) {
617 m_register_info.Finalize(GetTarget().GetArchitecture());
618 return;
619 }
620
621 // We didn't get anything if the accumulated reg_num is zero. See if we are
622 // debugging ARM and fill with a hard coded register set until we can get an
623 // updated debugserver down on the devices.
624 // On the other hand, if the accumulated reg_num is positive, see if we can
625 // add composite registers to the existing primordial ones.
626 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
627
628 if (!target_arch.IsValid()) {
629 if (arch_to_use.IsValid() &&
630 (arch_to_use.GetMachine() == llvm::Triple::arm ||
631 arch_to_use.GetMachine() == llvm::Triple::thumb) &&
632 arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
633 m_register_info.HardcodeARMRegisters(from_scratch);
634 } else if (target_arch.GetMachine() == llvm::Triple::arm ||
635 target_arch.GetMachine() == llvm::Triple::thumb) {
636 m_register_info.HardcodeARMRegisters(from_scratch);
637 }
638
639 // At this point, we can finalize our register info.
640 m_register_info.Finalize(GetTarget().GetArchitecture());
Jason Molenda21586c82015-09-09 03:36:24 +0000641}
642
Zachary Turner97206d52017-05-12 04:51:55 +0000643Status ProcessGDBRemote::WillLaunch(Module *module) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644 return WillLaunchOrAttach();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000645}
646
Zachary Turner97206d52017-05-12 04:51:55 +0000647Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 return WillLaunchOrAttach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000649}
650
Zachary Turner97206d52017-05-12 04:51:55 +0000651Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
652 bool wait_for_launch) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653 return WillLaunchOrAttach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000654}
655
Zachary Turner97206d52017-05-12 04:51:55 +0000656Status ProcessGDBRemote::DoConnectRemote(Stream *strm,
657 llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +0000659 Status error(WillLaunchOrAttach());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000660
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 if (error.Fail())
Greg Claytonb766a732011-02-04 01:58:07 +0000662 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663
664 error = ConnectToDebugserver(remote_url);
665
666 if (error.Fail())
667 return error;
668 StartAsyncThread();
669
670 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
671 if (pid == LLDB_INVALID_PROCESS_ID) {
672 // We don't have a valid process ID, so note that we are connected
673 // and could now request to launch or attach, or get remote process
674 // listings...
675 SetPrivateState(eStateConnected);
676 } else {
677 // We have a valid process
678 SetID(pid);
679 GetThreadList();
680 StringExtractorGDBRemote response;
681 if (m_gdb_comm.GetStopReply(response)) {
682 SetLastStopPacket(response);
683
684 // '?' Packets must be handled differently in non-stop mode
685 if (GetTarget().GetNonStopModeEnabled())
686 HandleStopReplySequence();
687
688 Target &target = GetTarget();
689 if (!target.GetArchitecture().IsValid()) {
690 if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
691 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
692 } else {
693 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
694 }
695 }
696
697 const StateType state = SetThreadStopInfo(response);
698 if (state != eStateInvalid) {
699 SetPrivateState(state);
700 } else
Zachary Turner31659452016-11-17 21:15:14 +0000701 error.SetErrorStringWithFormat(
702 "Process %" PRIu64 " was reported after connecting to "
703 "'%s', but state was not stopped: %s",
704 pid, remote_url.str().c_str(), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 } else
706 error.SetErrorStringWithFormat("Process %" PRIu64
707 " was reported after connecting to '%s', "
708 "but no stop reply packet was received",
Zachary Turner31659452016-11-17 21:15:14 +0000709 pid, remote_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710 }
711
712 if (log)
713 log->Printf("ProcessGDBRemote::%s pid %" PRIu64
714 ": normalizing target architecture initial triple: %s "
715 "(GetTarget().GetArchitecture().IsValid() %s, "
716 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
717 __FUNCTION__, GetID(),
718 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
719 GetTarget().GetArchitecture().IsValid() ? "true" : "false",
720 m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
721
722 if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
723 m_gdb_comm.GetHostArchitecture().IsValid()) {
724 // Prefer the *process'* architecture over that of the *host*, if available.
725 if (m_gdb_comm.GetProcessArchitecture().IsValid())
726 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
727 else
728 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
729 }
730
731 if (log)
732 log->Printf("ProcessGDBRemote::%s pid %" PRIu64
733 ": normalized target architecture triple: %s",
734 __FUNCTION__, GetID(),
735 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
736
737 if (error.Success()) {
738 PlatformSP platform_sp = GetTarget().GetPlatform();
739 if (platform_sp && platform_sp->IsConnected())
740 SetUnixSignals(platform_sp->GetUnixSignals());
741 else
742 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
743 }
744
745 return error;
Greg Claytonb766a732011-02-04 01:58:07 +0000746}
747
Zachary Turner97206d52017-05-12 04:51:55 +0000748Status ProcessGDBRemote::WillLaunchOrAttach() {
749 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750 m_stdio_communication.Clear();
751 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000752}
753
754//----------------------------------------------------------------------
755// Process Control
756//----------------------------------------------------------------------
Zachary Turner97206d52017-05-12 04:51:55 +0000757Status ProcessGDBRemote::DoLaunch(Module *exe_module,
758 ProcessLaunchInfo &launch_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +0000760 Status error;
Greg Clayton982c9762011-11-03 21:22:33 +0000761
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762 if (log)
763 log->Printf("ProcessGDBRemote::%s() entered", __FUNCTION__);
Todd Fiala75f47c32014-10-11 21:42:09 +0000764
Kate Stoneb9c1b512016-09-06 20:57:50 +0000765 uint32_t launch_flags = launch_info.GetFlags().Get();
766 FileSpec stdin_file_spec{};
767 FileSpec stdout_file_spec{};
768 FileSpec stderr_file_spec{};
769 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000770
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771 const FileAction *file_action;
772 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
773 if (file_action) {
774 if (file_action->GetAction() == FileAction::eFileActionOpen)
775 stdin_file_spec = file_action->GetFileSpec();
776 }
777 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
778 if (file_action) {
779 if (file_action->GetAction() == FileAction::eFileActionOpen)
780 stdout_file_spec = file_action->GetFileSpec();
781 }
782 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
783 if (file_action) {
784 if (file_action->GetAction() == FileAction::eFileActionOpen)
785 stderr_file_spec = file_action->GetFileSpec();
786 }
Greg Clayton982c9762011-11-03 21:22:33 +0000787
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 if (log) {
789 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
790 log->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
791 "launch_info: stdin=%s, stdout=%s, stderr=%s",
792 __FUNCTION__,
793 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
794 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
795 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Vince Harrondf3f00f2015-02-10 21:09:04 +0000796 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 log->Printf("ProcessGDBRemote::%s no STDIO paths given via launch_info",
798 __FUNCTION__);
799 }
Vince Harrondf3f00f2015-02-10 21:09:04 +0000800
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
802 if (stdin_file_spec || disable_stdio) {
803 // the inferior will be reading stdin from the specified file
804 // or stdio is completely disabled
805 m_stdin_forward = false;
806 } else {
807 m_stdin_forward = true;
808 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000809
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
811 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
812 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
813 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
814 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000815
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 ObjectFile *object_file = exe_module->GetObjectFile();
817 if (object_file) {
818 error = EstablishConnectionIfNeeded(launch_info);
819 if (error.Success()) {
820 lldb_utility::PseudoTerminal pty;
821 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000822
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 PlatformSP platform_sp(GetTarget().GetPlatform());
824 if (disable_stdio) {
825 // set to /dev/null unless redirected to a file above
826 if (!stdin_file_spec)
827 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
828 if (!stdout_file_spec)
829 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
830 if (!stderr_file_spec)
831 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
832 } else if (platform_sp && platform_sp->IsHost()) {
833 // If the debugserver is local and we aren't disabling STDIO, lets use
834 // a pseudo terminal to instead of relying on the 'O' packets for stdio
835 // since 'O' packets can really slow down debugging if the inferior
836 // does a lot of output.
837 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
838 pty.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, NULL, 0)) {
839 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
Chaoren Lind3173f32015-05-29 19:52:29 +0000840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 if (!stdin_file_spec)
842 stdin_file_spec = slave_name;
Chaoren Lind3173f32015-05-29 19:52:29 +0000843
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844 if (!stdout_file_spec)
845 stdout_file_spec = slave_name;
Greg Clayton71337622011-02-24 22:24:29 +0000846
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 if (!stderr_file_spec)
848 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000849 }
Vince Harron1b5a74e2015-01-21 22:42:49 +0000850 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 log->Printf(
852 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
853 "(IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
854 __FUNCTION__,
855 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
856 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
857 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
858 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000859
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 if (log)
861 log->Printf("ProcessGDBRemote::%s final STDIO paths after all "
862 "adjustments: stdin=%s, stdout=%s, stderr=%s",
863 __FUNCTION__,
864 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
865 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
866 stderr_file_spec ? stderr_file_spec.GetCString()
867 : "<null>");
Ed Maste81b4c5f2016-01-04 01:43:47 +0000868
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869 if (stdin_file_spec)
870 m_gdb_comm.SetSTDIN(stdin_file_spec);
871 if (stdout_file_spec)
872 m_gdb_comm.SetSTDOUT(stdout_file_spec);
873 if (stderr_file_spec)
874 m_gdb_comm.SetSTDERR(stderr_file_spec);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000875
Kate Stoneb9c1b512016-09-06 20:57:50 +0000876 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
877 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 m_gdb_comm.SendLaunchArchPacket(
880 GetTarget().GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000881
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882 const char *launch_event_data = launch_info.GetLaunchEventData();
883 if (launch_event_data != NULL && *launch_event_data != '\0')
884 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
Eugene Zelenko0722f082015-10-24 01:28:05 +0000885
Kate Stoneb9c1b512016-09-06 20:57:50 +0000886 if (working_dir) {
887 m_gdb_comm.SetWorkingDir(working_dir);
888 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000889
Kate Stoneb9c1b512016-09-06 20:57:50 +0000890 // Send the environment and the program + arguments after we connect
891 const Args &environment = launch_info.GetEnvironmentEntries();
892 if (environment.GetArgumentCount()) {
893 size_t num_environment_entries = environment.GetArgumentCount();
894 for (size_t i = 0; i < num_environment_entries; ++i) {
895 const char *env_entry = environment.GetArgumentAtIndex(i);
896 if (env_entry == NULL ||
897 m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Ewan Crawford78baa192015-05-13 09:18:18 +0000898 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899 }
900 }
Ewan Crawford78baa192015-05-13 09:18:18 +0000901
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902 {
903 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +0000904 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
905 std::chrono::seconds(10));
Ewan Crawford78baa192015-05-13 09:18:18 +0000906
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907 int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
908 if (arg_packet_err == 0) {
909 std::string error_str;
910 if (m_gdb_comm.GetLaunchSuccess(error_str)) {
911 SetID(m_gdb_comm.GetCurrentProcessID());
912 } else {
913 error.SetErrorString(error_str.c_str());
914 }
915 } else {
916 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
917 arg_packet_err);
918 }
919 }
920
921 if (GetID() == LLDB_INVALID_PROCESS_ID) {
922 if (log)
923 log->Printf("failed to connect to debugserver: %s",
924 error.AsCString());
925 KillDebugserverProcess();
926 return error;
927 }
928
929 StringExtractorGDBRemote response;
930 if (m_gdb_comm.GetStopReply(response)) {
Ewan Crawford78baa192015-05-13 09:18:18 +0000931 SetLastStopPacket(response);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000932 // '?' Packets must be handled differently in non-stop mode
933 if (GetTarget().GetNonStopModeEnabled())
934 HandleStopReplySequence();
935
936 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
937
938 if (process_arch.IsValid()) {
939 GetTarget().MergeArchitecture(process_arch);
940 } else {
941 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
942 if (host_arch.IsValid())
943 GetTarget().MergeArchitecture(host_arch);
944 }
945
946 SetPrivateState(SetThreadStopInfo(response));
947
948 if (!disable_stdio) {
949 if (pty.GetMasterFileDescriptor() !=
950 lldb_utility::PseudoTerminal::invalid_fd)
951 SetSTDIOFileDescriptor(pty.ReleaseMasterFileDescriptor());
952 }
953 }
954 } else {
955 if (log)
956 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Ewan Crawford78baa192015-05-13 09:18:18 +0000957 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958 } else {
959 // Set our user ID to an invalid process ID.
960 SetID(LLDB_INVALID_PROCESS_ID);
961 error.SetErrorStringWithFormat(
962 "failed to get object file from '%s' for arch %s",
963 exe_module->GetFileSpec().GetFilename().AsCString(),
964 exe_module->GetArchitecture().GetArchitectureName());
965 }
966 return error;
Ewan Crawford78baa192015-05-13 09:18:18 +0000967}
968
Zachary Turner97206d52017-05-12 04:51:55 +0000969Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
970 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 // Only connect if we have a valid connect URL
972 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
973
Zachary Turner31659452016-11-17 21:15:14 +0000974 if (!connect_url.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 if (log)
976 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
Zachary Turner31659452016-11-17 21:15:14 +0000977 connect_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
979 new ConnectionFileDescriptor());
980 if (conn_ap.get()) {
981 const uint32_t max_retry_count = 50;
982 uint32_t retry_count = 0;
983 while (!m_gdb_comm.IsConnected()) {
984 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) {
985 m_gdb_comm.SetConnection(conn_ap.release());
986 break;
987 } else if (error.WasInterrupted()) {
988 // If we were interrupted, don't keep retrying.
989 break;
990 }
991
992 retry_count++;
993
994 if (retry_count >= max_retry_count)
995 break;
996
997 usleep(100000);
998 }
999 }
1000 }
1001
1002 if (!m_gdb_comm.IsConnected()) {
1003 if (error.Success())
1004 error.SetErrorString("not connected to remote gdb server");
1005 return error;
1006 }
1007
1008 // Start the communications read thread so all incoming data can be
1009 // parsed into packets and queued as they arrive.
1010 if (GetTarget().GetNonStopModeEnabled())
1011 m_gdb_comm.StartReadThread();
1012
1013 // We always seem to be able to open a connection to a local port
1014 // so we need to make sure we can then send data to it. If we can't
1015 // then we aren't actually connected to anything, so try and do the
1016 // handshake with the remote GDB server and make sure that goes
1017 // alright.
1018 if (!m_gdb_comm.HandshakeWithServer(&error)) {
1019 m_gdb_comm.Disconnect();
1020 if (error.Success())
1021 error.SetErrorString("not connected to remote gdb server");
1022 return error;
1023 }
1024
1025 // Send $QNonStop:1 packet on startup if required
1026 if (GetTarget().GetNonStopModeEnabled())
1027 GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true));
1028
1029 m_gdb_comm.GetEchoSupported();
1030 m_gdb_comm.GetThreadSuffixSupported();
1031 m_gdb_comm.GetListThreadsInStopReplySupported();
1032 m_gdb_comm.GetHostInfo();
1033 m_gdb_comm.GetVContSupported('c');
1034 m_gdb_comm.GetVAttachOrWaitSupported();
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001035 m_gdb_comm.EnableErrorStringInPacket();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036
1037 // Ask the remote server for the default thread id
1038 if (GetTarget().GetNonStopModeEnabled())
1039 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1040
1041 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1042 for (size_t idx = 0; idx < num_cmds; idx++) {
1043 StringExtractorGDBRemote response;
1044 m_gdb_comm.SendPacketAndWaitForResponse(
1045 GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1046 }
1047 return error;
1048}
1049
1050void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
1051 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1052 if (log)
1053 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1054 if (GetID() != LLDB_INVALID_PROCESS_ID) {
1055 BuildDynamicRegisterInfo(false);
1056
1057 // See if the GDB server supports the qHostInfo information
1058
1059 // See if the GDB server supports the qProcessInfo packet, if so
1060 // prefer that over the Host information as it will be more specific
1061 // to our process.
1062
1063 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1064 if (remote_process_arch.IsValid()) {
1065 process_arch = remote_process_arch;
1066 if (log)
1067 log->Printf("ProcessGDBRemote::%s gdb-remote had process architecture, "
1068 "using %s %s",
1069 __FUNCTION__, process_arch.GetArchitectureName()
1070 ? process_arch.GetArchitectureName()
1071 : "<null>",
1072 process_arch.GetTriple().getTriple().c_str()
1073 ? process_arch.GetTriple().getTriple().c_str()
1074 : "<null>");
1075 } else {
1076 process_arch = m_gdb_comm.GetHostArchitecture();
1077 if (log)
1078 log->Printf("ProcessGDBRemote::%s gdb-remote did not have process "
1079 "architecture, using gdb-remote host architecture %s %s",
1080 __FUNCTION__, process_arch.GetArchitectureName()
1081 ? process_arch.GetArchitectureName()
1082 : "<null>",
1083 process_arch.GetTriple().getTriple().c_str()
1084 ? process_arch.GetTriple().getTriple().c_str()
1085 : "<null>");
1086 }
1087
1088 if (process_arch.IsValid()) {
1089 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1090 if (target_arch.IsValid()) {
1091 if (log)
1092 log->Printf(
1093 "ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1094 __FUNCTION__, target_arch.GetArchitectureName()
1095 ? target_arch.GetArchitectureName()
1096 : "<null>",
1097 target_arch.GetTriple().getTriple().c_str()
1098 ? target_arch.GetTriple().getTriple().c_str()
1099 : "<null>");
1100
1101 // If the remote host is ARM and we have apple as the vendor, then
1102 // ARM executables and shared libraries can have mixed ARM
1103 // architectures.
1104 // You can have an armv6 executable, and if the host is armv7, then the
1105 // system will load the best possible architecture for all shared
1106 // libraries
1107 // it has, so we really need to take the remote host architecture as our
1108 // defacto architecture in this case.
1109
1110 if ((process_arch.GetMachine() == llvm::Triple::arm ||
1111 process_arch.GetMachine() == llvm::Triple::thumb) &&
1112 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1113 GetTarget().SetArchitecture(process_arch);
1114 if (log)
1115 log->Printf("ProcessGDBRemote::%s remote process is ARM/Apple, "
1116 "setting target arch to %s %s",
1117 __FUNCTION__, process_arch.GetArchitectureName()
1118 ? process_arch.GetArchitectureName()
1119 : "<null>",
1120 process_arch.GetTriple().getTriple().c_str()
1121 ? process_arch.GetTriple().getTriple().c_str()
1122 : "<null>");
1123 } else {
1124 // Fill in what is missing in the triple
1125 const llvm::Triple &remote_triple = process_arch.GetTriple();
1126 llvm::Triple new_target_triple = target_arch.GetTriple();
1127 if (new_target_triple.getVendorName().size() == 0) {
1128 new_target_triple.setVendor(remote_triple.getVendor());
1129
1130 if (new_target_triple.getOSName().size() == 0) {
1131 new_target_triple.setOS(remote_triple.getOS());
1132
1133 if (new_target_triple.getEnvironmentName().size() == 0)
1134 new_target_triple.setEnvironment(
1135 remote_triple.getEnvironment());
1136 }
1137
1138 ArchSpec new_target_arch = target_arch;
1139 new_target_arch.SetTriple(new_target_triple);
1140 GetTarget().SetArchitecture(new_target_arch);
1141 }
1142 }
1143
1144 if (log)
1145 log->Printf("ProcessGDBRemote::%s final target arch after "
1146 "adjustments for remote architecture: %s %s",
1147 __FUNCTION__, target_arch.GetArchitectureName()
1148 ? target_arch.GetArchitectureName()
1149 : "<null>",
1150 target_arch.GetTriple().getTriple().c_str()
1151 ? target_arch.GetTriple().getTriple().c_str()
1152 : "<null>");
1153 } else {
1154 // The target doesn't have a valid architecture yet, set it from
1155 // the architecture we got from the remote GDB server
1156 GetTarget().SetArchitecture(process_arch);
1157 }
1158 }
1159
1160 // Find out which StructuredDataPlugins are supported by the
1161 // debug monitor. These plugins transmit data over async $J packets.
1162 auto supported_packets_array =
1163 m_gdb_comm.GetSupportedStructuredDataPlugins();
1164 if (supported_packets_array)
1165 MapSupportedStructuredDataPlugins(*supported_packets_array);
1166 }
1167}
1168
1169void ProcessGDBRemote::DidLaunch() {
1170 ArchSpec process_arch;
1171 DidLaunchOrAttach(process_arch);
1172}
1173
Zachary Turner97206d52017-05-12 04:51:55 +00001174Status ProcessGDBRemote::DoAttachToProcessWithID(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1176 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00001177 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001178
1179 if (log)
1180 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1181
1182 // Clear out and clean up from any current state
1183 Clear();
1184 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1185 error = EstablishConnectionIfNeeded(attach_info);
1186 if (error.Success()) {
1187 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1188
1189 char packet[64];
1190 const int packet_len =
1191 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1192 SetID(attach_pid);
1193 m_async_broadcaster.BroadcastEvent(
1194 eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1195 } else
1196 SetExitStatus(-1, error.AsCString());
1197 }
1198
1199 return error;
1200}
1201
Zachary Turner97206d52017-05-12 04:51:55 +00001202Status ProcessGDBRemote::DoAttachToProcessWithName(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203 const char *process_name, const ProcessAttachInfo &attach_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001204 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 // Clear out and clean up from any current state
1206 Clear();
1207
1208 if (process_name && process_name[0]) {
1209 error = EstablishConnectionIfNeeded(attach_info);
1210 if (error.Success()) {
1211 StreamString packet;
1212
1213 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1214
1215 if (attach_info.GetWaitForLaunch()) {
1216 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1217 packet.PutCString("vAttachWait");
1218 } else {
1219 if (attach_info.GetIgnoreExisting())
1220 packet.PutCString("vAttachWait");
1221 else
1222 packet.PutCString("vAttachOrWait");
1223 }
1224 } else
1225 packet.PutCString("vAttachName");
1226 packet.PutChar(';');
1227 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1228 endian::InlHostByteOrder(),
1229 endian::InlHostByteOrder());
1230
1231 m_async_broadcaster.BroadcastEvent(
1232 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001233 new EventDataBytes(packet.GetString().data(), packet.GetSize()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001234
1235 } else
1236 SetExitStatus(-1, error.AsCString());
1237 }
1238 return error;
1239}
1240
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001241lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options,
1242 Status &error) {
1243 return m_gdb_comm.SendStartTracePacket(options, error);
1244}
1245
1246Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
1247 return m_gdb_comm.SendStopTracePacket(uid, thread_id);
1248}
1249
1250Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
1251 llvm::MutableArrayRef<uint8_t> &buffer,
1252 size_t offset) {
1253 return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset);
1254}
1255
1256Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
1257 llvm::MutableArrayRef<uint8_t> &buffer,
1258 size_t offset) {
1259 return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset);
1260}
1261
1262Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid,
1263 TraceOptions &options) {
1264 return m_gdb_comm.SendGetTraceConfigPacket(uid, options);
1265}
1266
Kate Stoneb9c1b512016-09-06 20:57:50 +00001267void ProcessGDBRemote::DidExit() {
1268 // When we exit, disconnect from the GDB server communications
1269 m_gdb_comm.Disconnect();
1270}
1271
1272void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1273 // If you can figure out what the architecture is, fill it in here.
1274 process_arch.Clear();
1275 DidLaunchOrAttach(process_arch);
1276}
1277
Zachary Turner97206d52017-05-12 04:51:55 +00001278Status ProcessGDBRemote::WillResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279 m_continue_c_tids.clear();
1280 m_continue_C_tids.clear();
1281 m_continue_s_tids.clear();
1282 m_continue_S_tids.clear();
1283 m_jstopinfo_sp.reset();
1284 m_jthreadsinfo_sp.reset();
Zachary Turner97206d52017-05-12 04:51:55 +00001285 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286}
1287
Zachary Turner97206d52017-05-12 04:51:55 +00001288Status ProcessGDBRemote::DoResume() {
1289 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1291 if (log)
1292 log->Printf("ProcessGDBRemote::Resume()");
1293
1294 ListenerSP listener_sp(
1295 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1296 if (listener_sp->StartListeningForEvents(
1297 &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
1298 listener_sp->StartListeningForEvents(
1299 &m_async_broadcaster,
1300 ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1301
1302 const size_t num_threads = GetThreadList().GetSize();
1303
1304 StreamString continue_packet;
1305 bool continue_packet_error = false;
1306 if (m_gdb_comm.HasAnyVContSupport()) {
1307 if (!GetTarget().GetNonStopModeEnabled() &&
1308 (m_continue_c_tids.size() == num_threads ||
1309 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1310 m_continue_s_tids.empty() && m_continue_S_tids.empty()))) {
1311 // All threads are continuing, just send a "c" packet
1312 continue_packet.PutCString("c");
1313 } else {
1314 continue_packet.PutCString("vCont");
1315
1316 if (!m_continue_c_tids.empty()) {
1317 if (m_gdb_comm.GetVContSupported('c')) {
1318 for (tid_collection::const_iterator
1319 t_pos = m_continue_c_tids.begin(),
1320 t_end = m_continue_c_tids.end();
1321 t_pos != t_end; ++t_pos)
1322 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1323 } else
1324 continue_packet_error = true;
1325 }
1326
1327 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1328 if (m_gdb_comm.GetVContSupported('C')) {
1329 for (tid_sig_collection::const_iterator
1330 s_pos = m_continue_C_tids.begin(),
1331 s_end = m_continue_C_tids.end();
1332 s_pos != s_end; ++s_pos)
1333 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
1334 s_pos->first);
1335 } else
1336 continue_packet_error = true;
1337 }
1338
1339 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1340 if (m_gdb_comm.GetVContSupported('s')) {
1341 for (tid_collection::const_iterator
1342 t_pos = m_continue_s_tids.begin(),
1343 t_end = m_continue_s_tids.end();
1344 t_pos != t_end; ++t_pos)
1345 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1346 } else
1347 continue_packet_error = true;
1348 }
1349
1350 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1351 if (m_gdb_comm.GetVContSupported('S')) {
1352 for (tid_sig_collection::const_iterator
1353 s_pos = m_continue_S_tids.begin(),
1354 s_end = m_continue_S_tids.end();
1355 s_pos != s_end; ++s_pos)
1356 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
1357 s_pos->first);
1358 } else
1359 continue_packet_error = true;
1360 }
1361
1362 if (continue_packet_error)
Zachary Turnerc1564272016-11-16 21:15:24 +00001363 continue_packet.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001364 }
1365 } else
1366 continue_packet_error = true;
1367
1368 if (continue_packet_error) {
1369 // Either no vCont support, or we tried to use part of the vCont
1370 // packet that wasn't supported by the remote GDB server.
1371 // We need to try and make a simple packet that can do our continue
1372 const size_t num_continue_c_tids = m_continue_c_tids.size();
1373 const size_t num_continue_C_tids = m_continue_C_tids.size();
1374 const size_t num_continue_s_tids = m_continue_s_tids.size();
1375 const size_t num_continue_S_tids = m_continue_S_tids.size();
1376 if (num_continue_c_tids > 0) {
1377 if (num_continue_c_tids == num_threads) {
1378 // All threads are resuming...
1379 m_gdb_comm.SetCurrentThreadForRun(-1);
1380 continue_packet.PutChar('c');
1381 continue_packet_error = false;
1382 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1383 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1384 // Only one thread is continuing
1385 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1386 continue_packet.PutChar('c');
1387 continue_packet_error = false;
1388 }
1389 }
1390
1391 if (continue_packet_error && num_continue_C_tids > 0) {
1392 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1393 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1394 num_continue_S_tids == 0) {
1395 const int continue_signo = m_continue_C_tids.front().second;
1396 // Only one thread is continuing
1397 if (num_continue_C_tids > 1) {
1398 // More that one thread with a signal, yet we don't have
1399 // vCont support and we are being asked to resume each
1400 // thread with a signal, we need to make sure they are
1401 // all the same signal, or we can't issue the continue
1402 // accurately with the current support...
1403 if (num_continue_C_tids > 1) {
1404 continue_packet_error = false;
1405 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1406 if (m_continue_C_tids[i].second != continue_signo)
1407 continue_packet_error = true;
1408 }
1409 }
1410 if (!continue_packet_error)
1411 m_gdb_comm.SetCurrentThreadForRun(-1);
1412 } else {
1413 // Set the continue thread ID
1414 continue_packet_error = false;
1415 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1416 }
1417 if (!continue_packet_error) {
1418 // Add threads continuing with the same signo...
1419 continue_packet.Printf("C%2.2x", continue_signo);
1420 }
1421 }
1422 }
1423
1424 if (continue_packet_error && num_continue_s_tids > 0) {
1425 if (num_continue_s_tids == num_threads) {
1426 // All threads are resuming...
1427 m_gdb_comm.SetCurrentThreadForRun(-1);
1428
1429 // If in Non-Stop-Mode use vCont when stepping
1430 if (GetTarget().GetNonStopModeEnabled()) {
1431 if (m_gdb_comm.GetVContSupported('s'))
1432 continue_packet.PutCString("vCont;s");
1433 else
1434 continue_packet.PutChar('s');
1435 } else
1436 continue_packet.PutChar('s');
1437
1438 continue_packet_error = false;
1439 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1440 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1441 // Only one thread is stepping
1442 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1443 continue_packet.PutChar('s');
1444 continue_packet_error = false;
1445 }
1446 }
1447
1448 if (!continue_packet_error && num_continue_S_tids > 0) {
1449 if (num_continue_S_tids == num_threads) {
1450 const int step_signo = m_continue_S_tids.front().second;
1451 // Are all threads trying to step with the same signal?
1452 continue_packet_error = false;
1453 if (num_continue_S_tids > 1) {
1454 for (size_t i = 1; i < num_threads; ++i) {
1455 if (m_continue_S_tids[i].second != step_signo)
1456 continue_packet_error = true;
1457 }
1458 }
1459 if (!continue_packet_error) {
1460 // Add threads stepping with the same signo...
1461 m_gdb_comm.SetCurrentThreadForRun(-1);
1462 continue_packet.Printf("S%2.2x", step_signo);
1463 }
1464 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1465 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1466 // Only one thread is stepping with signal
1467 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1468 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1469 continue_packet_error = false;
1470 }
1471 }
1472 }
1473
1474 if (continue_packet_error) {
1475 error.SetErrorString("can't make continue packet for this resume");
1476 } else {
1477 EventSP event_sp;
1478 if (!m_async_thread.IsJoinable()) {
1479 error.SetErrorString("Trying to resume but the async thread is dead.");
1480 if (log)
1481 log->Printf("ProcessGDBRemote::DoResume: Trying to resume but the "
1482 "async thread is dead.");
1483 return error;
1484 }
1485
1486 m_async_broadcaster.BroadcastEvent(
1487 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001488 new EventDataBytes(continue_packet.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001489 continue_packet.GetSize()));
1490
Pavel Labathd35031e12016-11-30 10:41:42 +00001491 if (listener_sp->GetEvent(event_sp, std::chrono::seconds(5)) == false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001492 error.SetErrorString("Resume timed out.");
1493 if (log)
1494 log->Printf("ProcessGDBRemote::DoResume: Resume timed out.");
1495 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1496 error.SetErrorString("Broadcast continue, but the async thread was "
1497 "killed before we got an ack back.");
1498 if (log)
1499 log->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
1500 "async thread was killed before we got an ack back.");
1501 return error;
1502 }
1503 }
1504 }
1505
1506 return error;
1507}
1508
1509void ProcessGDBRemote::HandleStopReplySequence() {
1510 while (true) {
1511 // Send vStopped
1512 StringExtractorGDBRemote response;
1513 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1514
1515 // OK represents end of signal list
1516 if (response.IsOKResponse())
1517 break;
1518
1519 // If not OK or a normal packet we have a problem
1520 if (!response.IsNormalResponse())
1521 break;
1522
1523 SetLastStopPacket(response);
1524 }
1525}
1526
1527void ProcessGDBRemote::ClearThreadIDList() {
1528 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1529 m_thread_ids.clear();
1530 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00001531}
1532
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001533size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001534ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
1535 m_thread_ids.clear();
1536 m_thread_pcs.clear();
1537 size_t comma_pos;
1538 lldb::tid_t tid;
1539 while ((comma_pos = value.find(',')) != std::string::npos) {
1540 value[comma_pos] = '\0';
1541 // thread in big endian hex
1542 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001543 if (tid != LLDB_INVALID_THREAD_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001544 m_thread_ids.push_back(tid);
1545 value.erase(0, comma_pos + 1);
1546 }
1547 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1548 if (tid != LLDB_INVALID_THREAD_ID)
1549 m_thread_ids.push_back(tid);
1550 return m_thread_ids.size();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001551}
1552
Jason Molenda545304d2015-12-18 00:45:35 +00001553size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001554ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
1555 m_thread_pcs.clear();
1556 size_t comma_pos;
1557 lldb::addr_t pc;
1558 while ((comma_pos = value.find(',')) != std::string::npos) {
1559 value[comma_pos] = '\0';
1560 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1561 if (pc != LLDB_INVALID_ADDRESS)
1562 m_thread_pcs.push_back(pc);
1563 value.erase(0, comma_pos + 1);
1564 }
1565 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1566 if (pc != LLDB_INVALID_THREAD_ID)
1567 m_thread_pcs.push_back(pc);
1568 return m_thread_pcs.size();
Jason Molenda545304d2015-12-18 00:45:35 +00001569}
1570
Kate Stoneb9c1b512016-09-06 20:57:50 +00001571bool ProcessGDBRemote::UpdateThreadIDList() {
1572 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001573
Kate Stoneb9c1b512016-09-06 20:57:50 +00001574 if (m_jthreadsinfo_sp) {
1575 // If we have the JSON threads info, we can get the thread list from that
1576 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1577 if (thread_infos && thread_infos->GetSize() > 0) {
1578 m_thread_ids.clear();
1579 m_thread_pcs.clear();
1580 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1581 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1582 if (thread_dict) {
1583 // Set the thread stop info from the JSON dictionary
1584 SetThreadStopInfo(thread_dict);
1585 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1586 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1587 m_thread_ids.push_back(tid);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001588 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001589 return true; // Keep iterating through all thread_info objects
1590 });
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001591 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001592 if (!m_thread_ids.empty())
1593 return true;
1594 } else {
1595 // See if we can get the thread IDs from the current stop reply packets
1596 // that might contain a "threads" key/value pair
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001597
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598 // Lock the thread stack while we access it
1599 // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1600 std::unique_lock<std::recursive_mutex> stop_stack_lock(
1601 m_last_stop_packet_mutex, std::defer_lock);
1602 if (stop_stack_lock.try_lock()) {
1603 // Get the number of stop packets on the stack
1604 int nItems = m_stop_packet_stack.size();
1605 // Iterate over them
1606 for (int i = 0; i < nItems; i++) {
1607 // Get the thread stop info
1608 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1609 const std::string &stop_info_str = stop_info.GetStringRef();
Jason Molenda545304d2015-12-18 00:45:35 +00001610
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611 m_thread_pcs.clear();
1612 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1613 if (thread_pcs_pos != std::string::npos) {
1614 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1615 const size_t end = stop_info_str.find(';', start);
1616 if (end != std::string::npos) {
1617 std::string value = stop_info_str.substr(start, end - start);
1618 UpdateThreadPCsFromStopReplyThreadsValue(value);
1619 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001620 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001621
Kate Stoneb9c1b512016-09-06 20:57:50 +00001622 const size_t threads_pos = stop_info_str.find(";threads:");
1623 if (threads_pos != std::string::npos) {
1624 const size_t start = threads_pos + strlen(";threads:");
1625 const size_t end = stop_info_str.find(';', start);
1626 if (end != std::string::npos) {
1627 std::string value = stop_info_str.substr(start, end - start);
1628 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1629 return true;
1630 }
1631 }
1632 }
1633 }
1634 }
1635
1636 bool sequence_mutex_unavailable = false;
1637 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1638 if (sequence_mutex_unavailable) {
1639 return false; // We just didn't get the list
1640 }
1641 return true;
1642}
1643
1644bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
1645 ThreadList &new_thread_list) {
1646 // locker will keep a mutex locked until it goes out of scope
1647 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
Pavel Labathe8a7b982017-02-06 19:31:09 +00001648 LLDB_LOGV(log, "pid = {0}", GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001649
1650 size_t num_thread_ids = m_thread_ids.size();
1651 // The "m_thread_ids" thread ID list should always be updated after each stop
1652 // reply packet, but in case it isn't, update it here.
1653 if (num_thread_ids == 0) {
1654 if (!UpdateThreadIDList())
1655 return false;
1656 num_thread_ids = m_thread_ids.size();
1657 }
1658
1659 ThreadList old_thread_list_copy(old_thread_list);
1660 if (num_thread_ids > 0) {
1661 for (size_t i = 0; i < num_thread_ids; ++i) {
1662 tid_t tid = m_thread_ids[i];
1663 ThreadSP thread_sp(
1664 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1665 if (!thread_sp) {
1666 thread_sp.reset(new ThreadGDBRemote(*this, tid));
Pavel Labathe8a7b982017-02-06 19:31:09 +00001667 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1668 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001669 } else {
Pavel Labathe8a7b982017-02-06 19:31:09 +00001670 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1671 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001672 }
Pavel Labathe0a5b572017-01-20 14:17:16 +00001673
1674 SetThreadPc(thread_sp, i);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1676 }
1677 }
1678
1679 // Whatever that is left in old_thread_list_copy are not
1680 // present in new_thread_list. Remove non-existent threads from internal id
1681 // table.
1682 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1683 for (size_t i = 0; i < old_num_thread_ids; i++) {
1684 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1685 if (old_thread_sp) {
1686 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1687 m_thread_id_to_index_id_map.erase(old_thread_id);
1688 }
1689 }
1690
1691 return true;
1692}
1693
Pavel Labathe0a5b572017-01-20 14:17:16 +00001694void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1695 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1696 GetByteOrder() != eByteOrderInvalid) {
1697 ThreadGDBRemote *gdb_thread =
1698 static_cast<ThreadGDBRemote *>(thread_sp.get());
1699 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1700 if (reg_ctx_sp) {
1701 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1702 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1703 if (pc_regnum != LLDB_INVALID_REGNUM) {
1704 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1705 }
1706 }
1707 }
1708}
1709
Kate Stoneb9c1b512016-09-06 20:57:50 +00001710bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1711 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1712 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1713 // packet
1714 if (thread_infos_sp) {
1715 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1716 if (thread_infos) {
1717 lldb::tid_t tid;
1718 const size_t n = thread_infos->GetSize();
1719 for (size_t i = 0; i < n; ++i) {
1720 StructuredData::Dictionary *thread_dict =
1721 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1722 if (thread_dict) {
1723 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1724 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1725 if (tid == thread->GetID())
1726 return (bool)SetThreadStopInfo(thread_dict);
1727 }
1728 }
1729 }
1730 }
1731 }
1732 return false;
1733}
1734
1735bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1736 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1737 // packet
1738 if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1739 return true;
1740
1741 // See if we got thread stop info for any threads valid stop info reasons
1742 // threads
1743 // via the "jstopinfo" packet stop reply packet key/value pair?
1744 if (m_jstopinfo_sp) {
1745 // If we have "jstopinfo" then we have stop descriptions for all threads
1746 // that have stop reasons, and if there is no entry for a thread, then
1747 // it has no stop reason.
1748 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1749 if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1750 thread->SetStopInfo(StopInfoSP());
Greg Clayton9e920902012-04-10 02:25:43 +00001751 }
1752 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001753 }
1754
1755 // Fall back to using the qThreadStopInfo packet
1756 StringExtractorGDBRemote stop_packet;
1757 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1758 return SetThreadStopInfo(stop_packet) == eStateStopped;
1759 return false;
Greg Clayton9e920902012-04-10 02:25:43 +00001760}
1761
Kate Stoneb9c1b512016-09-06 20:57:50 +00001762ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1763 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1764 uint8_t signo, const std::string &thread_name, const std::string &reason,
1765 const std::string &description, uint32_t exc_type,
1766 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1767 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1768 // queue_serial are valid
1769 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1770 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1771 ThreadSP thread_sp;
1772 if (tid != LLDB_INVALID_THREAD_ID) {
1773 // Scope for "locker" below
Greg Clayton9e920902012-04-10 02:25:43 +00001774 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001775 // m_thread_list_real does have its own mutex, but we need to
1776 // hold onto the mutex between the call to
1777 // m_thread_list_real.FindThreadByID(...)
1778 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1779 std::lock_guard<std::recursive_mutex> guard(
1780 m_thread_list_real.GetMutex());
1781 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1782
1783 if (!thread_sp) {
1784 // Create the thread if we need to
1785 thread_sp.reset(new ThreadGDBRemote(*this, tid));
1786 m_thread_list_real.AddThread(thread_sp);
1787 }
Greg Clayton9e920902012-04-10 02:25:43 +00001788 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001789
Kate Stoneb9c1b512016-09-06 20:57:50 +00001790 if (thread_sp) {
1791 ThreadGDBRemote *gdb_thread =
1792 static_cast<ThreadGDBRemote *>(thread_sp.get());
1793 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1794
Pavel Labathe0a5b572017-01-20 14:17:16 +00001795 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1796 if (iter != m_thread_ids.end()) {
1797 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1798 }
1799
Kate Stoneb9c1b512016-09-06 20:57:50 +00001800 for (const auto &pair : expedited_register_map) {
1801 StringExtractor reg_value_extractor;
1802 reg_value_extractor.GetStringRef() = pair.second;
1803 DataBufferSP buffer_sp(new DataBufferHeap(
1804 reg_value_extractor.GetStringRef().size() / 2, 0));
1805 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1806 gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
1807 }
1808
1809 thread_sp->SetName(thread_name.empty() ? NULL : thread_name.c_str());
1810
1811 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1812 // Check if the GDB server was able to provide the queue name, kind and
1813 // serial number
1814 if (queue_vars_valid)
1815 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1816 queue_serial, dispatch_queue_t,
1817 associated_with_dispatch_queue);
1818 else
1819 gdb_thread->ClearQueueInfo();
1820
1821 gdb_thread->SetAssociatedWithLibdispatchQueue(
1822 associated_with_dispatch_queue);
1823
1824 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1825 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1826
1827 // Make sure we update our thread stop reason just once
1828 if (!thread_sp->StopInfoIsUpToDate()) {
1829 thread_sp->SetStopInfo(StopInfoSP());
1830 // If there's a memory thread backed by this thread, we need to use it
1831 // to calcualte StopInfo.
1832 ThreadSP memory_thread_sp =
1833 m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
1834 if (memory_thread_sp)
1835 thread_sp = memory_thread_sp;
1836
1837 if (exc_type != 0) {
1838 const size_t exc_data_size = exc_data.size();
1839
1840 thread_sp->SetStopInfo(
1841 StopInfoMachException::CreateStopReasonWithMachException(
1842 *thread_sp, exc_type, exc_data_size,
1843 exc_data_size >= 1 ? exc_data[0] : 0,
1844 exc_data_size >= 2 ? exc_data[1] : 0,
1845 exc_data_size >= 3 ? exc_data[2] : 0));
1846 } else {
1847 bool handled = false;
1848 bool did_exec = false;
1849 if (!reason.empty()) {
1850 if (reason.compare("trace") == 0) {
1851 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1852 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1853 ->GetBreakpointSiteList()
1854 .FindByAddress(pc);
1855
1856 // If the current pc is a breakpoint site then the StopInfo should
1857 // be set to Breakpoint
1858 // Otherwise, it will be set to Trace.
1859 if (bp_site_sp &&
1860 bp_site_sp->ValidForThisThread(thread_sp.get())) {
1861 thread_sp->SetStopInfo(
1862 StopInfo::CreateStopReasonWithBreakpointSiteID(
1863 *thread_sp, bp_site_sp->GetID()));
1864 } else
1865 thread_sp->SetStopInfo(
1866 StopInfo::CreateStopReasonToTrace(*thread_sp));
1867 handled = true;
1868 } else if (reason.compare("breakpoint") == 0) {
1869 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1870 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1871 ->GetBreakpointSiteList()
1872 .FindByAddress(pc);
1873 if (bp_site_sp) {
1874 // If the breakpoint is for this thread, then we'll report the
1875 // hit, but if it is for another thread,
1876 // we can just report no reason. We don't need to worry about
1877 // stepping over the breakpoint here, that
1878 // will be taken care of when the thread resumes and notices
1879 // that there's a breakpoint under the pc.
1880 handled = true;
1881 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1882 thread_sp->SetStopInfo(
1883 StopInfo::CreateStopReasonWithBreakpointSiteID(
1884 *thread_sp, bp_site_sp->GetID()));
1885 } else {
1886 StopInfoSP invalid_stop_info_sp;
1887 thread_sp->SetStopInfo(invalid_stop_info_sp);
Jason Molenda545304d2015-12-18 00:45:35 +00001888 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001889 }
1890 } else if (reason.compare("trap") == 0) {
1891 // Let the trap just use the standard signal stop reason below...
1892 } else if (reason.compare("watchpoint") == 0) {
1893 StringExtractor desc_extractor(description.c_str());
1894 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1895 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1896 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1897 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1898 if (wp_addr != LLDB_INVALID_ADDRESS) {
1899 WatchpointSP wp_sp;
1900 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1901 if ((core >= ArchSpec::kCore_mips_first &&
1902 core <= ArchSpec::kCore_mips_last) ||
1903 (core >= ArchSpec::eCore_arm_generic &&
1904 core <= ArchSpec::eCore_arm_aarch64))
1905 wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1906 wp_hit_addr);
1907 if (!wp_sp)
1908 wp_sp =
1909 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1910 if (wp_sp) {
1911 wp_sp->SetHardwareIndex(wp_index);
1912 watch_id = wp_sp->GetID();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001913 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001914 }
1915 if (watch_id == LLDB_INVALID_WATCH_ID) {
1916 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1917 GDBR_LOG_WATCHPOINTS));
1918 if (log)
1919 log->Printf("failed to find watchpoint");
1920 }
1921 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1922 *thread_sp, watch_id, wp_hit_addr));
1923 handled = true;
1924 } else if (reason.compare("exception") == 0) {
1925 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1926 *thread_sp, description.c_str()));
1927 handled = true;
1928 } else if (reason.compare("exec") == 0) {
1929 did_exec = true;
1930 thread_sp->SetStopInfo(
1931 StopInfo::CreateStopReasonWithExec(*thread_sp));
1932 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001933 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001934 } else if (!signo) {
1935 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1936 lldb::BreakpointSiteSP bp_site_sp =
1937 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1938 pc);
Greg Clayton2e309072015-07-17 23:42:28 +00001939
Kate Stoneb9c1b512016-09-06 20:57:50 +00001940 // If the current pc is a breakpoint site then the StopInfo should
1941 // be set to Breakpoint
1942 // even though the remote stub did not set it as such. This can
1943 // happen when
1944 // the thread is involuntarily interrupted (e.g. due to stops on
1945 // other
1946 // threads) just as it is about to execute the breakpoint
1947 // instruction.
1948 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
1949 thread_sp->SetStopInfo(
1950 StopInfo::CreateStopReasonWithBreakpointSiteID(
1951 *thread_sp, bp_site_sp->GetID()));
1952 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001953 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001954 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001955
Kate Stoneb9c1b512016-09-06 20:57:50 +00001956 if (!handled && signo && did_exec == false) {
1957 if (signo == SIGTRAP) {
1958 // Currently we are going to assume SIGTRAP means we are either
1959 // hitting a breakpoint or hardware single stepping.
1960 handled = true;
1961 addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1962 m_breakpoint_pc_offset;
1963 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1964 ->GetBreakpointSiteList()
1965 .FindByAddress(pc);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001966
Kate Stoneb9c1b512016-09-06 20:57:50 +00001967 if (bp_site_sp) {
1968 // If the breakpoint is for this thread, then we'll report the
1969 // hit, but if it is for another thread,
1970 // we can just report no reason. We don't need to worry about
1971 // stepping over the breakpoint here, that
1972 // will be taken care of when the thread resumes and notices
1973 // that there's a breakpoint under the pc.
1974 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1975 if (m_breakpoint_pc_offset != 0)
1976 thread_sp->GetRegisterContext()->SetPC(pc);
1977 thread_sp->SetStopInfo(
1978 StopInfo::CreateStopReasonWithBreakpointSiteID(
1979 *thread_sp, bp_site_sp->GetID()));
1980 } else {
1981 StopInfoSP invalid_stop_info_sp;
1982 thread_sp->SetStopInfo(invalid_stop_info_sp);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001983 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984 } else {
1985 // If we were stepping then assume the stop was the result of
1986 // the trace. If we were
1987 // not stepping then report the SIGTRAP.
1988 // FIXME: We are still missing the case where we single step
1989 // over a trap instruction.
1990 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1991 thread_sp->SetStopInfo(
1992 StopInfo::CreateStopReasonToTrace(*thread_sp));
Greg Clayton2e309072015-07-17 23:42:28 +00001993 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001994 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1995 *thread_sp, signo, description.c_str()));
1996 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001997 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001998 if (!handled)
1999 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2000 *thread_sp, signo, description.c_str()));
2001 }
2002
2003 if (!description.empty()) {
2004 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
2005 if (stop_info_sp) {
2006 const char *stop_info_desc = stop_info_sp->GetDescription();
2007 if (!stop_info_desc || !stop_info_desc[0])
2008 stop_info_sp->SetDescription(description.c_str());
2009 } else {
2010 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2011 *thread_sp, description.c_str()));
2012 }
2013 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002014 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002015 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002016 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002017 }
2018 return thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002019}
2020
Greg Clayton2e309072015-07-17 23:42:28 +00002021lldb::ThreadSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00002022ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
2023 static ConstString g_key_tid("tid");
2024 static ConstString g_key_name("name");
2025 static ConstString g_key_reason("reason");
2026 static ConstString g_key_metype("metype");
2027 static ConstString g_key_medata("medata");
2028 static ConstString g_key_qaddr("qaddr");
2029 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2030 static ConstString g_key_associated_with_dispatch_queue(
2031 "associated_with_dispatch_queue");
2032 static ConstString g_key_queue_name("qname");
2033 static ConstString g_key_queue_kind("qkind");
2034 static ConstString g_key_queue_serial_number("qserialnum");
2035 static ConstString g_key_registers("registers");
2036 static ConstString g_key_memory("memory");
2037 static ConstString g_key_address("address");
2038 static ConstString g_key_bytes("bytes");
2039 static ConstString g_key_description("description");
2040 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002041
Kate Stoneb9c1b512016-09-06 20:57:50 +00002042 // Stop with signal and thread info
2043 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2044 uint8_t signo = 0;
2045 std::string value;
2046 std::string thread_name;
2047 std::string reason;
2048 std::string description;
2049 uint32_t exc_type = 0;
2050 std::vector<addr_t> exc_data;
2051 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2052 ExpeditedRegisterMap expedited_register_map;
2053 bool queue_vars_valid = false;
2054 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2055 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2056 std::string queue_name;
2057 QueueKind queue_kind = eQueueKindUnknown;
2058 uint64_t queue_serial_number = 0;
2059 // Iterate through all of the thread dictionary key/value pairs from the
2060 // structured data dictionary
2061
2062 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2063 &signo, &reason, &description, &exc_type, &exc_data,
2064 &thread_dispatch_qaddr, &queue_vars_valid,
2065 &associated_with_dispatch_queue, &dispatch_queue_t,
2066 &queue_name, &queue_kind, &queue_serial_number](
2067 ConstString key,
2068 StructuredData::Object *object) -> bool {
2069 if (key == g_key_tid) {
2070 // thread in big endian hex
2071 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2072 } else if (key == g_key_metype) {
2073 // exception type in big endian hex
2074 exc_type = object->GetIntegerValue(0);
2075 } else if (key == g_key_medata) {
2076 // exception data in big endian hex
2077 StructuredData::Array *array = object->GetAsArray();
2078 if (array) {
2079 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2080 exc_data.push_back(object->GetIntegerValue());
2081 return true; // Keep iterating through all array items
2082 });
2083 }
2084 } else if (key == g_key_name) {
2085 thread_name = object->GetStringValue();
2086 } else if (key == g_key_qaddr) {
2087 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2088 } else if (key == g_key_queue_name) {
2089 queue_vars_valid = true;
2090 queue_name = object->GetStringValue();
2091 } else if (key == g_key_queue_kind) {
2092 std::string queue_kind_str = object->GetStringValue();
2093 if (queue_kind_str == "serial") {
2094 queue_vars_valid = true;
2095 queue_kind = eQueueKindSerial;
2096 } else if (queue_kind_str == "concurrent") {
2097 queue_vars_valid = true;
2098 queue_kind = eQueueKindConcurrent;
2099 }
2100 } else if (key == g_key_queue_serial_number) {
2101 queue_serial_number = object->GetIntegerValue(0);
2102 if (queue_serial_number != 0)
2103 queue_vars_valid = true;
2104 } else if (key == g_key_dispatch_queue_t) {
2105 dispatch_queue_t = object->GetIntegerValue(0);
2106 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2107 queue_vars_valid = true;
2108 } else if (key == g_key_associated_with_dispatch_queue) {
2109 queue_vars_valid = true;
2110 bool associated = object->GetBooleanValue();
2111 if (associated)
2112 associated_with_dispatch_queue = eLazyBoolYes;
2113 else
2114 associated_with_dispatch_queue = eLazyBoolNo;
2115 } else if (key == g_key_reason) {
2116 reason = object->GetStringValue();
2117 } else if (key == g_key_description) {
2118 description = object->GetStringValue();
2119 } else if (key == g_key_registers) {
2120 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2121
2122 if (registers_dict) {
2123 registers_dict->ForEach(
2124 [&expedited_register_map](ConstString key,
2125 StructuredData::Object *object) -> bool {
2126 const uint32_t reg =
2127 StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
2128 if (reg != UINT32_MAX)
2129 expedited_register_map[reg] = object->GetStringValue();
2130 return true; // Keep iterating through all array items
2131 });
2132 }
2133 } else if (key == g_key_memory) {
2134 StructuredData::Array *array = object->GetAsArray();
2135 if (array) {
2136 array->ForEach([this](StructuredData::Object *object) -> bool {
2137 StructuredData::Dictionary *mem_cache_dict =
2138 object->GetAsDictionary();
2139 if (mem_cache_dict) {
2140 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2141 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2142 "address", mem_cache_addr)) {
2143 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
Zachary Turner28333212017-05-12 05:49:54 +00002144 llvm::StringRef str;
2145 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2146 StringExtractor bytes(str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002147 bytes.SetFilePos(0);
2148
2149 const size_t byte_size = bytes.GetStringRef().size() / 2;
2150 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2151 const size_t bytes_copied =
2152 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2153 if (bytes_copied == byte_size)
2154 m_memory_cache.AddL1CacheData(mem_cache_addr,
2155 data_buffer_sp);
2156 }
2157 }
2158 }
2159 }
2160 return true; // Keep iterating through all array items
2161 });
2162 }
2163
2164 } else if (key == g_key_signal)
2165 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2166 return true; // Keep iterating through all dictionary key/value pairs
2167 });
2168
2169 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2170 reason, description, exc_type, exc_data,
2171 thread_dispatch_qaddr, queue_vars_valid,
2172 associated_with_dispatch_queue, dispatch_queue_t,
2173 queue_name, queue_kind, queue_serial_number);
2174}
2175
2176StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2177 stop_packet.SetFilePos(0);
2178 const char stop_type = stop_packet.GetChar();
2179 switch (stop_type) {
2180 case 'T':
2181 case 'S': {
2182 // This is a bit of a hack, but is is required. If we did exec, we
2183 // need to clear our thread lists and also know to rebuild our dynamic
2184 // register info before we lookup and threads and populate the expedited
2185 // register values so we need to know this right away so we can cleanup
2186 // and update our registers.
2187 const uint32_t stop_id = GetStopID();
2188 if (stop_id == 0) {
2189 // Our first stop, make sure we have a process ID, and also make
2190 // sure we know about our registers
2191 if (GetID() == LLDB_INVALID_PROCESS_ID) {
2192 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2193 if (pid != LLDB_INVALID_PROCESS_ID)
2194 SetID(pid);
2195 }
2196 BuildDynamicRegisterInfo(true);
2197 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002198 // Stop with signal and thread info
2199 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200 const uint8_t signo = stop_packet.GetHexU8();
2201 llvm::StringRef key;
2202 llvm::StringRef value;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002203 std::string thread_name;
2204 std::string reason;
2205 std::string description;
2206 uint32_t exc_type = 0;
2207 std::vector<addr_t> exc_data;
2208 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002209 bool queue_vars_valid =
2210 false; // says if locals below that start with "queue_" are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002211 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2212 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002213 std::string queue_name;
2214 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002215 uint64_t queue_serial_number = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002216 ExpeditedRegisterMap expedited_register_map;
2217 while (stop_packet.GetNameColonValue(key, value)) {
2218 if (key.compare("metype") == 0) {
2219 // exception type in big endian hex
2220 value.getAsInteger(16, exc_type);
2221 } else if (key.compare("medata") == 0) {
2222 // exception data in big endian hex
2223 uint64_t x;
2224 value.getAsInteger(16, x);
2225 exc_data.push_back(x);
2226 } else if (key.compare("thread") == 0) {
2227 // thread in big endian hex
2228 if (value.getAsInteger(16, tid))
2229 tid = LLDB_INVALID_THREAD_ID;
2230 } else if (key.compare("threads") == 0) {
2231 std::lock_guard<std::recursive_mutex> guard(
2232 m_thread_list_real.GetMutex());
Greg Clayton358cf1e2015-06-25 21:46:34 +00002233
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 m_thread_ids.clear();
2235 // A comma separated list of all threads in the current
2236 // process that includes the thread for this stop reply
2237 // packet
2238 lldb::tid_t tid;
2239 while (!value.empty()) {
2240 llvm::StringRef tid_str;
2241 std::tie(tid_str, value) = value.split(',');
2242 if (tid_str.getAsInteger(16, tid))
2243 tid = LLDB_INVALID_THREAD_ID;
2244 m_thread_ids.push_back(tid);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002245 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002246 } else if (key.compare("thread-pcs") == 0) {
2247 m_thread_pcs.clear();
2248 // A comma separated list of all threads in the current
2249 // process that includes the thread for this stop reply
2250 // packet
2251 lldb::addr_t pc;
2252 while (!value.empty()) {
2253 llvm::StringRef pc_str;
2254 std::tie(pc_str, value) = value.split(',');
2255 if (pc_str.getAsInteger(16, pc))
2256 pc = LLDB_INVALID_ADDRESS;
2257 m_thread_pcs.push_back(pc);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002258 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002259 } else if (key.compare("jstopinfo") == 0) {
2260 StringExtractor json_extractor(value);
2261 std::string json;
2262 // Now convert the HEX bytes into a string value
2263 json_extractor.GetHexByteString(json);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002264
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265 // This JSON contains thread IDs and thread stop info for all threads.
2266 // It doesn't contain expedited registers, memory or queue info.
2267 m_jstopinfo_sp = StructuredData::ParseJSON(json);
2268 } else if (key.compare("hexname") == 0) {
2269 StringExtractor name_extractor(value);
2270 std::string name;
2271 // Now convert the HEX bytes into a string value
2272 name_extractor.GetHexByteString(thread_name);
2273 } else if (key.compare("name") == 0) {
2274 thread_name = value;
2275 } else if (key.compare("qaddr") == 0) {
2276 value.getAsInteger(16, thread_dispatch_qaddr);
2277 } else if (key.compare("dispatch_queue_t") == 0) {
2278 queue_vars_valid = true;
2279 value.getAsInteger(16, dispatch_queue_t);
2280 } else if (key.compare("qname") == 0) {
2281 queue_vars_valid = true;
2282 StringExtractor name_extractor(value);
2283 // Now convert the HEX bytes into a string value
2284 name_extractor.GetHexByteString(queue_name);
2285 } else if (key.compare("qkind") == 0) {
2286 queue_kind = llvm::StringSwitch<QueueKind>(value)
2287 .Case("serial", eQueueKindSerial)
2288 .Case("concurrent", eQueueKindConcurrent)
2289 .Default(eQueueKindUnknown);
2290 queue_vars_valid = queue_kind != eQueueKindUnknown;
2291 } else if (key.compare("qserialnum") == 0) {
2292 if (!value.getAsInteger(0, queue_serial_number))
2293 queue_vars_valid = true;
2294 } else if (key.compare("reason") == 0) {
2295 reason = value;
2296 } else if (key.compare("description") == 0) {
2297 StringExtractor desc_extractor(value);
2298 // Now convert the HEX bytes into a string value
2299 desc_extractor.GetHexByteString(description);
2300 } else if (key.compare("memory") == 0) {
2301 // Expedited memory. GDB servers can choose to send back expedited
2302 // memory
2303 // that can populate the L1 memory cache in the process so that things
2304 // like
2305 // the frame pointer backchain can be expedited. This will help stack
2306 // backtracing be more efficient by not having to send as many memory
2307 // read
2308 // requests down the remote GDB server.
2309
2310 // Key/value pair format: memory:<addr>=<bytes>;
2311 // <addr> is a number whose base will be interpreted by the prefix:
2312 // "0x[0-9a-fA-F]+" for hex
2313 // "0[0-7]+" for octal
2314 // "[1-9]+" for decimal
2315 // <bytes> is native endian ASCII hex bytes just like the register
2316 // values
2317 llvm::StringRef addr_str, bytes_str;
2318 std::tie(addr_str, bytes_str) = value.split('=');
2319 if (!addr_str.empty() && !bytes_str.empty()) {
2320 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2321 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2322 StringExtractor bytes(bytes_str);
2323 const size_t byte_size = bytes.GetBytesLeft() / 2;
2324 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2325 const size_t bytes_copied =
2326 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2327 if (bytes_copied == byte_size)
2328 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2329 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002330 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002331 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2332 key.compare("awatch") == 0) {
2333 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2334 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2335 value.getAsInteger(16, wp_addr);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002336
Kate Stoneb9c1b512016-09-06 20:57:50 +00002337 WatchpointSP wp_sp =
2338 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2339 uint32_t wp_index = LLDB_INVALID_INDEX32;
Eugene Zelenko0722f082015-10-24 01:28:05 +00002340
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341 if (wp_sp)
2342 wp_index = wp_sp->GetHardwareIndex();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002343
Kate Stoneb9c1b512016-09-06 20:57:50 +00002344 reason = "watchpoint";
2345 StreamString ostr;
2346 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002347 description = ostr.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002348 } else if (key.compare("library") == 0) {
2349 LoadModules();
2350 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2351 uint32_t reg = UINT32_MAX;
2352 if (!key.getAsInteger(16, reg))
2353 expedited_register_map[reg] = std::move(value);
2354 }
2355 }
2356
2357 if (tid == LLDB_INVALID_THREAD_ID) {
2358 // A thread id may be invalid if the response is old style 'S' packet
2359 // which does not provide the
2360 // thread information. So update the thread list and choose the first one.
2361 UpdateThreadIDList();
2362
2363 if (!m_thread_ids.empty()) {
2364 tid = m_thread_ids.front();
2365 }
2366 }
2367
2368 ThreadSP thread_sp = SetThreadStopInfo(
2369 tid, expedited_register_map, signo, thread_name, reason, description,
2370 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2371 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2372 queue_kind, queue_serial_number);
2373
2374 return eStateStopped;
2375 } break;
2376
2377 case 'W':
2378 case 'X':
2379 // process exited
2380 return eStateExited;
2381
2382 default:
2383 break;
2384 }
2385 return eStateInvalid;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002386}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002387
Kate Stoneb9c1b512016-09-06 20:57:50 +00002388void ProcessGDBRemote::RefreshStateAfterStop() {
2389 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002390
Kate Stoneb9c1b512016-09-06 20:57:50 +00002391 m_thread_ids.clear();
2392 m_thread_pcs.clear();
2393 // Set the thread stop info. It might have a "threads" key whose value is
2394 // a list of all thread IDs in the current process, so m_thread_ids might
2395 // get set.
Greg Claytona5801ad2015-07-15 22:59:03 +00002396
Kate Stoneb9c1b512016-09-06 20:57:50 +00002397 // Scope for the lock
2398 {
2399 // Lock the thread stack while we access it
2400 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2401 // Get the number of stop packets on the stack
2402 int nItems = m_stop_packet_stack.size();
2403 // Iterate over them
2404 for (int i = 0; i < nItems; i++) {
2405 // Get the thread stop info
2406 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2407 // Process thread stop info
2408 SetThreadStopInfo(stop_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002409 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 // Clear the thread stop stack
2411 m_stop_packet_stack.clear();
2412 }
2413
2414 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2415 if (m_thread_ids.empty()) {
2416 // No, we need to fetch the thread list manually
2417 UpdateThreadIDList();
2418 }
2419
2420 // If we have queried for a default thread id
2421 if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2422 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2423 m_initial_tid = LLDB_INVALID_THREAD_ID;
2424 }
2425
2426 // Let all threads recover from stopping and do any clean up based
2427 // on the previous thread state (if any).
2428 m_thread_list_real.RefreshStateAfterStop();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429}
2430
Zachary Turner97206d52017-05-12 04:51:55 +00002431Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2432 Status error;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002433
Kate Stoneb9c1b512016-09-06 20:57:50 +00002434 if (m_public_state.GetValue() == eStateAttaching) {
2435 // We are being asked to halt during an attach. We need to just close
2436 // our file handle and debugserver will go away, and we can be done...
2437 m_gdb_comm.Disconnect();
2438 } else
2439 caused_stop = m_gdb_comm.Interrupt();
2440 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002441}
2442
Zachary Turner97206d52017-05-12 04:51:55 +00002443Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2444 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002445 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2446 if (log)
2447 log->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002448
Kate Stoneb9c1b512016-09-06 20:57:50 +00002449 error = m_gdb_comm.Detach(keep_stopped);
2450 if (log) {
2451 if (error.Success())
2452 log->PutCString(
2453 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
Greg Clayton513c26c2011-01-29 07:10:55 +00002454 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002455 log->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2456 error.AsCString() ? error.AsCString() : "<unknown error>");
2457 }
2458
2459 if (!error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002460 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002461
2462 // Sleep for one second to let the process get all detached...
2463 StopAsyncThread();
2464
2465 SetPrivateState(eStateDetached);
2466 ResumePrivateStateThread();
2467
2468 // KillDebugserverProcess ();
2469 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002470}
2471
Zachary Turner97206d52017-05-12 04:51:55 +00002472Status ProcessGDBRemote::DoDestroy() {
2473 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002474 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2475 if (log)
2476 log->Printf("ProcessGDBRemote::DoDestroy()");
Ed Maste81b4c5f2016-01-04 01:43:47 +00002477
Kate Stoneb9c1b512016-09-06 20:57:50 +00002478 // There is a bug in older iOS debugservers where they don't shut down the
2479 // process
2480 // they are debugging properly. If the process is sitting at a breakpoint or
2481 // an exception,
2482 // this can cause problems with restarting. So we check to see if any of our
2483 // threads are stopped
2484 // at a breakpoint, and if so we remove all the breakpoints, resume the
2485 // process, and THEN
2486 // destroy it again.
2487 //
2488 // Note, we don't have a good way to test the version of debugserver, but I
2489 // happen to know that
2490 // the set of all the iOS debugservers which don't support
2491 // GetThreadSuffixSupported() and that of
2492 // the debugservers with this bug are equal. There really should be a better
2493 // way to test this!
2494 //
2495 // We also use m_destroy_tried_resuming to make sure we only do this once, if
2496 // we resume and then halt and
2497 // get called here to destroy again and we're still at a breakpoint or
2498 // exception, then we should
2499 // just do the straight-forward kill.
2500 //
2501 // And of course, if we weren't able to stop the process by the time we get
2502 // here, it isn't
2503 // necessary (or helpful) to do any of this.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002504
Kate Stoneb9c1b512016-09-06 20:57:50 +00002505 if (!m_gdb_comm.GetThreadSuffixSupported() &&
2506 m_public_state.GetValue() != eStateRunning) {
2507 PlatformSP platform_sp = GetTarget().GetPlatform();
Jim Inghamacff8952013-05-02 00:27:30 +00002508
Kate Stoneb9c1b512016-09-06 20:57:50 +00002509 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2510 if (platform_sp && platform_sp->GetName() &&
2511 platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2512 if (m_destroy_tried_resuming) {
Greg Clayton8cda7f02013-05-21 21:55:59 +00002513 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514 log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2515 "destroy once already, not doing it again.");
2516 } else {
2517 // At present, the plans are discarded and the breakpoints disabled
2518 // Process::Destroy,
2519 // but we really need it to happen here and it doesn't matter if we do
2520 // it twice.
2521 m_thread_list.DiscardThreadPlans();
2522 DisableAllBreakpointSites();
Greg Clayton8cda7f02013-05-21 21:55:59 +00002523
Kate Stoneb9c1b512016-09-06 20:57:50 +00002524 bool stop_looks_like_crash = false;
2525 ThreadList &threads = GetThreadList();
2526
2527 {
2528 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2529
2530 size_t num_threads = threads.GetSize();
2531 for (size_t i = 0; i < num_threads; i++) {
2532 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2533 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2534 StopReason reason = eStopReasonInvalid;
2535 if (stop_info_sp)
2536 reason = stop_info_sp->GetStopReason();
2537 if (reason == eStopReasonBreakpoint ||
2538 reason == eStopReasonException) {
2539 if (log)
2540 log->Printf(
2541 "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2542 " stopped with reason: %s.",
2543 thread_sp->GetProtocolID(), stop_info_sp->GetDescription());
2544 stop_looks_like_crash = true;
2545 break;
2546 }
2547 }
2548 }
2549
2550 if (stop_looks_like_crash) {
2551 if (log)
2552 log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2553 "breakpoint, continue and then kill.");
2554 m_destroy_tried_resuming = true;
2555
2556 // If we are going to run again before killing, it would be good to
2557 // suspend all the threads
2558 // before resuming so they won't get into more trouble. Sadly, for
2559 // the threads stopped with
2560 // the breakpoint or exception, the exception doesn't get cleared if
2561 // it is suspended, so we do
2562 // have to run the risk of letting those threads proceed a bit.
2563
2564 {
2565 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2566
2567 size_t num_threads = threads.GetSize();
2568 for (size_t i = 0; i < num_threads; i++) {
2569 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2570 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2571 StopReason reason = eStopReasonInvalid;
2572 if (stop_info_sp)
2573 reason = stop_info_sp->GetStopReason();
2574 if (reason != eStopReasonBreakpoint &&
2575 reason != eStopReasonException) {
2576 if (log)
2577 log->Printf("ProcessGDBRemote::DoDestroy() - Suspending "
2578 "thread: 0x%4.4" PRIx64 " before running.",
2579 thread_sp->GetProtocolID());
2580 thread_sp->SetResumeState(eStateSuspended);
2581 }
2582 }
2583 }
2584 Resume();
2585 return Destroy(false);
2586 }
2587 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002588 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002589 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002590
Kate Stoneb9c1b512016-09-06 20:57:50 +00002591 // Interrupt if our inferior is running...
2592 int exit_status = SIGABRT;
2593 std::string exit_string;
Greg Clayton2e309072015-07-17 23:42:28 +00002594
Kate Stoneb9c1b512016-09-06 20:57:50 +00002595 if (m_gdb_comm.IsConnected()) {
2596 if (m_public_state.GetValue() != eStateAttaching) {
2597 StringExtractorGDBRemote response;
2598 bool send_async = true;
Pavel Labath3aa04912016-10-31 17:19:42 +00002599 GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2600 std::chrono::seconds(3));
Greg Clayton2e309072015-07-17 23:42:28 +00002601
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002602 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002603 GDBRemoteCommunication::PacketResult::Success) {
2604 char packet_cmd = response.GetChar(0);
2605
2606 if (packet_cmd == 'W' || packet_cmd == 'X') {
2607#if defined(__APPLE__)
2608 // For Native processes on Mac OS X, we launch through the Host
2609 // Platform, then hand the process off
2610 // to debugserver, which becomes the parent process through
2611 // "PT_ATTACH". Then when we go to kill
2612 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we
2613 // call waitpid which returns
2614 // with no error and the correct status. But amusingly enough that
2615 // doesn't seem to actually reap
2616 // the process, but instead it is left around as a Zombie. Probably
2617 // the kernel is in the process of
2618 // switching ownership back to lldb which was the original parent, and
2619 // gets confused in the handoff.
2620 // Anyway, so call waitpid here to finally reap it.
2621 PlatformSP platform_sp(GetTarget().GetPlatform());
2622 if (platform_sp && platform_sp->IsHost()) {
2623 int status;
2624 ::pid_t reap_pid;
2625 reap_pid = waitpid(GetID(), &status, WNOHANG);
2626 if (log)
2627 log->Printf("Reaped pid: %d, status: %d.\n", reap_pid, status);
2628 }
2629#endif
2630 SetLastStopPacket(response);
2631 ClearThreadIDList();
2632 exit_status = response.GetHexU8();
2633 } else {
2634 if (log)
2635 log->Printf("ProcessGDBRemote::DoDestroy - got unexpected response "
2636 "to k packet: %s",
2637 response.GetStringRef().c_str());
2638 exit_string.assign("got unexpected response to k packet: ");
2639 exit_string.append(response.GetStringRef());
2640 }
2641 } else {
2642 if (log)
2643 log->Printf("ProcessGDBRemote::DoDestroy - failed to send k packet");
2644 exit_string.assign("failed to send the k packet");
2645 }
2646 } else {
2647 if (log)
2648 log->Printf("ProcessGDBRemote::DoDestroy - killed or interrupted while "
2649 "attaching");
2650 exit_string.assign("killed or interrupted while attaching.");
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002651 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002652 } else {
2653 // If we missed setting the exit status on the way out, do it here.
2654 // NB set exit status can be called multiple times, the first one sets the
2655 // status.
2656 exit_string.assign("destroying when not connected to debugserver");
2657 }
2658
2659 SetExitStatus(exit_status, exit_string.c_str());
2660
2661 StopAsyncThread();
2662 KillDebugserverProcess();
2663 return error;
Greg Clayton8cda7f02013-05-21 21:55:59 +00002664}
2665
Kate Stoneb9c1b512016-09-06 20:57:50 +00002666void ProcessGDBRemote::SetLastStopPacket(
2667 const StringExtractorGDBRemote &response) {
2668 const bool did_exec =
2669 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2670 if (did_exec) {
2671 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2672 if (log)
2673 log->Printf("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2674
2675 m_thread_list_real.Clear();
2676 m_thread_list.Clear();
2677 BuildDynamicRegisterInfo(true);
2678 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2679 }
2680
2681 // Scope the lock
2682 {
2683 // Lock the thread stack while we access it
2684 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2685
2686 // We are are not using non-stop mode, there can only be one last stop
2687 // reply packet, so clear the list.
2688 if (GetTarget().GetNonStopModeEnabled() == false)
2689 m_stop_packet_stack.clear();
2690
2691 // Add this stop packet to the stop packet stack
2692 // This stack will get popped and examined when we switch to the
2693 // Stopped state
2694 m_stop_packet_stack.push_back(response);
2695 }
2696}
2697
2698void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2699 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
Chaoren Linc963a222015-09-01 16:58:45 +00002700}
2701
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002702//------------------------------------------------------------------
2703// Process Queries
2704//------------------------------------------------------------------
2705
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706bool ProcessGDBRemote::IsAlive() {
2707 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002708}
2709
Kate Stoneb9c1b512016-09-06 20:57:50 +00002710addr_t ProcessGDBRemote::GetImageInfoAddress() {
2711 // request the link map address via the $qShlibInfoAddr packet
2712 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
Aidan Doddsc0c83852015-05-08 09:36:31 +00002713
Kate Stoneb9c1b512016-09-06 20:57:50 +00002714 // the loaded module list can also provides a link map address
2715 if (addr == LLDB_INVALID_ADDRESS) {
2716 LoadedModuleInfoList list;
2717 if (GetLoadedModuleList(list).Success())
2718 addr = list.m_link_map;
2719 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00002720
Kate Stoneb9c1b512016-09-06 20:57:50 +00002721 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002722}
2723
Kate Stoneb9c1b512016-09-06 20:57:50 +00002724void ProcessGDBRemote::WillPublicStop() {
2725 // See if the GDB remote client supports the JSON threads info.
2726 // If so, we gather stop info for all threads, expedited registers,
2727 // expedited memory, runtime queue information (iOS and MacOSX only),
2728 // and more. Expediting memory will help stack backtracing be much
2729 // faster. Expediting registers will make sure we don't have to read
2730 // the thread registers for GPRs.
2731 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
Greg Clayton2e309072015-07-17 23:42:28 +00002732
Kate Stoneb9c1b512016-09-06 20:57:50 +00002733 if (m_jthreadsinfo_sp) {
2734 // Now set the stop info for each thread and also expedite any registers
2735 // and memory that was in the jThreadsInfo response.
2736 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2737 if (thread_infos) {
2738 const size_t n = thread_infos->GetSize();
2739 for (size_t i = 0; i < n; ++i) {
2740 StructuredData::Dictionary *thread_dict =
2741 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2742 if (thread_dict)
2743 SetThreadStopInfo(thread_dict);
2744 }
Greg Clayton2e309072015-07-17 23:42:28 +00002745 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002746 }
Greg Clayton2e309072015-07-17 23:42:28 +00002747}
2748
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002749//------------------------------------------------------------------
2750// Process Memory
2751//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002752size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002753 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002754 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002755 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2756 // M and m packets take 2 bytes for 1 byte of memory
2757 size_t max_memory_size =
2758 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2759 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 // Keep memory read sizes down to a sane limit. This function will be
2761 // called multiple times in order to complete the task by
2762 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002763 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002764 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002765
Kate Stoneb9c1b512016-09-06 20:57:50 +00002766 char packet[64];
2767 int packet_len;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002768 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2769 binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2770 (uint64_t)size);
2771 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002772 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002774 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002775 GDBRemoteCommunication::PacketResult::Success) {
2776 if (response.IsNormalResponse()) {
2777 error.Clear();
2778 if (binary_memory_read) {
2779 // The lower level GDBRemoteCommunication packet receive layer has
2780 // already de-quoted any
2781 // 0x7d character escaping that was present in the packet
Jason Molenda6076bf42014-05-06 04:34:52 +00002782
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 size_t data_received_size = response.GetBytesLeft();
2784 if (data_received_size > size) {
2785 // Don't write past the end of BUF if the remote debug server gave us
2786 // too
2787 // much data for some reason.
2788 data_received_size = size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002789 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 memcpy(buf, response.GetStringRef().data(), data_received_size);
2791 return data_received_size;
2792 } else {
2793 return response.GetHexBytes(
2794 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2795 }
2796 } else if (response.IsErrorResponse())
2797 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2798 else if (response.IsUnsupportedResponse())
2799 error.SetErrorStringWithFormat(
2800 "GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002801 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002802 error.SetErrorStringWithFormat(
2803 "unexpected response to GDB server memory read packet '%s': '%s'",
2804 packet, response.GetStringRef().c_str());
2805 } else {
2806 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2807 }
2808 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002809}
2810
Kate Stoneb9c1b512016-09-06 20:57:50 +00002811size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
Zachary Turner97206d52017-05-12 04:51:55 +00002812 size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002813 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002814 // M and m packets take 2 bytes for 1 byte of memory
2815 size_t max_memory_size = m_max_memory_size / 2;
2816 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817 // Keep memory read sizes down to a sane limit. This function will be
2818 // called multiple times in order to complete the task by
2819 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002820 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 }
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002822
Kate Stoneb9c1b512016-09-06 20:57:50 +00002823 StreamString packet;
2824 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2825 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2826 endian::InlHostByteOrder());
2827 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002828 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2829 true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 GDBRemoteCommunication::PacketResult::Success) {
2831 if (response.IsOKResponse()) {
2832 error.Clear();
2833 return size;
2834 } else if (response.IsErrorResponse())
2835 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2836 addr);
2837 else if (response.IsUnsupportedResponse())
2838 error.SetErrorStringWithFormat(
2839 "GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002840 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 error.SetErrorStringWithFormat(
2842 "unexpected response to GDB server memory write packet '%s': '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00002843 packet.GetData(), response.GetStringRef().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002844 } else {
2845 error.SetErrorStringWithFormat("failed to send packet: '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00002846 packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002847 }
2848 return 0;
2849}
2850
2851lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2852 uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002853 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002854 Log *log(
2855 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
2856 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2857
2858 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2859 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2860 if (allocated_addr != LLDB_INVALID_ADDRESS ||
2861 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2862 return allocated_addr;
2863 }
2864
2865 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2866 // Call mmap() to create memory in the inferior..
2867 unsigned prot = 0;
2868 if (permissions & lldb::ePermissionsReadable)
2869 prot |= eMmapProtRead;
2870 if (permissions & lldb::ePermissionsWritable)
2871 prot |= eMmapProtWrite;
2872 if (permissions & lldb::ePermissionsExecutable)
2873 prot |= eMmapProtExec;
2874
2875 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2876 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2877 m_addr_to_mmap_size[allocated_addr] = size;
2878 else {
2879 allocated_addr = LLDB_INVALID_ADDRESS;
2880 if (log)
2881 log->Printf("ProcessGDBRemote::%s no direct stub support for memory "
2882 "allocation, and InferiorCallMmap also failed - is stub "
2883 "missing register context save/restore capability?",
2884 __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002885 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002886 }
2887
2888 if (allocated_addr == LLDB_INVALID_ADDRESS)
2889 error.SetErrorStringWithFormat(
2890 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
2891 (uint64_t)size, GetPermissionsAsCString(permissions));
2892 else
2893 error.Clear();
2894 return allocated_addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002895}
2896
Zachary Turner97206d52017-05-12 04:51:55 +00002897Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
2898 MemoryRegionInfo &region_info) {
Ed Maste81b4c5f2016-01-04 01:43:47 +00002899
Zachary Turner97206d52017-05-12 04:51:55 +00002900 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 return error;
2902}
2903
Zachary Turner97206d52017-05-12 04:51:55 +00002904Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002905
Zachary Turner97206d52017-05-12 04:51:55 +00002906 Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002907 return error;
2908}
2909
Zachary Turner97206d52017-05-12 04:51:55 +00002910Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2911 Status error(m_gdb_comm.GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002912 num, after, GetTarget().GetArchitecture()));
2913 return error;
2914}
2915
Zachary Turner97206d52017-05-12 04:51:55 +00002916Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
2917 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002918 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2919
2920 switch (supported) {
2921 case eLazyBoolCalculate:
2922 // We should never be deallocating memory without allocating memory
2923 // first so we should never get eLazyBoolCalculate
2924 error.SetErrorString(
2925 "tried to deallocate memory without ever allocating memory");
2926 break;
2927
2928 case eLazyBoolYes:
2929 if (!m_gdb_comm.DeallocateMemory(addr))
2930 error.SetErrorStringWithFormat(
2931 "unable to deallocate memory at 0x%" PRIx64, addr);
2932 break;
2933
2934 case eLazyBoolNo:
2935 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2a48f522011-05-14 01:50:35 +00002936 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002937 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2938 if (pos != m_addr_to_mmap_size.end() &&
2939 InferiorCallMunmap(this, addr, pos->second))
2940 m_addr_to_mmap_size.erase(pos);
2941 else
2942 error.SetErrorStringWithFormat(
2943 "unable to deallocate memory at 0x%" PRIx64, addr);
Greg Claytoncec91ef2016-02-26 01:20:20 +00002944 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002945 break;
2946 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002947
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002949}
2950
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002951//------------------------------------------------------------------
2952// Process STDIO
2953//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002954size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002955 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 if (m_stdio_communication.IsConnected()) {
2957 ConnectionStatus status;
2958 m_stdio_communication.Write(src, src_len, status, NULL);
2959 } else if (m_stdin_forward) {
2960 m_gdb_comm.SendStdinNotification(src, src_len);
2961 }
2962 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002963}
2964
Zachary Turner97206d52017-05-12 04:51:55 +00002965Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
2966 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002967 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002968
Kate Stoneb9c1b512016-09-06 20:57:50 +00002969 // Get logging info
2970 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2971 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002972
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 // Get the breakpoint address
2974 const addr_t addr = bp_site->GetLoadAddress();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002975
Kate Stoneb9c1b512016-09-06 20:57:50 +00002976 // Log that a breakpoint was requested
2977 if (log)
2978 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2979 ") address = 0x%" PRIx64,
2980 site_id, (uint64_t)addr);
2981
2982 // Breakpoint already exists and is enabled
2983 if (bp_site->IsEnabled()) {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002984 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002985 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2986 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
2987 site_id, (uint64_t)addr);
2988 return error;
2989 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002990
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 // Get the software breakpoint trap opcode size
2992 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2993
2994 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
2995 // breakpoint type
2996 // is supported by the remote stub. These are set to true by default, and
2997 // later set to false
2998 // only after we receive an unimplemented response when sending a breakpoint
2999 // packet. This means
3000 // initially that unless we were specifically instructed to use a hardware
3001 // breakpoint, LLDB will
3002 // attempt to set a software breakpoint. HardwareRequired() also queries a
3003 // boolean variable which
3004 // indicates if the user specifically asked for hardware breakpoints. If true
3005 // then we will
3006 // skip over software breakpoints.
3007 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3008 (!bp_site->HardwareRequired())) {
3009 // Try to send off a software breakpoint packet ($Z0)
3010 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3011 eBreakpointSoftware, true, addr, bp_op_size);
3012 if (error_no == 0) {
3013 // The breakpoint was placed successfully
3014 bp_site->SetEnabled(true);
3015 bp_site->SetType(BreakpointSite::eExternal);
3016 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003017 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003018
Kate Stoneb9c1b512016-09-06 20:57:50 +00003019 // SendGDBStoppointTypePacket() will return an error if it was unable to set
3020 // this
3021 // breakpoint. We need to differentiate between a error specific to placing
3022 // this breakpoint
3023 // or if we have learned that this breakpoint type is unsupported. To do
3024 // this, we
3025 // must test the support boolean for this breakpoint type to see if it now
3026 // indicates that
3027 // this breakpoint type is unsupported. If they are still supported then we
3028 // should return
3029 // with the error code. If they are now unsupported, then we would like to
3030 // fall through
3031 // and try another form of breakpoint.
3032 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3033 if (error_no != UINT8_MAX)
3034 error.SetErrorStringWithFormat(
3035 "error: %d sending the breakpoint request", errno);
3036 else
3037 error.SetErrorString("error sending the breakpoint request");
3038 return error;
3039 }
3040
3041 // We reach here when software breakpoints have been found to be
3042 // unsupported. For future
3043 // calls to set a breakpoint, we will not attempt to set a breakpoint with a
3044 // type that is
3045 // known not to be supported.
3046 if (log)
3047 log->Printf("Software breakpoints are unsupported");
3048
3049 // So we will fall through and try a hardware breakpoint
3050 }
3051
3052 // The process of setting a hardware breakpoint is much the same as above. We
3053 // check the
3054 // supported boolean for this breakpoint type, and if it is thought to be
3055 // supported then we
3056 // will try to set this breakpoint with a hardware breakpoint.
3057 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3058 // Try to send off a hardware breakpoint packet ($Z1)
3059 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3060 eBreakpointHardware, true, addr, bp_op_size);
3061 if (error_no == 0) {
3062 // The breakpoint was placed successfully
3063 bp_site->SetEnabled(true);
3064 bp_site->SetType(BreakpointSite::eHardware);
3065 return error;
3066 }
3067
3068 // Check if the error was something other then an unsupported breakpoint
3069 // type
3070 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3071 // Unable to set this hardware breakpoint
3072 if (error_no != UINT8_MAX)
3073 error.SetErrorStringWithFormat(
3074 "error: %d sending the hardware breakpoint request "
3075 "(hardware breakpoint resources might be exhausted or unavailable)",
3076 error_no);
3077 else
3078 error.SetErrorString("error sending the hardware breakpoint request "
3079 "(hardware breakpoint resources "
3080 "might be exhausted or unavailable)");
3081 return error;
3082 }
3083
3084 // We will reach here when the stub gives an unsupported response to a
3085 // hardware breakpoint
3086 if (log)
3087 log->Printf("Hardware breakpoints are unsupported");
3088
3089 // Finally we will falling through to a #trap style breakpoint
3090 }
3091
3092 // Don't fall through when hardware breakpoints were specifically requested
3093 if (bp_site->HardwareRequired()) {
3094 error.SetErrorString("hardware breakpoints are not supported");
3095 return error;
3096 }
3097
3098 // As a last resort we want to place a manual breakpoint. An instruction
3099 // is placed into the process memory using memory write packets.
3100 return EnableSoftwareBreakpoint(bp_site);
3101}
3102
Zachary Turner97206d52017-05-12 04:51:55 +00003103Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3104 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003105 assert(bp_site != NULL);
3106 addr_t addr = bp_site->GetLoadAddress();
3107 user_id_t site_id = bp_site->GetID();
3108 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3109 if (log)
3110 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3111 ") addr = 0x%8.8" PRIx64,
3112 site_id, (uint64_t)addr);
3113
3114 if (bp_site->IsEnabled()) {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003115 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3116
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117 BreakpointSite::Type bp_type = bp_site->GetType();
3118 switch (bp_type) {
3119 case BreakpointSite::eSoftware:
3120 error = DisableSoftwareBreakpoint(bp_site);
3121 break;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003122
Kate Stoneb9c1b512016-09-06 20:57:50 +00003123 case BreakpointSite::eHardware:
3124 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3125 addr, bp_op_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003126 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003127 break;
3128
3129 case BreakpointSite::eExternal: {
3130 GDBStoppointType stoppoint_type;
3131 if (bp_site->IsHardware())
3132 stoppoint_type = eBreakpointHardware;
3133 else
3134 stoppoint_type = eBreakpointSoftware;
3135
3136 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr,
3137 bp_op_size))
3138 error.SetErrorToGenericError();
3139 } break;
3140 }
3141 if (error.Success())
3142 bp_site->SetEnabled(false);
3143 } else {
3144 if (log)
3145 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3146 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3147 site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003148 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003149 }
3150
3151 if (error.Success())
3152 error.SetErrorToGenericError();
3153 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003154}
3155
Johnny Chen11309a32011-09-06 22:38:36 +00003156// Pre-requisite: wp != NULL.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003157static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3158 assert(wp);
3159 bool watch_read = wp->WatchpointRead();
3160 bool watch_write = wp->WatchpointWrite();
Johnny Chen11309a32011-09-06 22:38:36 +00003161
Kate Stoneb9c1b512016-09-06 20:57:50 +00003162 // watch_read and watch_write cannot both be false.
3163 assert(watch_read || watch_write);
3164 if (watch_read && watch_write)
3165 return eWatchpointReadWrite;
3166 else if (watch_read)
3167 return eWatchpointRead;
3168 else // Must be watch_write, then.
3169 return eWatchpointWrite;
Johnny Chen11309a32011-09-06 22:38:36 +00003170}
3171
Zachary Turner97206d52017-05-12 04:51:55 +00003172Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3173 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003174 if (wp) {
3175 user_id_t watchID = wp->GetID();
3176 addr_t addr = wp->GetLoadAddress();
3177 Log *log(
3178 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003179 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003180 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3181 watchID);
3182 if (wp->IsEnabled()) {
3183 if (log)
3184 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3185 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3186 watchID, (uint64_t)addr);
3187 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003188 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003189
3190 GDBStoppointType type = GetGDBStoppointType(wp);
3191 // Pass down an appropriate z/Z packet...
3192 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3193 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3194 wp->GetByteSize()) == 0) {
3195 wp->SetEnabled(true, notify);
3196 return error;
3197 } else
3198 error.SetErrorString("sending gdb watchpoint packet failed");
3199 } else
3200 error.SetErrorString("watchpoints not supported");
3201 } else {
3202 error.SetErrorString("Watchpoint argument was NULL.");
3203 }
3204 if (error.Success())
3205 error.SetErrorToGenericError();
3206 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003207}
Kate Stoneb9c1b512016-09-06 20:57:50 +00003208
Zachary Turner97206d52017-05-12 04:51:55 +00003209Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3210 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003211 if (wp) {
3212 user_id_t watchID = wp->GetID();
3213
3214 Log *log(
3215 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3216
3217 addr_t addr = wp->GetLoadAddress();
3218
3219 if (log)
3220 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3221 ") addr = 0x%8.8" PRIx64,
3222 watchID, (uint64_t)addr);
3223
3224 if (!wp->IsEnabled()) {
3225 if (log)
3226 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3227 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3228 watchID, (uint64_t)addr);
3229 // See also 'class WatchpointSentry' within StopInfo.cpp.
3230 // This disabling attempt might come from the user-supplied actions, we'll
3231 // route it in order for
3232 // the watchpoint object to intelligently process this action.
3233 wp->SetEnabled(false, notify);
3234 return error;
3235 }
3236
3237 if (wp->IsHardware()) {
3238 GDBStoppointType type = GetGDBStoppointType(wp);
3239 // Pass down an appropriate z/Z packet...
3240 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3241 wp->GetByteSize()) == 0) {
3242 wp->SetEnabled(false, notify);
3243 return error;
3244 } else
3245 error.SetErrorString("sending gdb watchpoint packet failed");
3246 }
3247 // TODO: clear software watchpoints if we implement them
3248 } else {
3249 error.SetErrorString("Watchpoint argument was NULL.");
3250 }
3251 if (error.Success())
3252 error.SetErrorToGenericError();
3253 return error;
3254}
3255
3256void ProcessGDBRemote::Clear() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003257 m_thread_list_real.Clear();
3258 m_thread_list.Clear();
3259}
3260
Zachary Turner97206d52017-05-12 04:51:55 +00003261Status ProcessGDBRemote::DoSignal(int signo) {
3262 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003263 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3264 if (log)
3265 log->Printf("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3266
3267 if (!m_gdb_comm.SendAsyncSignal(signo))
3268 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3269 return error;
3270}
3271
Zachary Turner97206d52017-05-12 04:51:55 +00003272Status
3273ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003274 // Make sure we aren't already connected?
3275 if (m_gdb_comm.IsConnected())
Zachary Turner97206d52017-05-12 04:51:55 +00003276 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003277
3278 PlatformSP platform_sp(GetTarget().GetPlatform());
3279 if (platform_sp && !platform_sp->IsHost())
Zachary Turner97206d52017-05-12 04:51:55 +00003280 return Status("Lost debug server connection");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003281
3282 auto error = LaunchAndConnectToDebugserver(process_info);
3283 if (error.Fail()) {
3284 const char *error_string = error.AsCString();
3285 if (error_string == nullptr)
3286 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3287 }
3288 return error;
3289}
Eugene Zemtsov30153412017-09-25 17:41:16 +00003290#if !defined(_WIN32)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003291#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3292#endif
3293
3294#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Kate Stoneb9c1b512016-09-06 20:57:50 +00003295static bool SetCloexecFlag(int fd) {
3296#if defined(FD_CLOEXEC)
3297 int flags = ::fcntl(fd, F_GETFD);
3298 if (flags == -1)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003299 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003300 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3301#else
3302 return false;
Greg Claytonc6c420f2016-08-12 16:46:18 +00003303#endif
3304}
3305#endif
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003306
Zachary Turner97206d52017-05-12 04:51:55 +00003307Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003308 const ProcessInfo &process_info) {
3309 using namespace std::placeholders; // For _1, _2, etc.
Pavel Labath998bdc52016-05-11 16:59:04 +00003310
Zachary Turner97206d52017-05-12 04:51:55 +00003311 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003312 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3313 // If we locate debugserver, keep that located version around
3314 static FileSpec g_debugserver_file_spec;
3315
3316 ProcessLaunchInfo debugserver_launch_info;
3317 // Make debugserver run in its own session so signals generated by
3318 // special terminal key sequences (^C) don't affect debugserver.
3319 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3320
3321 const std::weak_ptr<ProcessGDBRemote> this_wp =
3322 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3323 debugserver_launch_info.SetMonitorProcessCallback(
3324 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3325 debugserver_launch_info.SetUserID(process_info.GetUserID());
3326
3327 int communication_fd = -1;
3328#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3329 // Auto close the sockets we might open up unless everything goes OK. This
3330 // helps us not leak file descriptors when things go wrong.
3331 lldb_utility::CleanUp<int, int> our_socket(-1, -1, close);
3332 lldb_utility::CleanUp<int, int> gdb_socket(-1, -1, close);
3333
Eugene Zemtsov30153412017-09-25 17:41:16 +00003334 // Use a socketpair on non-Windows systems for security and performance
3335 // reasons.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003336 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003337 int sockets[2]; /* the pair of socket descriptors */
3338 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3339 error.SetErrorToErrno();
3340 return error;
3341 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003342
Kate Stoneb9c1b512016-09-06 20:57:50 +00003343 our_socket.set(sockets[0]);
3344 gdb_socket.set(sockets[1]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003345 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003346
3347 // Don't let any child processes inherit our communication socket
3348 SetCloexecFlag(our_socket.get());
3349 communication_fd = gdb_socket.get();
3350#endif
3351
3352 error = m_gdb_comm.StartDebugserverProcess(
3353 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3354 nullptr, nullptr, communication_fd);
3355
3356 if (error.Success())
3357 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3358 else
3359 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3360
3361 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3362#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3363 // Our process spawned correctly, we can now set our connection to use our
3364 // end of the socket pair
3365 m_gdb_comm.SetConnection(
3366 new ConnectionFileDescriptor(our_socket.release(), true));
3367#endif
3368 StartAsyncThread();
3369 }
3370
3371 if (error.Fail()) {
3372 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3373
3374 if (log)
3375 log->Printf("failed to start debugserver process: %s",
3376 error.AsCString());
3377 return error;
3378 }
3379
3380 if (m_gdb_comm.IsConnected()) {
3381 // Finish the connection process by doing the handshake without connecting
3382 // (send NULL URL)
Zachary Turner31659452016-11-17 21:15:14 +00003383 ConnectToDebugserver("");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003384 } else {
3385 error.SetErrorString("connection failed");
3386 }
3387 }
3388 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003389}
3390
Kate Stoneb9c1b512016-09-06 20:57:50 +00003391bool ProcessGDBRemote::MonitorDebugserverProcess(
3392 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3393 bool exited, // True if the process did exit
3394 int signo, // Zero for no signal
3395 int exit_status // Exit value of process if signal is zero
3396 ) {
3397 // "debugserver_pid" argument passed in is the process ID for
3398 // debugserver that we are tracking...
3399 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3400 const bool handled = true;
Greg Claytone4e45922011-11-16 05:37:56 +00003401
Kate Stoneb9c1b512016-09-06 20:57:50 +00003402 if (log)
3403 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3404 ", signo=%i (0x%x), exit_status=%i)",
3405 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00003406
Kate Stoneb9c1b512016-09-06 20:57:50 +00003407 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3408 if (log)
3409 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3410 static_cast<void *>(process_sp.get()));
3411 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
Pavel Labath194357c2016-05-12 11:10:01 +00003412 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003413
Kate Stoneb9c1b512016-09-06 20:57:50 +00003414 // Sleep for a half a second to make sure our inferior process has
3415 // time to set its exit status before we set it incorrectly when
3416 // both the debugserver and the inferior process shut down.
3417 usleep(500000);
3418 // If our process hasn't yet exited, debugserver might have died.
3419 // If the process did exit, then we are reaping it.
3420 const StateType state = process_sp->GetState();
3421
3422 if (state != eStateInvalid && state != eStateUnloaded &&
3423 state != eStateExited && state != eStateDetached) {
3424 char error_str[1024];
3425 if (signo) {
3426 const char *signal_cstr =
3427 process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3428 if (signal_cstr)
3429 ::snprintf(error_str, sizeof(error_str),
3430 DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3431 else
3432 ::snprintf(error_str, sizeof(error_str),
3433 DEBUGSERVER_BASENAME " died with signal %i", signo);
3434 } else {
3435 ::snprintf(error_str, sizeof(error_str),
3436 DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3437 exit_status);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003438 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003439
3440 process_sp->SetExitStatus(-1, error_str);
3441 }
3442 // Debugserver has exited we need to let our ProcessGDBRemote
3443 // know that it no longer has a debugserver instance
3444 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3445 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003446}
3447
Kate Stoneb9c1b512016-09-06 20:57:50 +00003448void ProcessGDBRemote::KillDebugserverProcess() {
3449 m_gdb_comm.Disconnect();
3450 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3451 Host::Kill(m_debugserver_pid, SIGINT);
3452 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3453 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003454}
3455
Kate Stoneb9c1b512016-09-06 20:57:50 +00003456void ProcessGDBRemote::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003457 static llvm::once_flag g_once_flag;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003458
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003459 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003460 PluginManager::RegisterPlugin(GetPluginNameStatic(),
3461 GetPluginDescriptionStatic(), CreateInstance,
3462 DebuggerInitialize);
3463 });
Greg Clayton7f982402013-07-15 22:54:20 +00003464}
3465
Kate Stoneb9c1b512016-09-06 20:57:50 +00003466void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3467 if (!PluginManager::GetSettingForProcessPlugin(
3468 debugger, PluginProperties::GetSettingName())) {
3469 const bool is_global_setting = true;
3470 PluginManager::CreateSettingForProcessPlugin(
3471 debugger, GetGlobalPluginProperties()->GetValueProperties(),
3472 ConstString("Properties for the gdb-remote process plug-in."),
3473 is_global_setting);
3474 }
3475}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003476
Kate Stoneb9c1b512016-09-06 20:57:50 +00003477bool ProcessGDBRemote::StartAsyncThread() {
3478 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3479
3480 if (log)
3481 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3482
3483 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3484 if (!m_async_thread.IsJoinable()) {
3485 // Create a thread that watches our internal state and controls which
3486 // events make it to clients (into the DCProcess event queue).
3487
3488 m_async_thread =
3489 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>",
3490 ProcessGDBRemote::AsyncThread, this, NULL);
3491 } else if (log)
3492 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
3493 "already running.",
3494 __FUNCTION__);
3495
3496 return m_async_thread.IsJoinable();
3497}
3498
3499void ProcessGDBRemote::StopAsyncThread() {
3500 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3501
3502 if (log)
3503 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3504
3505 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3506 if (m_async_thread.IsJoinable()) {
3507 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3508
3509 // This will shut down the async thread.
3510 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3511
3512 // Stop the stdio thread
3513 m_async_thread.Join(nullptr);
3514 m_async_thread.Reset();
3515 } else if (log)
3516 log->Printf(
3517 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3518 __FUNCTION__);
3519}
3520
3521bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3522 // get the packet at a string
3523 const std::string &pkt = packet.GetStringRef();
3524 // skip %stop:
3525 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3526
3527 // pass as a thread stop info packet
3528 SetLastStopPacket(stop_info);
3529
3530 // check for more stop reasons
3531 HandleStopReplySequence();
3532
3533 // if the process is stopped then we need to fake a resume
3534 // so that we can stop properly with the new break. This
3535 // is possible due to SetPrivateState() broadcasting the
3536 // state change as a side effect.
3537 if (GetPrivateState() == lldb::StateType::eStateStopped) {
3538 SetPrivateState(lldb::StateType::eStateRunning);
3539 }
3540
3541 // since we have some stopped packets we can halt the process
3542 SetPrivateState(lldb::StateType::eStateStopped);
3543
3544 return true;
3545}
3546
3547thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3548 ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3549
3550 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3551 if (log)
3552 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3553 ") thread starting...",
3554 __FUNCTION__, arg, process->GetID());
3555
3556 EventSP event_sp;
3557 bool done = false;
3558 while (!done) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003559 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003560 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3561 ") listener.WaitForEvent (NULL, event_sp)...",
3562 __FUNCTION__, arg, process->GetID());
Pavel Labathd35031e12016-11-30 10:41:42 +00003563 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003564 const uint32_t event_type = event_sp->GetType();
3565 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
Pavel Labath50556852015-09-03 09:36:22 +00003566 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003567 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3568 ") Got an event of type: %d...",
3569 __FUNCTION__, arg, process->GetID(), event_type);
Pavel Labath50556852015-09-03 09:36:22 +00003570
Kate Stoneb9c1b512016-09-06 20:57:50 +00003571 switch (event_type) {
3572 case eBroadcastBitAsyncContinue: {
3573 const EventDataBytes *continue_packet =
3574 EventDataBytes::GetEventDataFromEvent(event_sp.get());
Pavel Labath50556852015-09-03 09:36:22 +00003575
Kate Stoneb9c1b512016-09-06 20:57:50 +00003576 if (continue_packet) {
3577 const char *continue_cstr =
3578 (const char *)continue_packet->GetBytes();
3579 const size_t continue_cstr_len = continue_packet->GetByteSize();
Pavel Labath50556852015-09-03 09:36:22 +00003580 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003581 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3582 ") got eBroadcastBitAsyncContinue: %s",
3583 __FUNCTION__, arg, process->GetID(), continue_cstr);
3584
3585 if (::strstr(continue_cstr, "vAttach") == NULL)
3586 process->SetPrivateState(eStateRunning);
3587 StringExtractorGDBRemote response;
3588
3589 // If in Non-Stop-Mode
3590 if (process->GetTarget().GetNonStopModeEnabled()) {
3591 // send the vCont packet
3592 if (!process->GetGDBRemote().SendvContPacket(
3593 llvm::StringRef(continue_cstr, continue_cstr_len),
3594 response)) {
3595 // Something went wrong
3596 done = true;
3597 break;
3598 }
3599 }
3600 // If in All-Stop-Mode
3601 else {
3602 StateType stop_state =
3603 process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3604 *process, *process->GetUnixSignals(),
3605 llvm::StringRef(continue_cstr, continue_cstr_len),
3606 response);
3607
3608 // We need to immediately clear the thread ID list so we are sure
3609 // to get a valid list of threads.
3610 // The thread ID list might be contained within the "response", or
3611 // the stop reply packet that
3612 // caused the stop. So clear it now before we give the stop reply
3613 // packet to the process
3614 // using the process->SetLastStopPacket()...
3615 process->ClearThreadIDList();
3616
3617 switch (stop_state) {
3618 case eStateStopped:
3619 case eStateCrashed:
3620 case eStateSuspended:
3621 process->SetLastStopPacket(response);
3622 process->SetPrivateState(stop_state);
3623 break;
3624
3625 case eStateExited: {
3626 process->SetLastStopPacket(response);
3627 process->ClearThreadIDList();
3628 response.SetFilePos(1);
3629
3630 int exit_status = response.GetHexU8();
3631 std::string desc_string;
3632 if (response.GetBytesLeft() > 0 &&
3633 response.GetChar('-') == ';') {
3634 llvm::StringRef desc_str;
3635 llvm::StringRef desc_token;
3636 while (response.GetNameColonValue(desc_token, desc_str)) {
3637 if (desc_token != "description")
3638 continue;
3639 StringExtractor extractor(desc_str);
3640 extractor.GetHexByteString(desc_string);
3641 }
3642 }
3643 process->SetExitStatus(exit_status, desc_string.c_str());
3644 done = true;
3645 break;
3646 }
3647 case eStateInvalid: {
3648 // Check to see if we were trying to attach and if we got back
3649 // the "E87" error code from debugserver -- this indicates that
3650 // the process is not debuggable. Return a slightly more
3651 // helpful
3652 // error message about why the attach failed.
3653 if (::strstr(continue_cstr, "vAttach") != NULL &&
3654 response.GetError() == 0x87) {
3655 process->SetExitStatus(-1, "cannot attach to process due to "
3656 "System Integrity Protection");
3657 }
3658 // E01 code from vAttach means that the attach failed
3659 if (::strstr(continue_cstr, "vAttach") != NULL &&
3660 response.GetError() == 0x1) {
3661 process->SetExitStatus(-1, "unable to attach");
3662 } else {
3663 process->SetExitStatus(-1, "lost connection");
3664 }
3665 break;
3666 }
3667
3668 default:
3669 process->SetPrivateState(stop_state);
3670 break;
3671 } // switch(stop_state)
3672 } // else // if in All-stop-mode
3673 } // if (continue_packet)
3674 } // case eBroadcastBitAysncContinue
3675 break;
3676
3677 case eBroadcastBitAsyncThreadShouldExit:
3678 if (log)
3679 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3680 ") got eBroadcastBitAsyncThreadShouldExit...",
3681 __FUNCTION__, arg, process->GetID());
3682 done = true;
3683 break;
3684
3685 default:
3686 if (log)
3687 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3688 ") got unknown event 0x%8.8x",
3689 __FUNCTION__, arg, process->GetID(), event_type);
3690 done = true;
3691 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003692 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003693 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3694 switch (event_type) {
3695 case Communication::eBroadcastBitReadThreadDidExit:
3696 process->SetExitStatus(-1, "lost connection");
3697 done = true;
3698 break;
3699
3700 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3701 lldb_private::Event *event = event_sp.get();
3702 const EventDataBytes *continue_packet =
3703 EventDataBytes::GetEventDataFromEvent(event);
3704 StringExtractorGDBRemote notify(
3705 (const char *)continue_packet->GetBytes());
3706 // Hand this over to the process to handle
3707 process->HandleNotifyPacket(notify);
3708 break;
3709 }
3710
3711 default:
3712 if (log)
3713 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3714 ") got unknown event 0x%8.8x",
3715 __FUNCTION__, arg, process->GetID(), event_type);
3716 done = true;
3717 break;
3718 }
3719 }
3720 } else {
3721 if (log)
3722 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3723 ") listener.WaitForEvent (NULL, event_sp) => false",
3724 __FUNCTION__, arg, process->GetID());
3725 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003727 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003728
Kate Stoneb9c1b512016-09-06 20:57:50 +00003729 if (log)
3730 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3731 ") thread exiting...",
3732 __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003733
Kate Stoneb9c1b512016-09-06 20:57:50 +00003734 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003735}
3736
Kate Stoneb9c1b512016-09-06 20:57:50 +00003737// uint32_t
3738// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3739// &matches, std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00003740//{
Kate Stoneb9c1b512016-09-06 20:57:50 +00003741// // If we are planning to launch the debugserver remotely, then we need to
3742// fire up a debugserver
3743// // process and ask it for the list of processes. But if we are local, we
3744// can let the Host do it.
Greg Claytone996fd32011-03-08 22:40:15 +00003745// if (m_local_debugserver)
3746// {
3747// return Host::ListProcessesMatchingName (name, matches, pids);
3748// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003749// else
Greg Claytone996fd32011-03-08 22:40:15 +00003750// {
3751// // FIXME: Implement talking to the remote debugserver.
3752// return 0;
3753// }
3754//
3755//}
3756//
Kate Stoneb9c1b512016-09-06 20:57:50 +00003757bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3758 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3759 lldb::user_id_t break_loc_id) {
3760 // I don't think I have to do anything here, just make sure I notice the new
3761 // thread when it starts to
3762 // run so I can stop it if that's what I want to do.
3763 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3764 if (log)
3765 log->Printf("Hit New Thread Notification breakpoint.");
3766 return false;
Jim Ingham1c823b42011-01-22 01:33:44 +00003767}
3768
Zachary Turner97206d52017-05-12 04:51:55 +00003769Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003770 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3771 LLDB_LOG(log, "Check if need to update ignored signals");
3772
3773 // QPassSignals package is not supported by the server,
3774 // there is no way we can ignore any signals on server side.
3775 if (!m_gdb_comm.GetQPassSignalsSupported())
Zachary Turner97206d52017-05-12 04:51:55 +00003776 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003777
3778 // No signals, nothing to send.
3779 if (m_unix_signals_sp == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00003780 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003781
3782 // Signals' version hasn't changed, no need to send anything.
3783 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3784 if (new_signals_version == m_last_signals_version) {
3785 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3786 m_last_signals_version);
Zachary Turner97206d52017-05-12 04:51:55 +00003787 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003788 }
3789
3790 auto signals_to_ignore =
3791 m_unix_signals_sp->GetFilteredSignals(false, false, false);
Zachary Turner97206d52017-05-12 04:51:55 +00003792 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003793
3794 LLDB_LOG(log,
3795 "Signals' version changed. old version={0}, new version={1}, "
3796 "signals ignored={2}, update result={3}",
3797 m_last_signals_version, new_signals_version,
3798 signals_to_ignore.size(), error);
3799
3800 if (error.Success())
3801 m_last_signals_version = new_signals_version;
3802
3803 return error;
3804}
3805
Kate Stoneb9c1b512016-09-06 20:57:50 +00003806bool ProcessGDBRemote::StartNoticingNewThreads() {
3807 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3808 if (m_thread_create_bp_sp) {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003809 if (log && log->GetVerbose())
Kate Stoneb9c1b512016-09-06 20:57:50 +00003810 log->Printf("Enabled noticing new thread breakpoint.");
3811 m_thread_create_bp_sp->SetEnabled(true);
3812 } else {
3813 PlatformSP platform_sp(GetTarget().GetPlatform());
3814 if (platform_sp) {
3815 m_thread_create_bp_sp =
3816 platform_sp->SetThreadCreationBreakpoint(GetTarget());
3817 if (m_thread_create_bp_sp) {
3818 if (log && log->GetVerbose())
3819 log->Printf(
3820 "Successfully created new thread notification breakpoint %i",
3821 m_thread_create_bp_sp->GetID());
3822 m_thread_create_bp_sp->SetCallback(
3823 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3824 } else {
3825 if (log)
3826 log->Printf("Failed to create new thread notification breakpoint.");
3827 }
Jason Molendaa3329782014-03-29 18:54:20 +00003828 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003829 }
3830 return m_thread_create_bp_sp.get() != NULL;
Jason Molendaa3329782014-03-29 18:54:20 +00003831}
3832
Kate Stoneb9c1b512016-09-06 20:57:50 +00003833bool ProcessGDBRemote::StopNoticingNewThreads() {
3834 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3835 if (log && log->GetVerbose())
3836 log->Printf("Disabling new thread notification breakpoint.");
3837
3838 if (m_thread_create_bp_sp)
3839 m_thread_create_bp_sp->SetEnabled(false);
3840
3841 return true;
3842}
3843
3844DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3845 if (m_dyld_ap.get() == NULL)
3846 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, NULL));
3847 return m_dyld_ap.get();
3848}
3849
Zachary Turner97206d52017-05-12 04:51:55 +00003850Status ProcessGDBRemote::SendEventData(const char *data) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003851 int return_value;
3852 bool was_supported;
3853
Zachary Turner97206d52017-05-12 04:51:55 +00003854 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003855
3856 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3857 if (return_value != 0) {
3858 if (!was_supported)
3859 error.SetErrorString("Sending events is not supported for this process.");
3860 else
3861 error.SetErrorStringWithFormat("Error sending event data: %d.",
3862 return_value);
3863 }
3864 return error;
3865}
3866
3867const DataBufferSP ProcessGDBRemote::GetAuxvData() {
3868 DataBufferSP buf;
3869 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3870 std::string response_string;
3871 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
3872 response_string) ==
3873 GDBRemoteCommunication::PacketResult::Success)
3874 buf.reset(new DataBufferHeap(response_string.c_str(),
3875 response_string.length()));
3876 }
3877 return buf;
Steve Pucci03904ac2014-03-04 23:18:46 +00003878}
3879
Jason Molenda705b1802014-06-13 02:37:02 +00003880StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00003881ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3882 StructuredData::ObjectSP object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00003883
Kate Stoneb9c1b512016-09-06 20:57:50 +00003884 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003885 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003886 SystemRuntime *runtime = GetSystemRuntime();
3887 if (runtime) {
3888 runtime->AddThreadExtendedInfoPacketHints(args_dict);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003889 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003890 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003891
Kate Stoneb9c1b512016-09-06 20:57:50 +00003892 StreamString packet;
3893 packet << "jThreadExtendedInfo:";
3894 args_dict->Dump(packet, false);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003895
Kate Stoneb9c1b512016-09-06 20:57:50 +00003896 // FIXME the final character of a JSON dictionary, '}', is the escape
3897 // character in gdb-remote binary mode. lldb currently doesn't escape
3898 // these characters in its packet output -- so we add the quoted version
3899 // of the } character here manually in case we talk to a debugserver which
3900 // un-escapes the characters at packet read time.
3901 packet << (char)(0x7d ^ 0x20);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003902
Kate Stoneb9c1b512016-09-06 20:57:50 +00003903 StringExtractorGDBRemote response;
3904 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003905 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3906 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003907 GDBRemoteCommunication::PacketResult::Success) {
3908 StringExtractorGDBRemote::ResponseType response_type =
3909 response.GetResponseType();
3910 if (response_type == StringExtractorGDBRemote::eResponse) {
3911 if (!response.Empty()) {
3912 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda705b1802014-06-13 02:37:02 +00003913 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003914 }
Jason Molenda705b1802014-06-13 02:37:02 +00003915 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003916 }
3917 return object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00003918}
3919
Kate Stoneb9c1b512016-09-06 20:57:50 +00003920StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3921 lldb::addr_t image_list_address, lldb::addr_t image_count) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003922
Kate Stoneb9c1b512016-09-06 20:57:50 +00003923 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3924 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3925 image_list_address);
3926 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003927
Kate Stoneb9c1b512016-09-06 20:57:50 +00003928 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3929}
3930
3931StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3932 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3933
3934 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3935
3936 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3937}
3938
3939StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3940 const std::vector<lldb::addr_t> &load_addresses) {
3941 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3942 StructuredData::ArraySP addresses(new StructuredData::Array);
3943
3944 for (auto addr : load_addresses) {
3945 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
3946 addresses->AddItem(addr_sp);
3947 }
3948
3949 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3950
3951 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3952}
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003953
Jason Molenda37397352016-07-22 00:17:55 +00003954StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00003955ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3956 StructuredData::ObjectSP args_dict) {
3957 StructuredData::ObjectSP object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00003958
Kate Stoneb9c1b512016-09-06 20:57:50 +00003959 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3960 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +00003961 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
3962 std::chrono::seconds(10));
Jason Molenda37397352016-07-22 00:17:55 +00003963
Kate Stoneb9c1b512016-09-06 20:57:50 +00003964 StreamString packet;
3965 packet << "jGetLoadedDynamicLibrariesInfos:";
3966 args_dict->Dump(packet, false);
Jason Molenda37397352016-07-22 00:17:55 +00003967
Kate Stoneb9c1b512016-09-06 20:57:50 +00003968 // FIXME the final character of a JSON dictionary, '}', is the escape
3969 // character in gdb-remote binary mode. lldb currently doesn't escape
3970 // these characters in its packet output -- so we add the quoted version
3971 // of the } character here manually in case we talk to a debugserver which
3972 // un-escapes the characters at packet read time.
3973 packet << (char)(0x7d ^ 0x20);
3974
3975 StringExtractorGDBRemote response;
3976 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003977 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3978 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003979 GDBRemoteCommunication::PacketResult::Success) {
3980 StringExtractorGDBRemote::ResponseType response_type =
3981 response.GetResponseType();
3982 if (response_type == StringExtractorGDBRemote::eResponse) {
3983 if (!response.Empty()) {
3984 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda37397352016-07-22 00:17:55 +00003985 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003986 }
Jason Molenda37397352016-07-22 00:17:55 +00003987 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003988 }
3989 return object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00003990}
3991
Kate Stoneb9c1b512016-09-06 20:57:50 +00003992StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
3993 StructuredData::ObjectSP object_sp;
3994 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3995
3996 if (m_gdb_comm.GetSharedCacheInfoSupported()) {
3997 StreamString packet;
3998 packet << "jGetSharedCacheInfo:";
3999 args_dict->Dump(packet, false);
4000
4001 // FIXME the final character of a JSON dictionary, '}', is the escape
4002 // character in gdb-remote binary mode. lldb currently doesn't escape
4003 // these characters in its packet output -- so we add the quoted version
4004 // of the } character here manually in case we talk to a debugserver which
4005 // un-escapes the characters at packet read time.
4006 packet << (char)(0x7d ^ 0x20);
4007
4008 StringExtractorGDBRemote response;
4009 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004010 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4011 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004012 GDBRemoteCommunication::PacketResult::Success) {
4013 StringExtractorGDBRemote::ResponseType response_type =
4014 response.GetResponseType();
4015 if (response_type == StringExtractorGDBRemote::eResponse) {
4016 if (!response.Empty()) {
4017 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4018 }
4019 }
4020 }
4021 }
4022 return object_sp;
4023}
4024
Zachary Turner97206d52017-05-12 04:51:55 +00004025Status ProcessGDBRemote::ConfigureStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004026 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
4027 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
Todd Fiala75930012016-08-19 04:21:48 +00004028}
Jason Molenda37397352016-07-22 00:17:55 +00004029
Jason Molenda6076bf42014-05-06 04:34:52 +00004030// Establish the largest memory read/write payloads we should use.
4031// If the remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004032//
4033// If the remote stub's max packet size is crazy large, use a
Jason Molenda6076bf42014-05-06 04:34:52 +00004034// reasonable largeish default.
4035//
4036// If the remote stub doesn't advertise a max packet size, use a
4037// conservative default.
4038
Kate Stoneb9c1b512016-09-06 20:57:50 +00004039void ProcessGDBRemote::GetMaxMemorySize() {
4040 const uint64_t reasonable_largeish_default = 128 * 1024;
4041 const uint64_t conservative_default = 512;
Jason Molenda6076bf42014-05-06 04:34:52 +00004042
Kate Stoneb9c1b512016-09-06 20:57:50 +00004043 if (m_max_memory_size == 0) {
4044 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4045 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4046 // Save the stub's claimed maximum packet size
4047 m_remote_stub_max_memory_size = stub_max_size;
Jason Molenda6076bf42014-05-06 04:34:52 +00004048
Kate Stoneb9c1b512016-09-06 20:57:50 +00004049 // Even if the stub says it can support ginormous packets,
4050 // don't exceed our reasonable largeish default packet size.
4051 if (stub_max_size > reasonable_largeish_default) {
4052 stub_max_size = reasonable_largeish_default;
4053 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004054
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00004055 // Memory packet have other overheads too like Maddr,size:#NN
4056 // Instead of calculating the bytes taken by size and addr every
4057 // time, we take a maximum guess here.
4058 if (stub_max_size > 70)
4059 stub_max_size -= 32 + 32 + 6;
4060 else {
4061 // In unlikely scenario that max packet size is less then 70, we will
4062 // hope that data being written is small enough to fit.
4063 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4064 GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4065 if (log)
4066 log->Warning("Packet size is too small. "
4067 "LLDB may face problems while writing memory");
4068 }
4069
Kate Stoneb9c1b512016-09-06 20:57:50 +00004070 m_max_memory_size = stub_max_size;
4071 } else {
4072 m_max_memory_size = conservative_default;
Jason Molenda6076bf42014-05-06 04:34:52 +00004073 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004074 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004075}
4076
Kate Stoneb9c1b512016-09-06 20:57:50 +00004077void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4078 uint64_t user_specified_max) {
4079 if (user_specified_max != 0) {
4080 GetMaxMemorySize();
Jason Molenda6076bf42014-05-06 04:34:52 +00004081
Kate Stoneb9c1b512016-09-06 20:57:50 +00004082 if (m_remote_stub_max_memory_size != 0) {
4083 if (m_remote_stub_max_memory_size < user_specified_max) {
4084 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4085 // packet size too
4086 // big, go as big
4087 // as the remote stub says we can go.
4088 } else {
4089 m_max_memory_size = user_specified_max; // user's packet size is good
4090 }
4091 } else {
4092 m_max_memory_size =
4093 user_specified_max; // user's packet size is probably fine
Jason Molenda6076bf42014-05-06 04:34:52 +00004094 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004095 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004096}
4097
Kate Stoneb9c1b512016-09-06 20:57:50 +00004098bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4099 const ArchSpec &arch,
4100 ModuleSpec &module_spec) {
4101 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004102
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004103 const ModuleCacheKey key(module_file_spec.GetPath(),
4104 arch.GetTriple().getTriple());
4105 auto cached = m_cached_module_specs.find(key);
4106 if (cached != m_cached_module_specs.end()) {
4107 module_spec = cached->second;
4108 return bool(module_spec);
4109 }
4110
Kate Stoneb9c1b512016-09-06 20:57:50 +00004111 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004112 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004113 log->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4114 __FUNCTION__, module_file_spec.GetPath().c_str(),
4115 arch.GetTriple().getTriple().c_str());
4116 return false;
4117 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004118
Kate Stoneb9c1b512016-09-06 20:57:50 +00004119 if (log) {
4120 StreamString stream;
4121 module_spec.Dump(stream);
4122 log->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4123 __FUNCTION__, module_file_spec.GetPath().c_str(),
Zachary Turnerc1564272016-11-16 21:15:24 +00004124 arch.GetTriple().getTriple().c_str(), stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004125 }
4126
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004127 m_cached_module_specs[key] = module_spec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004128 return true;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004129}
4130
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004131void ProcessGDBRemote::PrefetchModuleSpecs(
4132 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4133 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4134 if (module_specs) {
4135 for (const FileSpec &spec : module_file_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004136 m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4137 triple.getTriple())] = ModuleSpec();
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004138 for (const ModuleSpec &spec : *module_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004139 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4140 triple.getTriple())] = spec;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004141 }
4142}
4143
Kate Stoneb9c1b512016-09-06 20:57:50 +00004144bool ProcessGDBRemote::GetHostOSVersion(uint32_t &major, uint32_t &minor,
4145 uint32_t &update) {
4146 if (m_gdb_comm.GetOSVersion(major, minor, update))
4147 return true;
4148 // We failed to get the host OS version, defer to the base
4149 // implementation to correctly invalidate the arguments.
4150 return Process::GetHostOSVersion(major, minor, update);
Jim Ingham13c30d22015-11-05 22:33:17 +00004151}
4152
Colin Rileyc3c95b22015-04-16 15:51:33 +00004153namespace {
4154
4155typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004156
4157typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004158struct RegisterSetInfo {
4159 ConstString name;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004160};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004161
Greg Claytond04f0ed2015-05-26 18:00:51 +00004162typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004163
Kate Stoneb9c1b512016-09-06 20:57:50 +00004164struct GdbServerTargetInfo {
4165 std::string arch;
4166 std::string osabi;
4167 stringVec includes;
4168 RegisterSetMap reg_set_map;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004169};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004170
Kate Stoneb9c1b512016-09-06 20:57:50 +00004171bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4172 GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4173 uint32_t &cur_reg_num, uint32_t &reg_offset) {
4174 if (!feature_node)
4175 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004176
Kate Stoneb9c1b512016-09-06 20:57:50 +00004177 feature_node.ForEachChildElementWithName(
4178 "reg", [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset,
4179 &abi_sp](const XMLNode &reg_node) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004180 std::string gdb_group;
4181 std::string gdb_type;
4182 ConstString reg_name;
4183 ConstString alt_name;
4184 ConstString set_name;
4185 std::vector<uint32_t> value_regs;
4186 std::vector<uint32_t> invalidate_regs;
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004187 std::vector<uint8_t> dwarf_opcode_bytes;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004188 bool encoding_set = false;
4189 bool format_set = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004190 RegisterInfo reg_info = {
4191 NULL, // Name
4192 NULL, // Alt name
4193 0, // byte size
4194 reg_offset, // offset
4195 eEncodingUint, // encoding
4196 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004197 {
Jason Molendabf67a302015-09-01 05:17:01 +00004198 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004199 LLDB_INVALID_REGNUM, // DWARF reg num
4200 LLDB_INVALID_REGNUM, // generic reg num
Kate Stoneb9c1b512016-09-06 20:57:50 +00004201 cur_reg_num, // process plugin reg num
4202 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004203 },
4204 NULL,
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004205 NULL,
Kate Stoneb9c1b512016-09-06 20:57:50 +00004206 NULL, // Dwarf Expression opcode bytes pointer
4207 0 // Dwarf Expression opcode bytes length
Greg Claytond04f0ed2015-05-26 18:00:51 +00004208 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004209
Kate Stoneb9c1b512016-09-06 20:57:50 +00004210 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4211 &reg_name, &alt_name, &set_name, &value_regs,
4212 &invalidate_regs, &encoding_set, &format_set,
Zachary Turner3bc714b2017-03-02 00:05:25 +00004213 &reg_info, &reg_offset, &dwarf_opcode_bytes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004214 const llvm::StringRef &name,
4215 const llvm::StringRef &value) -> bool {
4216 if (name == "name") {
4217 reg_name.SetString(value);
4218 } else if (name == "bitsize") {
4219 reg_info.byte_size =
4220 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4221 } else if (name == "type") {
4222 gdb_type = value.str();
4223 } else if (name == "group") {
4224 gdb_group = value.str();
4225 } else if (name == "regnum") {
4226 const uint32_t regnum =
4227 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4228 if (regnum != LLDB_INVALID_REGNUM) {
4229 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004230 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004231 } else if (name == "offset") {
4232 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4233 } else if (name == "altname") {
4234 alt_name.SetString(value);
4235 } else if (name == "encoding") {
4236 encoding_set = true;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004237 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004238 } else if (name == "format") {
4239 format_set = true;
4240 Format format = eFormatInvalid;
4241 if (Args::StringToFormat(value.data(), format, NULL).Success())
4242 reg_info.format = format;
4243 else if (value == "vector-sint8")
4244 reg_info.format = eFormatVectorOfSInt8;
4245 else if (value == "vector-uint8")
4246 reg_info.format = eFormatVectorOfUInt8;
4247 else if (value == "vector-sint16")
4248 reg_info.format = eFormatVectorOfSInt16;
4249 else if (value == "vector-uint16")
4250 reg_info.format = eFormatVectorOfUInt16;
4251 else if (value == "vector-sint32")
4252 reg_info.format = eFormatVectorOfSInt32;
4253 else if (value == "vector-uint32")
4254 reg_info.format = eFormatVectorOfUInt32;
4255 else if (value == "vector-float32")
4256 reg_info.format = eFormatVectorOfFloat32;
Valentina Giusticda0ae42016-09-08 14:16:45 +00004257 else if (value == "vector-uint64")
4258 reg_info.format = eFormatVectorOfUInt64;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004259 else if (value == "vector-uint128")
4260 reg_info.format = eFormatVectorOfUInt128;
4261 } else if (name == "group_id") {
4262 const uint32_t set_id =
4263 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4264 RegisterSetMap::const_iterator pos =
4265 target_info.reg_set_map.find(set_id);
4266 if (pos != target_info.reg_set_map.end())
4267 set_name = pos->second.name;
4268 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4269 reg_info.kinds[eRegisterKindEHFrame] =
4270 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4271 } else if (name == "dwarf_regnum") {
4272 reg_info.kinds[eRegisterKindDWARF] =
4273 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4274 } else if (name == "generic") {
4275 reg_info.kinds[eRegisterKindGeneric] =
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004276 Args::StringToGenericRegister(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004277 } else if (name == "value_regnums") {
4278 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4279 } else if (name == "invalidate_regnums") {
4280 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4281 } else if (name == "dynamic_size_dwarf_expr_bytes") {
4282 StringExtractor opcode_extractor;
4283 std::string opcode_string = value.str();
4284 size_t dwarf_opcode_len = opcode_string.length() / 2;
4285 assert(dwarf_opcode_len > 0);
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004286
Kate Stoneb9c1b512016-09-06 20:57:50 +00004287 dwarf_opcode_bytes.resize(dwarf_opcode_len);
4288 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4289 opcode_extractor.GetStringRef().swap(opcode_string);
4290 uint32_t ret_val =
4291 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4292 assert(dwarf_opcode_len == ret_val);
Hafiz Abid Qadeer05008ca2017-01-19 15:11:01 +00004293 UNUSED_IF_ASSERT_DISABLED(ret_val);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004294 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4295 } else {
4296 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4297 }
4298 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004299 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004300
Kate Stoneb9c1b512016-09-06 20:57:50 +00004301 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4302 if (gdb_type.find("int") == 0) {
4303 reg_info.format = eFormatHex;
4304 reg_info.encoding = eEncodingUint;
4305 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4306 reg_info.format = eFormatAddressInfo;
4307 reg_info.encoding = eEncodingUint;
4308 } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4309 reg_info.format = eFormatFloat;
4310 reg_info.encoding = eEncodingIEEE754;
4311 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004312 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004313
Kate Stoneb9c1b512016-09-06 20:57:50 +00004314 // Only update the register set name if we didn't get a "reg_set"
4315 // attribute.
Greg Claytond04f0ed2015-05-26 18:00:51 +00004316 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4317 if (!set_name && !gdb_group.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004318 set_name.SetCString(gdb_group.c_str());
Ed Maste81b4c5f2016-01-04 01:43:47 +00004319
Greg Claytond04f0ed2015-05-26 18:00:51 +00004320 reg_info.byte_offset = reg_offset;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004321 assert(reg_info.byte_size != 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004322 reg_offset += reg_info.byte_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004323 if (!value_regs.empty()) {
4324 value_regs.push_back(LLDB_INVALID_REGNUM);
4325 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004326 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004327 if (!invalidate_regs.empty()) {
4328 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4329 reg_info.invalidate_regs = invalidate_regs.data();
Greg Claytond04f0ed2015-05-26 18:00:51 +00004330 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004331
Jason Molenda63bd0db2015-09-15 23:20:34 +00004332 ++cur_reg_num;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004333 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004334 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004335
Greg Claytond04f0ed2015-05-26 18:00:51 +00004336 return true; // Keep iterating through all "reg" elements
Kate Stoneb9c1b512016-09-06 20:57:50 +00004337 });
4338 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004339}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004340
Eugene Zelenko0722f082015-10-24 01:28:05 +00004341} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004342
Colin Rileyc3c95b22015-04-16 15:51:33 +00004343// query the target of gdb-remote for extended target information
4344// return: 'true' on success
4345// 'false' on failure
Kate Stoneb9c1b512016-09-06 20:57:50 +00004346bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4347 // Make sure LLDB has an XML parser it can use first
4348 if (!XMLDocument::XMLEnabled())
4349 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004350
Kate Stoneb9c1b512016-09-06 20:57:50 +00004351 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004352
Kate Stoneb9c1b512016-09-06 20:57:50 +00004353 GDBRemoteCommunicationClient &comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004354
Kate Stoneb9c1b512016-09-06 20:57:50 +00004355 // check that we have extended feature read support
4356 if (!comm.GetQXferFeaturesReadSupported())
4357 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004358
Kate Stoneb9c1b512016-09-06 20:57:50 +00004359 // request the target xml file
4360 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004361 lldb_private::Status lldberr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004362 if (!comm.ReadExtFeature(ConstString("features"), ConstString("target.xml"),
4363 raw, lldberr)) {
4364 return false;
4365 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004366
Kate Stoneb9c1b512016-09-06 20:57:50 +00004367 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004368
Kate Stoneb9c1b512016-09-06 20:57:50 +00004369 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) {
4370 GdbServerTargetInfo target_info;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004371
Kate Stoneb9c1b512016-09-06 20:57:50 +00004372 XMLNode target_node = xml_document.GetRootElement("target");
4373 if (target_node) {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004374 std::vector<XMLNode> feature_nodes;
4375 target_node.ForEachChildElement([&target_info, &feature_nodes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004376 const XMLNode &node) -> bool {
4377 llvm::StringRef name = node.GetName();
4378 if (name == "architecture") {
4379 node.GetElementText(target_info.arch);
4380 } else if (name == "osabi") {
4381 node.GetElementText(target_info.osabi);
4382 } else if (name == "xi:include" || name == "include") {
4383 llvm::StringRef href = node.GetAttributeValue("href");
4384 if (!href.empty())
4385 target_info.includes.push_back(href.str());
4386 } else if (name == "feature") {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004387 feature_nodes.push_back(node);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004388 } else if (name == "groups") {
4389 node.ForEachChildElementWithName(
4390 "group", [&target_info](const XMLNode &node) -> bool {
4391 uint32_t set_id = UINT32_MAX;
4392 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004393
Kate Stoneb9c1b512016-09-06 20:57:50 +00004394 node.ForEachAttribute(
4395 [&set_id, &set_info](const llvm::StringRef &name,
4396 const llvm::StringRef &value) -> bool {
4397 if (name == "id")
4398 set_id = StringConvert::ToUInt32(value.data(),
4399 UINT32_MAX, 0);
4400 if (name == "name")
4401 set_info.name = ConstString(value);
4402 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004403 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004404
Kate Stoneb9c1b512016-09-06 20:57:50 +00004405 if (set_id != UINT32_MAX)
4406 target_info.reg_set_map[set_id] = set_info;
4407 return true; // Keep iterating through all "group" elements
4408 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004409 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004410 return true; // Keep iterating through all children of the target_node
4411 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004412
Kate Stoneb9c1b512016-09-06 20:57:50 +00004413 // Initialize these outside of ParseRegisters, since they should not be
4414 // reset inside each include feature
4415 uint32_t cur_reg_num = 0;
4416 uint32_t reg_offset = 0;
4417
4418 // Don't use Process::GetABI, this code gets called from DidAttach, and in
4419 // that context we haven't
4420 // set the Target's architecture yet, so the ABI is also potentially
4421 // incorrect.
Jason Molenda43294c92017-06-29 02:57:03 +00004422 ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004423 for (auto &feature_node : feature_nodes) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004424 ParseRegisters(feature_node, target_info, this->m_register_info,
4425 abi_to_use_sp, cur_reg_num, reg_offset);
4426 }
4427
4428 for (const auto &include : target_info.includes) {
4429 // request register file
4430 std::string xml_data;
4431 if (!comm.ReadExtFeature(ConstString("features"), ConstString(include),
4432 xml_data, lldberr))
4433 continue;
4434
4435 XMLDocument include_xml_document;
4436 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(),
4437 include.c_str());
4438 XMLNode include_feature_node =
4439 include_xml_document.GetRootElement("feature");
4440 if (include_feature_node) {
4441 ParseRegisters(include_feature_node, target_info,
4442 this->m_register_info, abi_to_use_sp, cur_reg_num,
4443 reg_offset);
4444 }
4445 }
4446 this->m_register_info.Finalize(arch_to_use);
4447 }
4448 }
4449
4450 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004451}
4452
Zachary Turner97206d52017-05-12 04:51:55 +00004453Status ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004454 // Make sure LLDB has an XML parser it can use first
4455 if (!XMLDocument::XMLEnabled())
Zachary Turner97206d52017-05-12 04:51:55 +00004456 return Status(0, ErrorType::eErrorTypeGeneric);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004457
Kate Stoneb9c1b512016-09-06 20:57:50 +00004458 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
4459 if (log)
4460 log->Printf("ProcessGDBRemote::%s", __FUNCTION__);
4461
4462 GDBRemoteCommunicationClient &comm = m_gdb_comm;
4463
4464 // check that we have extended feature read support
4465 if (comm.GetQXferLibrariesSVR4ReadSupported()) {
4466 list.clear();
4467
4468 // request the loaded library list
4469 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004470 lldb_private::Status lldberr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004471
4472 if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4473 raw, lldberr))
Zachary Turner97206d52017-05-12 04:51:55 +00004474 return Status(0, ErrorType::eErrorTypeGeneric);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004475
4476 // parse the xml file in memory
Aidan Doddsc0c83852015-05-08 09:36:31 +00004477 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004478 log->Printf("parsing: %s", raw.c_str());
4479 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004480
Kate Stoneb9c1b512016-09-06 20:57:50 +00004481 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Zachary Turner97206d52017-05-12 04:51:55 +00004482 return Status(0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004483
Kate Stoneb9c1b512016-09-06 20:57:50 +00004484 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4485 if (!root_element)
Zachary Turner97206d52017-05-12 04:51:55 +00004486 return Status();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004487
Kate Stoneb9c1b512016-09-06 20:57:50 +00004488 // main link map structure
4489 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4490 if (!main_lm.empty()) {
4491 list.m_link_map =
4492 StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4493 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004494
Kate Stoneb9c1b512016-09-06 20:57:50 +00004495 root_element.ForEachChildElementWithName(
4496 "library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004497
Kate Stoneb9c1b512016-09-06 20:57:50 +00004498 LoadedModuleInfoList::LoadedModuleInfo module;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004499
Kate Stoneb9c1b512016-09-06 20:57:50 +00004500 library.ForEachAttribute(
Zachary Turner3bc714b2017-03-02 00:05:25 +00004501 [&module](const llvm::StringRef &name,
4502 const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004503
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004504 if (name == "name")
Kate Stoneb9c1b512016-09-06 20:57:50 +00004505 module.set_name(value.str());
4506 else if (name == "lm") {
4507 // the address of the link_map struct.
4508 module.set_link_map(StringConvert::ToUInt64(
4509 value.data(), LLDB_INVALID_ADDRESS, 0));
4510 } else if (name == "l_addr") {
4511 // the displacement as read from the field 'l_addr' of the
4512 // link_map struct.
4513 module.set_base(StringConvert::ToUInt64(
4514 value.data(), LLDB_INVALID_ADDRESS, 0));
4515 // base address is always a displacement, not an absolute
4516 // value.
4517 module.set_base_is_offset(true);
4518 } else if (name == "l_ld") {
4519 // the memory address of the libraries PT_DYAMIC section.
4520 module.set_dynamic(StringConvert::ToUInt64(
4521 value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004522 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004523
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004524 return true; // Keep iterating over all properties of "library"
Kate Stoneb9c1b512016-09-06 20:57:50 +00004525 });
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004526
Kate Stoneb9c1b512016-09-06 20:57:50 +00004527 if (log) {
4528 std::string name;
4529 lldb::addr_t lm = 0, base = 0, ld = 0;
4530 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004531
Kate Stoneb9c1b512016-09-06 20:57:50 +00004532 module.get_name(name);
4533 module.get_link_map(lm);
4534 module.get_base(base);
4535 module.get_base_is_offset(base_is_offset);
4536 module.get_dynamic(ld);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004537
Kate Stoneb9c1b512016-09-06 20:57:50 +00004538 log->Printf("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4539 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4540 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4541 name.c_str());
4542 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004543
Kate Stoneb9c1b512016-09-06 20:57:50 +00004544 list.add(module);
4545 return true; // Keep iterating over all "library" elements in the root
4546 // node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004547 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004548
Kate Stoneb9c1b512016-09-06 20:57:50 +00004549 if (log)
4550 log->Printf("found %" PRId32 " modules in total",
4551 (int)list.m_list.size());
4552 } else if (comm.GetQXferLibrariesReadSupported()) {
4553 list.clear();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004554
Kate Stoneb9c1b512016-09-06 20:57:50 +00004555 // request the loaded library list
4556 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004557 lldb_private::Status lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004558
Kate Stoneb9c1b512016-09-06 20:57:50 +00004559 if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4560 lldberr))
Zachary Turner97206d52017-05-12 04:51:55 +00004561 return Status(0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004562
Kate Stoneb9c1b512016-09-06 20:57:50 +00004563 if (log)
4564 log->Printf("parsing: %s", raw.c_str());
4565 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004566
Kate Stoneb9c1b512016-09-06 20:57:50 +00004567 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Zachary Turner97206d52017-05-12 04:51:55 +00004568 return Status(0, ErrorType::eErrorTypeGeneric);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004569
Kate Stoneb9c1b512016-09-06 20:57:50 +00004570 XMLNode root_element = doc.GetRootElement("library-list");
4571 if (!root_element)
Zachary Turner97206d52017-05-12 04:51:55 +00004572 return Status();
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004573
Kate Stoneb9c1b512016-09-06 20:57:50 +00004574 root_element.ForEachChildElementWithName(
4575 "library", [log, &list](const XMLNode &library) -> bool {
4576 LoadedModuleInfoList::LoadedModuleInfo module;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004577
Kate Stoneb9c1b512016-09-06 20:57:50 +00004578 llvm::StringRef name = library.GetAttributeValue("name");
4579 module.set_name(name.str());
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004580
Kate Stoneb9c1b512016-09-06 20:57:50 +00004581 // The base address of a given library will be the address of its
4582 // first section. Most remotes send only one section for Windows
4583 // targets for example.
4584 const XMLNode &section =
4585 library.FindFirstChildElementWithName("section");
4586 llvm::StringRef address = section.GetAttributeValue("address");
4587 module.set_base(
4588 StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4589 // These addresses are absolute values.
4590 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004591
Kate Stoneb9c1b512016-09-06 20:57:50 +00004592 if (log) {
4593 std::string name;
4594 lldb::addr_t base = 0;
4595 bool base_is_offset;
4596 module.get_name(name);
4597 module.get_base(base);
4598 module.get_base_is_offset(base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004599
Kate Stoneb9c1b512016-09-06 20:57:50 +00004600 log->Printf("found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4601 (base_is_offset ? "offset" : "absolute"), name.c_str());
4602 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004603
Kate Stoneb9c1b512016-09-06 20:57:50 +00004604 list.add(module);
4605 return true; // Keep iterating over all "library" elements in the root
4606 // node
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004607 });
4608
Kate Stoneb9c1b512016-09-06 20:57:50 +00004609 if (log)
4610 log->Printf("found %" PRId32 " modules in total",
4611 (int)list.m_list.size());
4612 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00004613 return Status(0, ErrorType::eErrorTypeGeneric);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004614 }
4615
Zachary Turner97206d52017-05-12 04:51:55 +00004616 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004617}
4618
4619lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4620 lldb::addr_t link_map,
4621 lldb::addr_t base_addr,
4622 bool value_is_offset) {
4623 DynamicLoader *loader = GetDynamicLoader();
4624 if (!loader)
4625 return nullptr;
4626
4627 return loader->LoadModuleAtAddress(file, link_map, base_addr,
4628 value_is_offset);
4629}
4630
4631size_t ProcessGDBRemote::LoadModules(LoadedModuleInfoList &module_list) {
4632 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4633
4634 // request a list of loaded libraries from GDBServer
4635 if (GetLoadedModuleList(module_list).Fail())
4636 return 0;
4637
4638 // get a list of all the modules
4639 ModuleList new_modules;
4640
4641 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list.m_list) {
4642 std::string mod_name;
4643 lldb::addr_t mod_base;
4644 lldb::addr_t link_map;
4645 bool mod_base_is_offset;
4646
4647 bool valid = true;
4648 valid &= modInfo.get_name(mod_name);
4649 valid &= modInfo.get_base(mod_base);
4650 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4651 if (!valid)
4652 continue;
4653
4654 if (!modInfo.get_link_map(link_map))
4655 link_map = LLDB_INVALID_ADDRESS;
4656
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00004657 FileSpec file(mod_name, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004658 lldb::ModuleSP module_sp =
4659 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4660
4661 if (module_sp.get())
4662 new_modules.Append(module_sp);
4663 }
4664
4665 if (new_modules.GetSize() > 0) {
4666 ModuleList removed_modules;
4667 Target &target = GetTarget();
4668 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4669
4670 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4671 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4672
4673 bool found = false;
4674 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4675 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4676 found = true;
4677 }
4678
4679 // The main executable will never be included in libraries-svr4, don't
4680 // remove it
4681 if (!found &&
4682 loaded_module.get() != target.GetExecutableModulePointer()) {
4683 removed_modules.Append(loaded_module);
4684 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004685 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004686
Kate Stoneb9c1b512016-09-06 20:57:50 +00004687 loaded_modules.Remove(removed_modules);
4688 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4689
4690 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4691 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4692 if (!obj)
4693 return true;
4694
4695 if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4696 return true;
4697
4698 lldb::ModuleSP module_copy_sp = module_sp;
4699 target.SetExecutableModule(module_copy_sp, false);
4700 return false;
4701 });
4702
4703 loaded_modules.AppendIfNeeded(new_modules);
4704 m_process->GetTarget().ModulesDidLoad(new_modules);
4705 }
4706
4707 return new_modules.GetSize();
4708}
4709
4710size_t ProcessGDBRemote::LoadModules() {
4711 LoadedModuleInfoList module_list;
4712 return LoadModules(module_list);
4713}
4714
Zachary Turner97206d52017-05-12 04:51:55 +00004715Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4716 bool &is_loaded,
4717 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004718 is_loaded = false;
4719 load_addr = LLDB_INVALID_ADDRESS;
4720
4721 std::string file_path = file.GetPath(false);
4722 if (file_path.empty())
Zachary Turner97206d52017-05-12 04:51:55 +00004723 return Status("Empty file name specified");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004724
4725 StreamString packet;
4726 packet.PutCString("qFileLoadAddress:");
4727 packet.PutCStringAsRawHex8(file_path.c_str());
4728
4729 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004730 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4731 false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00004732 GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00004733 return Status("Sending qFileLoadAddress packet failed");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004734
4735 if (response.IsErrorResponse()) {
4736 if (response.GetError() == 1) {
4737 // The file is not loaded into the inferior
4738 is_loaded = false;
4739 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00004740 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004741 }
4742
Zachary Turner97206d52017-05-12 04:51:55 +00004743 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004744 "Fetching file load address from remote server returned an error");
4745 }
4746
4747 if (response.IsNormalResponse()) {
4748 is_loaded = true;
4749 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
Zachary Turner97206d52017-05-12 04:51:55 +00004750 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004751 }
4752
Zachary Turner97206d52017-05-12 04:51:55 +00004753 return Status(
4754 "Unknown error happened during sending the load address packet");
Aidan Doddsc0c83852015-05-08 09:36:31 +00004755}
4756
Kate Stoneb9c1b512016-09-06 20:57:50 +00004757void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4758 // We must call the lldb_private::Process::ModulesDidLoad () first before we
4759 // do anything
4760 Process::ModulesDidLoad(module_list);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004761
Kate Stoneb9c1b512016-09-06 20:57:50 +00004762 // After loading shared libraries, we can ask our remote GDB server if
4763 // it needs any symbols.
4764 m_gdb_comm.ServeSymbolLookups(this);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004765}
4766
Kate Stoneb9c1b512016-09-06 20:57:50 +00004767void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4768 AppendSTDOUT(out.data(), out.size());
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004769}
4770
4771static const char *end_delimiter = "--end--;";
4772static const int end_delimiter_len = 8;
4773
Kate Stoneb9c1b512016-09-06 20:57:50 +00004774void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4775 std::string input = data.str(); // '1' to move beyond 'A'
4776 if (m_partial_profile_data.length() > 0) {
4777 m_partial_profile_data.append(input);
4778 input = m_partial_profile_data;
4779 m_partial_profile_data.clear();
4780 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004781
Kate Stoneb9c1b512016-09-06 20:57:50 +00004782 size_t found, pos = 0, len = input.length();
4783 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4784 StringExtractorGDBRemote profileDataExtractor(
4785 input.substr(pos, found).c_str());
4786 std::string profile_data =
4787 HarmonizeThreadIdsForProfileData(profileDataExtractor);
4788 BroadcastAsyncProfileData(profile_data);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004789
Kate Stoneb9c1b512016-09-06 20:57:50 +00004790 pos = found + end_delimiter_len;
4791 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004792
Kate Stoneb9c1b512016-09-06 20:57:50 +00004793 if (pos < len) {
4794 // Last incomplete chunk.
4795 m_partial_profile_data = input.substr(pos);
4796 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004797}
4798
Kate Stoneb9c1b512016-09-06 20:57:50 +00004799std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4800 StringExtractorGDBRemote &profileDataExtractor) {
4801 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4802 std::string output;
4803 llvm::raw_string_ostream output_stream(output);
4804 llvm::StringRef name, value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004805
Kate Stoneb9c1b512016-09-06 20:57:50 +00004806 // Going to assuming thread_used_usec comes first, else bail out.
4807 while (profileDataExtractor.GetNameColonValue(name, value)) {
4808 if (name.compare("thread_used_id") == 0) {
4809 StringExtractor threadIDHexExtractor(value);
4810 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004811
Kate Stoneb9c1b512016-09-06 20:57:50 +00004812 bool has_used_usec = false;
4813 uint32_t curr_used_usec = 0;
4814 llvm::StringRef usec_name, usec_value;
4815 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4816 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4817 if (usec_name.equals("thread_used_usec")) {
4818 has_used_usec = true;
4819 usec_value.getAsInteger(0, curr_used_usec);
4820 } else {
4821 // We didn't find what we want, it is probably
4822 // an older version. Bail out.
4823 profileDataExtractor.SetFilePos(input_file_pos);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004824 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004825 }
4826
4827 if (has_used_usec) {
4828 uint32_t prev_used_usec = 0;
4829 std::map<uint64_t, uint32_t>::iterator iterator =
4830 m_thread_id_to_used_usec_map.find(thread_id);
4831 if (iterator != m_thread_id_to_used_usec_map.end()) {
4832 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004833 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004834
4835 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4836 // A good first time record is one that runs for at least 0.25 sec
4837 bool good_first_time =
4838 (prev_used_usec == 0) && (real_used_usec > 250000);
4839 bool good_subsequent_time =
4840 (prev_used_usec > 0) &&
4841 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4842
4843 if (good_first_time || good_subsequent_time) {
4844 // We try to avoid doing too many index id reservation,
4845 // resulting in fast increase of index ids.
4846
4847 output_stream << name << ":";
4848 int32_t index_id = AssignIndexIDToThread(thread_id);
4849 output_stream << index_id << ";";
4850
4851 output_stream << usec_name << ":" << usec_value << ";";
4852 } else {
4853 // Skip past 'thread_used_name'.
4854 llvm::StringRef local_name, local_value;
4855 profileDataExtractor.GetNameColonValue(local_name, local_value);
4856 }
4857
4858 // Store current time as previous time so that they can be compared
4859 // later.
4860 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4861 } else {
4862 // Bail out and use old string.
4863 output_stream << name << ":" << value << ";";
4864 }
4865 } else {
4866 output_stream << name << ":" << value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004867 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004868 }
4869 output_stream << end_delimiter;
4870 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004871
Kate Stoneb9c1b512016-09-06 20:57:50 +00004872 return output_stream.str();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004873}
4874
Kate Stoneb9c1b512016-09-06 20:57:50 +00004875void ProcessGDBRemote::HandleStopReply() {
4876 if (GetStopID() != 0)
4877 return;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004878
Kate Stoneb9c1b512016-09-06 20:57:50 +00004879 if (GetID() == LLDB_INVALID_PROCESS_ID) {
4880 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
4881 if (pid != LLDB_INVALID_PROCESS_ID)
4882 SetID(pid);
4883 }
4884 BuildDynamicRegisterInfo(true);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004885}
Eugene Zelenko0722f082015-10-24 01:28:05 +00004886
Todd Fialafcdb1af2016-09-10 00:06:29 +00004887static const char *const s_async_json_packet_prefix = "JSON-async:";
4888
4889static StructuredData::ObjectSP
4890ParseStructuredDataPacket(llvm::StringRef packet) {
4891 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
4892
4893 if (!packet.consume_front(s_async_json_packet_prefix)) {
4894 if (log) {
4895 log->Printf(
4896 "GDBRemoteCommmunicationClientBase::%s() received $J packet "
4897 "but was not a StructuredData packet: packet starts with "
4898 "%s",
4899 __FUNCTION__,
4900 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
4901 }
4902 return StructuredData::ObjectSP();
4903 }
4904
4905 // This is an asynchronous JSON packet, destined for a
4906 // StructuredDataPlugin.
4907 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
4908 if (log) {
4909 if (json_sp) {
4910 StreamString json_str;
4911 json_sp->Dump(json_str);
4912 json_str.Flush();
4913 log->Printf("ProcessGDBRemote::%s() "
4914 "received Async StructuredData packet: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00004915 __FUNCTION__, json_str.GetData());
Todd Fialafcdb1af2016-09-10 00:06:29 +00004916 } else {
4917 log->Printf("ProcessGDBRemote::%s"
4918 "() received StructuredData packet:"
4919 " parse failure",
4920 __FUNCTION__);
4921 }
4922 }
4923 return json_sp;
4924}
4925
4926void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
4927 auto structured_data_sp = ParseStructuredDataPacket(data);
4928 if (structured_data_sp)
4929 RouteAsyncStructuredData(structured_data_sp);
Todd Fiala75930012016-08-19 04:21:48 +00004930}
4931
Kate Stoneb9c1b512016-09-06 20:57:50 +00004932class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
Greg Claytone034a042015-05-21 20:52:06 +00004933public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004934 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
4935 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
4936 "Tests packet speeds of various sizes to determine "
4937 "the performance characteristics of the GDB remote "
4938 "connection. ",
4939 NULL),
4940 m_option_group(),
4941 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
4942 "The number of packets to send of each varying size "
4943 "(default is 1000).",
4944 1000),
4945 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
4946 "The maximum number of bytes to send in a packet. Sizes "
4947 "increase in powers of 2 while the size is less than or "
4948 "equal to this option value. (default 1024).",
4949 1024),
4950 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
4951 "The maximum number of bytes to receive in a packet. Sizes "
4952 "increase in powers of 2 while the size is less than or "
4953 "equal to this option value. (default 1024).",
4954 1024),
4955 m_json(LLDB_OPT_SET_1, false, "json", 'j',
4956 "Print the output as JSON data for easy parsing.", false, true) {
4957 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4958 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4959 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4960 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4961 m_option_group.Finalize();
4962 }
Greg Claytone034a042015-05-21 20:52:06 +00004963
Kate Stoneb9c1b512016-09-06 20:57:50 +00004964 ~CommandObjectProcessGDBRemoteSpeedTest() {}
Eugene Zelenko0722f082015-10-24 01:28:05 +00004965
Kate Stoneb9c1b512016-09-06 20:57:50 +00004966 Options *GetOptions() override { return &m_option_group; }
Greg Claytone034a042015-05-21 20:52:06 +00004967
Kate Stoneb9c1b512016-09-06 20:57:50 +00004968 bool DoExecute(Args &command, CommandReturnObject &result) override {
4969 const size_t argc = command.GetArgumentCount();
4970 if (argc == 0) {
4971 ProcessGDBRemote *process =
4972 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
4973 .GetProcessPtr();
4974 if (process) {
4975 StreamSP output_stream_sp(
4976 m_interpreter.GetDebugger().GetAsyncOutputStream());
4977 result.SetImmediateOutputStream(output_stream_sp);
Greg Claytone034a042015-05-21 20:52:06 +00004978
Kate Stoneb9c1b512016-09-06 20:57:50 +00004979 const uint32_t num_packets =
4980 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4981 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4982 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4983 const bool json = m_json.GetOptionValue().GetCurrentValue();
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00004984 const uint64_t k_recv_amount =
4985 4 * 1024 * 1024; // Receive amount in bytes
4986 process->GetGDBRemote().TestPacketSpeed(
4987 num_packets, max_send, max_recv, k_recv_amount, json,
4988 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004989 result.SetStatus(eReturnStatusSuccessFinishResult);
4990 return true;
4991 }
4992 } else {
4993 result.AppendErrorWithFormat("'%s' takes no arguments",
4994 m_cmd_name.c_str());
Greg Claytone034a042015-05-21 20:52:06 +00004995 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004996 result.SetStatus(eReturnStatusFailed);
4997 return false;
4998 }
4999
Greg Claytone034a042015-05-21 20:52:06 +00005000protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005001 OptionGroupOptions m_option_group;
5002 OptionGroupUInt64 m_num_packets;
5003 OptionGroupUInt64 m_max_send;
5004 OptionGroupUInt64 m_max_recv;
5005 OptionGroupBoolean m_json;
Greg Claytone034a042015-05-21 20:52:06 +00005006};
5007
Kate Stoneb9c1b512016-09-06 20:57:50 +00005008class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005009private:
Greg Clayton998255b2012-10-13 02:07:45 +00005010public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005011 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5012 : CommandObjectParsed(interpreter, "process plugin packet history",
5013 "Dumps the packet history buffer. ", NULL) {}
5014
5015 ~CommandObjectProcessGDBRemotePacketHistory() {}
5016
5017 bool DoExecute(Args &command, CommandReturnObject &result) override {
5018 const size_t argc = command.GetArgumentCount();
5019 if (argc == 0) {
5020 ProcessGDBRemote *process =
5021 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5022 .GetProcessPtr();
5023 if (process) {
5024 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5025 result.SetStatus(eReturnStatusSuccessFinishResult);
5026 return true;
5027 }
5028 } else {
5029 result.AppendErrorWithFormat("'%s' takes no arguments",
5030 m_cmd_name.c_str());
5031 }
5032 result.SetStatus(eReturnStatusFailed);
5033 return false;
5034 }
5035};
5036
5037class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5038private:
5039public:
5040 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5041 : CommandObjectParsed(
5042 interpreter, "process plugin packet xfer-size",
5043 "Maximum size that lldb will try to read/write one one chunk.",
5044 NULL) {}
5045
5046 ~CommandObjectProcessGDBRemotePacketXferSize() {}
5047
5048 bool DoExecute(Args &command, CommandReturnObject &result) override {
5049 const size_t argc = command.GetArgumentCount();
5050 if (argc == 0) {
5051 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5052 "amount to be transferred when "
5053 "reading/writing",
5054 m_cmd_name.c_str());
5055 result.SetStatus(eReturnStatusFailed);
5056 return false;
Greg Clayton998255b2012-10-13 02:07:45 +00005057 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005058
Kate Stoneb9c1b512016-09-06 20:57:50 +00005059 ProcessGDBRemote *process =
5060 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5061 if (process) {
5062 const char *packet_size = command.GetArgumentAtIndex(0);
5063 errno = 0;
5064 uint64_t user_specified_max = strtoul(packet_size, NULL, 10);
5065 if (errno == 0 && user_specified_max != 0) {
5066 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5067 result.SetStatus(eReturnStatusSuccessFinishResult);
5068 return true;
5069 }
5070 }
5071 result.SetStatus(eReturnStatusFailed);
5072 return false;
5073 }
5074};
5075
5076class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5077private:
5078public:
5079 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5080 : CommandObjectParsed(interpreter, "process plugin packet send",
5081 "Send a custom packet through the GDB remote "
5082 "protocol and print the answer. "
5083 "The packet header and footer will automatically "
5084 "be added to the packet prior to sending and "
5085 "stripped from the result.",
5086 NULL) {}
5087
5088 ~CommandObjectProcessGDBRemotePacketSend() {}
5089
5090 bool DoExecute(Args &command, CommandReturnObject &result) override {
5091 const size_t argc = command.GetArgumentCount();
5092 if (argc == 0) {
5093 result.AppendErrorWithFormat(
5094 "'%s' takes a one or more packet content arguments",
5095 m_cmd_name.c_str());
5096 result.SetStatus(eReturnStatusFailed);
5097 return false;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005098 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005099
Kate Stoneb9c1b512016-09-06 20:57:50 +00005100 ProcessGDBRemote *process =
5101 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5102 if (process) {
5103 for (size_t i = 0; i < argc; ++i) {
5104 const char *packet_cstr = command.GetArgumentAtIndex(0);
5105 bool send_async = true;
5106 StringExtractorGDBRemote response;
5107 process->GetGDBRemote().SendPacketAndWaitForResponse(
5108 packet_cstr, response, send_async);
5109 result.SetStatus(eReturnStatusSuccessFinishResult);
5110 Stream &output_strm = result.GetOutputStream();
5111 output_strm.Printf(" packet: %s\n", packet_cstr);
5112 std::string &response_str = response.GetStringRef();
5113
5114 if (strstr(packet_cstr, "qGetProfileData") != NULL) {
5115 response_str = process->HarmonizeThreadIdsForProfileData(response);
Greg Clayton02686b82012-10-15 22:42:16 +00005116 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005117
5118 if (response_str.empty())
5119 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
Greg Clayton02686b82012-10-15 22:42:16 +00005120 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005121 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5122 }
Greg Clayton02686b82012-10-15 22:42:16 +00005123 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005124 return true;
5125 }
Greg Clayton02686b82012-10-15 22:42:16 +00005126};
5127
Kate Stoneb9c1b512016-09-06 20:57:50 +00005128class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005129private:
Jason Molenda6076bf42014-05-06 04:34:52 +00005130public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005131 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5132 : CommandObjectRaw(interpreter, "process plugin packet monitor",
5133 "Send a qRcmd packet through the GDB remote protocol "
5134 "and print the response."
5135 "The argument passed to this command will be hex "
5136 "encoded into a valid 'qRcmd' packet, sent and the "
Zachary Turnera4496982016-10-05 21:14:38 +00005137 "response will be printed.") {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005138
5139 ~CommandObjectProcessGDBRemotePacketMonitor() {}
5140
5141 bool DoExecute(const char *command, CommandReturnObject &result) override {
5142 if (command == NULL || command[0] == '\0') {
5143 result.AppendErrorWithFormat("'%s' takes a command string argument",
5144 m_cmd_name.c_str());
5145 result.SetStatus(eReturnStatusFailed);
5146 return false;
Jason Molenda6076bf42014-05-06 04:34:52 +00005147 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005148
Kate Stoneb9c1b512016-09-06 20:57:50 +00005149 ProcessGDBRemote *process =
5150 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5151 if (process) {
5152 StreamString packet;
5153 packet.PutCString("qRcmd,");
5154 packet.PutBytesAsRawHex8(command, strlen(command));
Ed Maste81b4c5f2016-01-04 01:43:47 +00005155
Kate Stoneb9c1b512016-09-06 20:57:50 +00005156 bool send_async = true;
5157 StringExtractorGDBRemote response;
5158 process->GetGDBRemote().SendPacketAndWaitForResponse(
Pavel Labath0f8f0d32016-09-23 09:11:49 +00005159 packet.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005160 result.SetStatus(eReturnStatusSuccessFinishResult);
5161 Stream &output_strm = result.GetOutputStream();
Zachary Turnerc1564272016-11-16 21:15:24 +00005162 output_strm.Printf(" packet: %s\n", packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005163 const std::string &response_str = response.GetStringRef();
Jason Molenda6076bf42014-05-06 04:34:52 +00005164
Kate Stoneb9c1b512016-09-06 20:57:50 +00005165 if (response_str.empty())
5166 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5167 else
5168 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
Jason Molenda6076bf42014-05-06 04:34:52 +00005169 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005170 return true;
5171 }
Jason Molenda6076bf42014-05-06 04:34:52 +00005172};
5173
Kate Stoneb9c1b512016-09-06 20:57:50 +00005174class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005175private:
Greg Clayton02686b82012-10-15 22:42:16 +00005176public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005177 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5178 : CommandObjectMultiword(interpreter, "process plugin packet",
5179 "Commands that deal with GDB remote packets.",
5180 NULL) {
5181 LoadSubCommand(
5182 "history",
5183 CommandObjectSP(
5184 new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5185 LoadSubCommand(
5186 "send", CommandObjectSP(
5187 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5188 LoadSubCommand(
5189 "monitor",
5190 CommandObjectSP(
5191 new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5192 LoadSubCommand(
5193 "xfer-size",
5194 CommandObjectSP(
5195 new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5196 LoadSubCommand("speed-test",
5197 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5198 interpreter)));
5199 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005200
Kate Stoneb9c1b512016-09-06 20:57:50 +00005201 ~CommandObjectProcessGDBRemotePacket() {}
Greg Clayton998255b2012-10-13 02:07:45 +00005202};
5203
Kate Stoneb9c1b512016-09-06 20:57:50 +00005204class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
Greg Claytonba4a0a52013-02-01 23:03:47 +00005205public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005206 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5207 : CommandObjectMultiword(
5208 interpreter, "process plugin",
5209 "Commands for operating on a ProcessGDBRemote process.",
5210 "process plugin <subcommand> [<subcommand-options>]") {
5211 LoadSubCommand(
5212 "packet",
5213 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5214 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005215
Kate Stoneb9c1b512016-09-06 20:57:50 +00005216 ~CommandObjectMultiwordProcessGDBRemote() {}
Greg Claytonba4a0a52013-02-01 23:03:47 +00005217};
5218
Kate Stoneb9c1b512016-09-06 20:57:50 +00005219CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5220 if (!m_command_sp)
5221 m_command_sp.reset(new CommandObjectMultiwordProcessGDBRemote(
5222 GetTarget().GetDebugger().GetCommandInterpreter()));
5223 return m_command_sp.get();
Greg Clayton998255b2012-10-13 02:07:45 +00005224}