blob: b3338f3b4b76e98d2c6b3e124cb38b779631310f [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>
Pavel Labath6b3c8bb2018-04-05 16:23:54 +000027#include <csignal>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000028#include <map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000029#include <mutex>
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000030#include <sstream>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031
Johnny Chen01a67862011-10-14 00:42:25 +000032#include "lldb/Breakpoint/Watchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000035#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Core/PluginManager.h"
37#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000038#include "lldb/Core/StreamFile.h"
Greg Clayton70b57652011-05-15 01:25:55 +000039#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000040#include "lldb/DataFormatters/FormatManager.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000041#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000042#include "lldb/Host/FileSystem.h"
Zachary Turner39de3112014-09-09 20:54:56 +000043#include "lldb/Host/HostThread.h"
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000044#include "lldb/Host/PosixApi.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000045#include "lldb/Host/PseudoTerminal.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000046#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000047#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000048#include "lldb/Host/ThreadLauncher.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000049#include "lldb/Host/XML.h"
Greg Clayton02686b82012-10-15 22:42:16 +000050#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000051#include "lldb/Interpreter/CommandObject.h"
52#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000053#include "lldb/Interpreter/CommandReturnObject.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000054#include "lldb/Interpreter/OptionArgParser.h"
Greg Claytone034a042015-05-21 20:52:06 +000055#include "lldb/Interpreter/OptionGroupBoolean.h"
56#include "lldb/Interpreter/OptionGroupUInt64.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000057#include "lldb/Interpreter/OptionValueProperties.h"
58#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000059#include "lldb/Interpreter/Property.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000060#include "lldb/Symbol/ObjectFile.h"
Jason Molenda21586c82015-09-09 03:36:24 +000061#include "lldb/Target/ABI.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000062#include "lldb/Target/DynamicLoader.h"
Pavel Labath16064d32018-03-20 11:56:24 +000063#include "lldb/Target/MemoryRegionInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000064#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065#include "lldb/Target/Target.h"
66#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000067#include "lldb/Target/ThreadPlanCallFunction.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000068#include "lldb/Utility/Args.h"
Greg Claytonc6c420f2016-08-12 16:46:18 +000069#include "lldb/Utility/CleanUp.h"
Zachary Turner5713a052017-03-22 18:40:07 +000070#include "lldb/Utility/FileSpec.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000071#include "lldb/Utility/StreamString.h"
Pavel Labath38d06322017-06-29 14:32:17 +000072#include "lldb/Utility/Timer.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073
Eugene Zelenko0722f082015-10-24 01:28:05 +000074// Project includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000075#include "GDBRemoteRegisterContext.h"
76#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000077#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000078#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000079#include "Plugins/Process/Utility/StopInfoMachException.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000080#include "ProcessGDBRemote.h"
81#include "ProcessGDBRemoteLog.h"
82#include "ThreadGDBRemote.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000083#include "lldb/Host/Host.h"
Pavel Labath9af71b32018-03-20 16:14:00 +000084#include "lldb/Utility/StringExtractorGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000085
Zachary Turner54695a32016-08-29 19:58:14 +000086#include "llvm/ADT/StringSwitch.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000087#include "llvm/Support/Threading.h"
Eugene Zemtsov7993cc52017-03-07 21:34:40 +000088#include "llvm/Support/raw_ostream.h"
Zachary Turner54695a32016-08-29 19:58:14 +000089
Kate Stoneb9c1b512016-09-06 20:57:50 +000090#define DEBUGSERVER_BASENAME "debugserver"
Tamas Berghammerdb264a62015-03-31 09:52:22 +000091using namespace lldb;
92using namespace lldb_private;
93using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000094
Kate Stoneb9c1b512016-09-06 20:57:50 +000095namespace lldb {
96// Provide a function that can easily dump the packet history if we know a
Adrian Prantl05097242018-04-30 16:49:04 +000097// ProcessGDBRemote * value (which we can get from logs or from debugging). We
98// need the function in the lldb namespace so it makes it into the final
Kate Stoneb9c1b512016-09-06 20:57:50 +000099// executable since the LLDB shared library only exports stuff in the lldb
Adrian Prantl05097242018-04-30 16:49:04 +0000100// namespace. This allows you to attach with a debugger and call this function
101// and get the packet history dumped to a file.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
103 StreamFile strm;
Zachary Turner97206d52017-05-12 04:51:55 +0000104 Status error(strm.GetFile().Open(path, File::eOpenOptionWrite |
105 File::eOpenOptionCanCreate));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 if (error.Success())
107 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(strm);
108}
Eugene Zelenko0722f082015-10-24 01:28:05 +0000109}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000110
Greg Clayton7f982402013-07-15 22:54:20 +0000111namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000112
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113static PropertyDefinition g_properties[] = {
114 {"packet-timeout", OptionValue::eTypeUInt64, true, 1, NULL, NULL,
115 "Specify the default packet timeout in seconds."},
116 {"target-definition-file", OptionValue::eTypeFileSpec, true, 0, NULL, NULL,
117 "The file that provides the description for remote target registers."},
118 {NULL, OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL}};
Ed Maste81b4c5f2016-01-04 01:43:47 +0000119
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120enum { ePropertyPacketTimeout, ePropertyTargetDefinitionFile };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000121
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122class PluginProperties : public Properties {
123public:
124 static ConstString GetSettingName() {
125 return ProcessGDBRemote::GetPluginNameStatic();
126 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000127
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 PluginProperties() : Properties() {
129 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
130 m_collection_sp->Initialize(g_properties);
131 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 virtual ~PluginProperties() {}
Ed Maste81b4c5f2016-01-04 01:43:47 +0000134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 uint64_t GetPacketTimeout() {
136 const uint32_t idx = ePropertyPacketTimeout;
137 return m_collection_sp->GetPropertyAtIndexAsUInt64(
138 NULL, idx, g_properties[idx].default_uint_value);
139 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 bool SetPacketTimeout(uint64_t timeout) {
142 const uint32_t idx = ePropertyPacketTimeout;
143 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
144 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146 FileSpec GetTargetDefinitionFile() const {
147 const uint32_t idx = ePropertyTargetDefinitionFile;
148 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
149 }
150};
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000151
Kate Stoneb9c1b512016-09-06 20:57:50 +0000152typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000153
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
155 static ProcessKDPPropertiesSP g_settings_sp;
156 if (!g_settings_sp)
157 g_settings_sp.reset(new PluginProperties());
158 return g_settings_sp;
159}
Ed Maste81b4c5f2016-01-04 01:43:47 +0000160
Eugene Zelenko0722f082015-10-24 01:28:05 +0000161} // anonymous namespace end
Greg Clayton7f982402013-07-15 22:54:20 +0000162
Greg Claytonfda4fab2014-01-10 22:24:11 +0000163// TODO Randomly assigning a port is unsafe. We should get an unused
Adrian Prantl05097242018-04-30 16:49:04 +0000164// ephemeral port from the kernel and make sure we reserve it before passing it
165// to debugserver.
Greg Claytonfda4fab2014-01-10 22:24:11 +0000166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167#if defined(__APPLE__)
168#define LOW_PORT (IPPORT_RESERVED)
169#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
Greg Claytonfda4fab2014-01-10 22:24:11 +0000170#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171#define LOW_PORT (1024u)
172#define HIGH_PORT (49151u)
Greg Claytonfda4fab2014-01-10 22:24:11 +0000173#endif
174
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175#if defined(__APPLE__) && \
176 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000177static bool rand_initialized = false;
178
Kate Stoneb9c1b512016-09-06 20:57:50 +0000179static inline uint16_t get_random_port() {
180 if (!rand_initialized) {
181 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000182
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183 rand_initialized = true;
184 srand(seed);
185 }
186 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Greg Claytonfda4fab2014-01-10 22:24:11 +0000187}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000188#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000189
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190ConstString ProcessGDBRemote::GetPluginNameStatic() {
191 static ConstString g_name("gdb-remote");
192 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195const char *ProcessGDBRemote::GetPluginDescriptionStatic() {
196 return "GDB Remote protocol based debugging plug-in.";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000197}
198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199void ProcessGDBRemote::Terminate() {
200 PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000201}
202
Greg Claytonc3776bf2012-02-09 06:16:32 +0000203lldb::ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
205 ListenerSP listener_sp,
206 const FileSpec *crash_file_path) {
207 lldb::ProcessSP process_sp;
208 if (crash_file_path == NULL)
209 process_sp.reset(new ProcessGDBRemote(target_sp, listener_sp));
210 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000211}
212
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
214 bool plugin_specified_by_name) {
215 if (plugin_specified_by_name)
Jim Ingham5aee1622010-08-09 23:31:02 +0000216 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217
218 // For now we are just making sure the file exists for a given module
219 Module *exe_module = target_sp->GetExecutableModulePointer();
220 if (exe_module) {
221 ObjectFile *exe_objfile = exe_module->GetObjectFile();
222 // We can't debug core files...
223 switch (exe_objfile->GetType()) {
224 case ObjectFile::eTypeInvalid:
225 case ObjectFile::eTypeCoreFile:
226 case ObjectFile::eTypeDebugInfo:
227 case ObjectFile::eTypeObjectFile:
228 case ObjectFile::eTypeSharedLibrary:
229 case ObjectFile::eTypeStubLibrary:
230 case ObjectFile::eTypeJIT:
231 return false;
232 case ObjectFile::eTypeExecutable:
233 case ObjectFile::eTypeDynamicLinker:
234 case ObjectFile::eTypeUnknown:
235 break;
236 }
237 return exe_module->GetFileSpec().Exists();
238 }
Adrian Prantl05097242018-04-30 16:49:04 +0000239 // However, if there is no executable module, we return true since we might
240 // be preparing to attach.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000242}
243
Eugene Zelenko0722f082015-10-24 01:28:05 +0000244//----------------------------------------------------------------------
245// ProcessGDBRemote constructor
246//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
248 ListenerSP listener_sp)
Pavel Labatha9640122017-11-03 22:12:50 +0000249 : Process(target_sp, listener_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_last_stop_packet_mutex(),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000251 m_register_info(),
252 m_async_broadcaster(NULL, "lldb.process.gdb-remote.async-broadcaster"),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 m_async_listener_sp(
254 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
255 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
256 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
257 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
258 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
259 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
260 m_waiting_for_attach(false), m_destroy_tried_resuming(false),
261 m_command_sp(), m_breakpoint_pc_offset(0),
Pavel Labath16064d32018-03-20 11:56:24 +0000262 m_initial_tid(LLDB_INVALID_THREAD_ID), m_allow_flash_writes(false),
263 m_erased_flash_ranges() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
265 "async thread should exit");
266 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
267 "async thread continue");
268 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
269 "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
Pavel Labath50556852015-09-03 09:36:22 +0000272
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273 const uint32_t async_event_mask =
274 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
Pavel Labath50556852015-09-03 09:36:22 +0000275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 if (m_async_listener_sp->StartListeningForEvents(
277 &m_async_broadcaster, async_event_mask) != async_event_mask) {
278 if (log)
279 log->Printf("ProcessGDBRemote::%s failed to listen for "
280 "m_async_broadcaster events",
281 __FUNCTION__);
282 }
Pavel Labath50556852015-09-03 09:36:22 +0000283
Kate Stoneb9c1b512016-09-06 20:57:50 +0000284 const uint32_t gdb_event_mask =
285 Communication::eBroadcastBitReadThreadDidExit |
286 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
287 if (m_async_listener_sp->StartListeningForEvents(
288 &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
289 if (log)
290 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
291 __FUNCTION__);
292 }
Pavel Labath50556852015-09-03 09:36:22 +0000293
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294 const uint64_t timeout_seconds =
295 GetGlobalPluginProperties()->GetPacketTimeout();
296 if (timeout_seconds > 0)
Pavel Labath3aa04912016-10-31 17:19:42 +0000297 m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000298}
299
Eugene Zelenko0722f082015-10-24 01:28:05 +0000300//----------------------------------------------------------------------
301// Destructor
302//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303ProcessGDBRemote::~ProcessGDBRemote() {
304 // m_mach_process.UnregisterNotificationCallbacks (this);
305 Clear();
Adrian Prantl05097242018-04-30 16:49:04 +0000306 // We need to call finalize on the process before destroying ourselves to
307 // make sure all of the broadcaster cleanup goes as planned. If we destruct
308 // this class, then Process::~Process() might have problems trying to fully
309 // destroy the broadcaster.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000310 Finalize();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000311
Adrian Prantl05097242018-04-30 16:49:04 +0000312 // The general Finalize is going to try to destroy the process and that
313 // SHOULD shut down the async thread. However, if we don't kill it it will
314 // get stranded and its connection will go away so when it wakes up it will
315 // crash. So kill it for sure here.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316 StopAsyncThread();
317 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318}
319
320//----------------------------------------------------------------------
321// PluginInterface
322//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000324
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000326
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327bool ProcessGDBRemote::ParsePythonTargetDefinition(
328 const FileSpec &target_definition_fspec) {
329 ScriptInterpreter *interpreter =
330 GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Zachary Turner97206d52017-05-12 04:51:55 +0000331 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 StructuredData::ObjectSP module_object_sp(
333 interpreter->LoadPluginModule(target_definition_fspec, error));
334 if (module_object_sp) {
335 StructuredData::DictionarySP target_definition_sp(
336 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
337 "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000338
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339 if (target_definition_sp) {
340 StructuredData::ObjectSP target_object(
341 target_definition_sp->GetValueForKey("host-info"));
342 if (target_object) {
343 if (auto host_info_dict = target_object->GetAsDictionary()) {
344 StructuredData::ObjectSP triple_value =
345 host_info_dict->GetValueForKey("triple");
346 if (auto triple_string_value = triple_value->GetAsString()) {
347 std::string triple_string = triple_string_value->GetValue();
348 ArchSpec host_arch(triple_string.c_str());
349 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
350 GetTarget().SetArchitecture(host_arch);
Greg Clayton312bcbe2013-10-17 01:10:23 +0000351 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 }
Greg Claytonef8180a2013-10-15 00:14:28 +0000353 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 }
355 m_breakpoint_pc_offset = 0;
356 StructuredData::ObjectSP breakpoint_pc_offset_value =
357 target_definition_sp->GetValueForKey("breakpoint-pc-offset");
358 if (breakpoint_pc_offset_value) {
359 if (auto breakpoint_pc_int_value =
360 breakpoint_pc_offset_value->GetAsInteger())
361 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
362 }
363
364 if (m_register_info.SetRegisterInfo(*target_definition_sp,
365 GetTarget().GetArchitecture()) > 0) {
366 return true;
367 }
Greg Claytonef8180a2013-10-15 00:14:28 +0000368 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 }
370 return false;
Greg Claytonef8180a2013-10-15 00:14:28 +0000371}
372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373// If the remote stub didn't give us eh_frame or DWARF register numbers for a
Adrian Prantl05097242018-04-30 16:49:04 +0000374// register, see if the ABI can provide them.
Jason Molenda21586c82015-09-09 03:36:24 +0000375// DWARF and eh_frame register numbers are defined as a part of the ABI.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376static void AugmentRegisterInfoViaABI(RegisterInfo &reg_info,
377 ConstString reg_name, ABISP abi_sp) {
378 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM ||
379 reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM) {
380 if (abi_sp) {
381 RegisterInfo abi_reg_info;
382 if (abi_sp->GetRegisterInfoByName(reg_name, abi_reg_info)) {
383 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM &&
384 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM) {
385 reg_info.kinds[eRegisterKindEHFrame] =
386 abi_reg_info.kinds[eRegisterKindEHFrame];
387 }
388 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM &&
389 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM) {
390 reg_info.kinds[eRegisterKindDWARF] =
391 abi_reg_info.kinds[eRegisterKindDWARF];
392 }
393 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM &&
394 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM) {
395 reg_info.kinds[eRegisterKindGeneric] =
396 abi_reg_info.kinds[eRegisterKindGeneric];
397 }
398 }
399 }
400 }
401}
402
403static size_t SplitCommaSeparatedRegisterNumberString(
404 const llvm::StringRef &comma_separated_regiter_numbers,
405 std::vector<uint32_t> &regnums, int base) {
406 regnums.clear();
407 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
408 value_pair.second = comma_separated_regiter_numbers;
409 do {
410 value_pair = value_pair.second.split(',');
411 if (!value_pair.first.empty()) {
412 uint32_t reg = StringConvert::ToUInt32(value_pair.first.str().c_str(),
413 LLDB_INVALID_REGNUM, base);
414 if (reg != LLDB_INVALID_REGNUM)
415 regnums.push_back(reg);
416 }
417 } while (!value_pair.second.empty());
418 return regnums.size();
419}
420
421void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
422 if (!force && m_register_info.GetNumRegisters() > 0)
423 return;
424
425 m_register_info.Clear();
426
Adrian Prantl05097242018-04-30 16:49:04 +0000427 // Check if qHostInfo specified a specific packet timeout for this
428 // connection. If so then lets update our setting so the user knows what the
429 // timeout is and can see it.
Pavel Labath3aa04912016-10-31 17:19:42 +0000430 const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
431 if (host_packet_timeout > std::chrono::seconds(0)) {
432 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout.count());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 }
434
435 // Register info search order:
436 // 1 - Use the target definition python file if one is specified.
437 // 2 - If the target definition doesn't have any of the info from the
438 // target.xml (registers) then proceed to read the target.xml.
439 // 3 - Fall back on the qRegisterInfo packets.
440
441 FileSpec target_definition_fspec =
442 GetGlobalPluginProperties()->GetTargetDefinitionFile();
443 if (!target_definition_fspec.Exists()) {
444 // If the filename doesn't exist, it may be a ~ not having been expanded -
445 // try to resolve it.
446 target_definition_fspec.ResolvePath();
447 }
448 if (target_definition_fspec) {
449 // See if we can get register definitions from a python file
450 if (ParsePythonTargetDefinition(target_definition_fspec)) {
451 return;
452 } else {
453 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
454 stream_sp->Printf("ERROR: target description file %s failed to parse.\n",
455 target_definition_fspec.GetPath().c_str());
456 }
457 }
458
459 const ArchSpec &target_arch = GetTarget().GetArchitecture();
460 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
461 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
462
463 // Use the process' architecture instead of the host arch, if available
464 ArchSpec arch_to_use;
465 if (remote_process_arch.IsValid())
466 arch_to_use = remote_process_arch;
467 else
468 arch_to_use = remote_host_arch;
469
470 if (!arch_to_use.IsValid())
471 arch_to_use = target_arch;
472
473 if (GetGDBServerRegisterInfo(arch_to_use))
474 return;
475
476 char packet[128];
477 uint32_t reg_offset = 0;
478 uint32_t reg_num = 0;
479 for (StringExtractorGDBRemote::ResponseType response_type =
480 StringExtractorGDBRemote::eResponse;
481 response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
482 const int packet_len =
483 ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
484 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000485 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000487 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 GDBRemoteCommunication::PacketResult::Success) {
489 response_type = response.GetResponseType();
490 if (response_type == StringExtractorGDBRemote::eResponse) {
491 llvm::StringRef name;
492 llvm::StringRef value;
493 ConstString reg_name;
494 ConstString alt_name;
495 ConstString set_name;
496 std::vector<uint32_t> value_regs;
497 std::vector<uint32_t> invalidate_regs;
498 std::vector<uint8_t> dwarf_opcode_bytes;
499 RegisterInfo reg_info = {
500 NULL, // Name
501 NULL, // Alt name
502 0, // byte size
503 reg_offset, // offset
504 eEncodingUint, // encoding
505 eFormatHex, // format
Jason Molenda21586c82015-09-09 03:36:24 +0000506 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 LLDB_INVALID_REGNUM, // eh_frame reg num
508 LLDB_INVALID_REGNUM, // DWARF reg num
509 LLDB_INVALID_REGNUM, // generic reg num
510 reg_num, // process plugin reg num
511 reg_num // native register number
512 },
513 NULL,
514 NULL,
515 NULL, // Dwarf expression opcode bytes pointer
516 0 // Dwarf expression opcode bytes length
517 };
518
519 while (response.GetNameColonValue(name, value)) {
520 if (name.equals("name")) {
521 reg_name.SetString(value);
522 } else if (name.equals("alt-name")) {
523 alt_name.SetString(value);
524 } else if (name.equals("bitsize")) {
525 value.getAsInteger(0, reg_info.byte_size);
526 reg_info.byte_size /= CHAR_BIT;
527 } else if (name.equals("offset")) {
528 if (value.getAsInteger(0, reg_offset))
529 reg_offset = UINT32_MAX;
530 } else if (name.equals("encoding")) {
531 const Encoding encoding = Args::StringToEncoding(value);
532 if (encoding != eEncodingInvalid)
533 reg_info.encoding = encoding;
534 } else if (name.equals("format")) {
535 Format format = eFormatInvalid;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000536 if (OptionArgParser::ToFormat(value.str().c_str(), format, NULL)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537 .Success())
538 reg_info.format = format;
539 else {
540 reg_info.format =
541 llvm::StringSwitch<Format>(value)
542 .Case("binary", eFormatBinary)
543 .Case("decimal", eFormatDecimal)
544 .Case("hex", eFormatHex)
545 .Case("float", eFormatFloat)
546 .Case("vector-sint8", eFormatVectorOfSInt8)
547 .Case("vector-uint8", eFormatVectorOfUInt8)
548 .Case("vector-sint16", eFormatVectorOfSInt16)
549 .Case("vector-uint16", eFormatVectorOfUInt16)
550 .Case("vector-sint32", eFormatVectorOfSInt32)
551 .Case("vector-uint32", eFormatVectorOfUInt32)
552 .Case("vector-float32", eFormatVectorOfFloat32)
Valentina Giusticda0ae42016-09-08 14:16:45 +0000553 .Case("vector-uint64", eFormatVectorOfUInt64)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 .Case("vector-uint128", eFormatVectorOfUInt128)
555 .Default(eFormatInvalid);
Jason Molenda21586c82015-09-09 03:36:24 +0000556 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557 } else if (name.equals("set")) {
558 set_name.SetString(value);
559 } else if (name.equals("gcc") || name.equals("ehframe")) {
560 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame]))
561 reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM;
562 } else if (name.equals("dwarf")) {
563 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF]))
564 reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM;
565 } else if (name.equals("generic")) {
566 reg_info.kinds[eRegisterKindGeneric] =
567 Args::StringToGenericRegister(value);
568 } else if (name.equals("container-regs")) {
569 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
570 } else if (name.equals("invalidate-regs")) {
571 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
572 } else if (name.equals("dynamic_size_dwarf_expr_bytes")) {
573 size_t dwarf_opcode_len = value.size() / 2;
574 assert(dwarf_opcode_len > 0);
575
576 dwarf_opcode_bytes.resize(dwarf_opcode_len);
577 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
578
579 StringExtractor opcode_extractor(value);
580 uint32_t ret_val =
581 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
582 assert(dwarf_opcode_len == ret_val);
Hafiz Abid Qadeer05008ca2017-01-19 15:11:01 +0000583 UNUSED_IF_ASSERT_DISABLED(ret_val);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
585 }
Jason Molenda21586c82015-09-09 03:36:24 +0000586 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000587
588 reg_info.byte_offset = reg_offset;
589 assert(reg_info.byte_size != 0);
590 reg_offset += reg_info.byte_size;
591 if (!value_regs.empty()) {
592 value_regs.push_back(LLDB_INVALID_REGNUM);
593 reg_info.value_regs = value_regs.data();
594 }
595 if (!invalidate_regs.empty()) {
596 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
597 reg_info.invalidate_regs = invalidate_regs.data();
598 }
599
600 // We have to make a temporary ABI here, and not use the GetABI because
Adrian Prantl05097242018-04-30 16:49:04 +0000601 // this code gets called in DidAttach, when the target architecture
602 // (and consequently the ABI we'll get from 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
Adrian Prantl05097242018-04-30 16:49:04 +0000623 // updated debugserver down on the devices. On the other hand, if the
624 // accumulated reg_num is positive, see if we can add composite registers to
625 // the existing primordial ones.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626 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) {
Adrian Prantl05097242018-04-30 16:49:04 +0000672 // We don't have a valid process ID, so note that we are connected and
673 // could now request to launch or attach, or get remote process listings...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 SetPrivateState(eStateConnected);
675 } else {
676 // We have a valid process
677 SetID(pid);
678 GetThreadList();
679 StringExtractorGDBRemote response;
680 if (m_gdb_comm.GetStopReply(response)) {
681 SetLastStopPacket(response);
682
683 // '?' Packets must be handled differently in non-stop mode
684 if (GetTarget().GetNonStopModeEnabled())
685 HandleStopReplySequence();
686
687 Target &target = GetTarget();
688 if (!target.GetArchitecture().IsValid()) {
689 if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
690 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
691 } else {
692 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
693 }
694 }
695
696 const StateType state = SetThreadStopInfo(response);
697 if (state != eStateInvalid) {
698 SetPrivateState(state);
699 } else
Zachary Turner31659452016-11-17 21:15:14 +0000700 error.SetErrorStringWithFormat(
701 "Process %" PRIu64 " was reported after connecting to "
702 "'%s', but state was not stopped: %s",
703 pid, remote_url.str().c_str(), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704 } else
705 error.SetErrorStringWithFormat("Process %" PRIu64
706 " was reported after connecting to '%s', "
707 "but no stop reply packet was received",
Zachary Turner31659452016-11-17 21:15:14 +0000708 pid, remote_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 }
710
711 if (log)
712 log->Printf("ProcessGDBRemote::%s pid %" PRIu64
713 ": normalizing target architecture initial triple: %s "
714 "(GetTarget().GetArchitecture().IsValid() %s, "
715 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
716 __FUNCTION__, GetID(),
717 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
718 GetTarget().GetArchitecture().IsValid() ? "true" : "false",
719 m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
720
721 if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
722 m_gdb_comm.GetHostArchitecture().IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000723 // Prefer the *process'* architecture over that of the *host*, if
724 // available.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 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) {
Adrian Prantl05097242018-04-30 16:49:04 +0000803 // the inferior will be reading stdin from the specified file or stdio is
804 // completely disabled
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805 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()) {
Pavel Labath07d6f882017-12-11 10:09:14 +0000820 PseudoTerminal pty;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 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
Pavel Labath62930e52018-01-10 11:57:31 +0000891 m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
Ewan Crawford78baa192015-05-13 09:18:18 +0000892
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893 {
894 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +0000895 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
896 std::chrono::seconds(10));
Ewan Crawford78baa192015-05-13 09:18:18 +0000897
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898 int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
899 if (arg_packet_err == 0) {
900 std::string error_str;
901 if (m_gdb_comm.GetLaunchSuccess(error_str)) {
902 SetID(m_gdb_comm.GetCurrentProcessID());
903 } else {
904 error.SetErrorString(error_str.c_str());
905 }
906 } else {
907 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
908 arg_packet_err);
909 }
910 }
911
912 if (GetID() == LLDB_INVALID_PROCESS_ID) {
913 if (log)
914 log->Printf("failed to connect to debugserver: %s",
915 error.AsCString());
916 KillDebugserverProcess();
917 return error;
918 }
919
920 StringExtractorGDBRemote response;
921 if (m_gdb_comm.GetStopReply(response)) {
Ewan Crawford78baa192015-05-13 09:18:18 +0000922 SetLastStopPacket(response);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000923 // '?' Packets must be handled differently in non-stop mode
924 if (GetTarget().GetNonStopModeEnabled())
925 HandleStopReplySequence();
926
927 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
928
929 if (process_arch.IsValid()) {
930 GetTarget().MergeArchitecture(process_arch);
931 } else {
932 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
933 if (host_arch.IsValid())
934 GetTarget().MergeArchitecture(host_arch);
935 }
936
937 SetPrivateState(SetThreadStopInfo(response));
938
939 if (!disable_stdio) {
Pavel Labath07d6f882017-12-11 10:09:14 +0000940 if (pty.GetMasterFileDescriptor() != PseudoTerminal::invalid_fd)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 SetSTDIOFileDescriptor(pty.ReleaseMasterFileDescriptor());
942 }
943 }
944 } else {
945 if (log)
946 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Ewan Crawford78baa192015-05-13 09:18:18 +0000947 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 } else {
949 // Set our user ID to an invalid process ID.
950 SetID(LLDB_INVALID_PROCESS_ID);
951 error.SetErrorStringWithFormat(
952 "failed to get object file from '%s' for arch %s",
953 exe_module->GetFileSpec().GetFilename().AsCString(),
954 exe_module->GetArchitecture().GetArchitectureName());
955 }
956 return error;
Ewan Crawford78baa192015-05-13 09:18:18 +0000957}
958
Zachary Turner97206d52017-05-12 04:51:55 +0000959Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
960 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 // Only connect if we have a valid connect URL
962 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
963
Zachary Turner31659452016-11-17 21:15:14 +0000964 if (!connect_url.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965 if (log)
966 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
Zachary Turner31659452016-11-17 21:15:14 +0000967 connect_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
969 new ConnectionFileDescriptor());
970 if (conn_ap.get()) {
971 const uint32_t max_retry_count = 50;
972 uint32_t retry_count = 0;
973 while (!m_gdb_comm.IsConnected()) {
974 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) {
975 m_gdb_comm.SetConnection(conn_ap.release());
976 break;
977 } else if (error.WasInterrupted()) {
978 // If we were interrupted, don't keep retrying.
979 break;
980 }
981
982 retry_count++;
983
984 if (retry_count >= max_retry_count)
985 break;
986
987 usleep(100000);
988 }
989 }
990 }
991
992 if (!m_gdb_comm.IsConnected()) {
993 if (error.Success())
994 error.SetErrorString("not connected to remote gdb server");
995 return error;
996 }
997
Adrian Prantl05097242018-04-30 16:49:04 +0000998 // Start the communications read thread so all incoming data can be parsed
999 // into packets and queued as they arrive.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 if (GetTarget().GetNonStopModeEnabled())
1001 m_gdb_comm.StartReadThread();
1002
Adrian Prantl05097242018-04-30 16:49:04 +00001003 // We always seem to be able to open a connection to a local port so we need
1004 // to make sure we can then send data to it. If we can't then we aren't
1005 // actually connected to anything, so try and do the handshake with the
1006 // remote GDB server and make sure that goes alright.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 if (!m_gdb_comm.HandshakeWithServer(&error)) {
1008 m_gdb_comm.Disconnect();
1009 if (error.Success())
1010 error.SetErrorString("not connected to remote gdb server");
1011 return error;
1012 }
1013
1014 // Send $QNonStop:1 packet on startup if required
1015 if (GetTarget().GetNonStopModeEnabled())
1016 GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true));
1017
1018 m_gdb_comm.GetEchoSupported();
1019 m_gdb_comm.GetThreadSuffixSupported();
1020 m_gdb_comm.GetListThreadsInStopReplySupported();
1021 m_gdb_comm.GetHostInfo();
1022 m_gdb_comm.GetVContSupported('c');
1023 m_gdb_comm.GetVAttachOrWaitSupported();
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001024 m_gdb_comm.EnableErrorStringInPacket();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025
1026 // Ask the remote server for the default thread id
1027 if (GetTarget().GetNonStopModeEnabled())
1028 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1029
1030 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1031 for (size_t idx = 0; idx < num_cmds; idx++) {
1032 StringExtractorGDBRemote response;
1033 m_gdb_comm.SendPacketAndWaitForResponse(
1034 GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1035 }
1036 return error;
1037}
1038
1039void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
1040 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1041 if (log)
1042 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1043 if (GetID() != LLDB_INVALID_PROCESS_ID) {
1044 BuildDynamicRegisterInfo(false);
1045
1046 // See if the GDB server supports the qHostInfo information
1047
Adrian Prantl05097242018-04-30 16:49:04 +00001048 // See if the GDB server supports the qProcessInfo packet, if so prefer
1049 // that over the Host information as it will be more specific to our
1050 // process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051
1052 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1053 if (remote_process_arch.IsValid()) {
1054 process_arch = remote_process_arch;
1055 if (log)
1056 log->Printf("ProcessGDBRemote::%s gdb-remote had process architecture, "
1057 "using %s %s",
1058 __FUNCTION__, process_arch.GetArchitectureName()
1059 ? process_arch.GetArchitectureName()
1060 : "<null>",
1061 process_arch.GetTriple().getTriple().c_str()
1062 ? process_arch.GetTriple().getTriple().c_str()
1063 : "<null>");
1064 } else {
1065 process_arch = m_gdb_comm.GetHostArchitecture();
1066 if (log)
1067 log->Printf("ProcessGDBRemote::%s gdb-remote did not have process "
1068 "architecture, using gdb-remote host architecture %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 }
1076
1077 if (process_arch.IsValid()) {
1078 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1079 if (target_arch.IsValid()) {
1080 if (log)
1081 log->Printf(
1082 "ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1083 __FUNCTION__, target_arch.GetArchitectureName()
1084 ? target_arch.GetArchitectureName()
1085 : "<null>",
1086 target_arch.GetTriple().getTriple().c_str()
1087 ? target_arch.GetTriple().getTriple().c_str()
1088 : "<null>");
1089
1090 // If the remote host is ARM and we have apple as the vendor, then
1091 // ARM executables and shared libraries can have mixed ARM
1092 // architectures.
1093 // You can have an armv6 executable, and if the host is armv7, then the
1094 // system will load the best possible architecture for all shared
Adrian Prantl05097242018-04-30 16:49:04 +00001095 // libraries it has, so we really need to take the remote host
1096 // architecture as our defacto architecture in this case.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097
1098 if ((process_arch.GetMachine() == llvm::Triple::arm ||
1099 process_arch.GetMachine() == llvm::Triple::thumb) &&
1100 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1101 GetTarget().SetArchitecture(process_arch);
1102 if (log)
1103 log->Printf("ProcessGDBRemote::%s remote process is ARM/Apple, "
1104 "setting target arch to %s %s",
1105 __FUNCTION__, process_arch.GetArchitectureName()
1106 ? process_arch.GetArchitectureName()
1107 : "<null>",
1108 process_arch.GetTriple().getTriple().c_str()
1109 ? process_arch.GetTriple().getTriple().c_str()
1110 : "<null>");
1111 } else {
1112 // Fill in what is missing in the triple
1113 const llvm::Triple &remote_triple = process_arch.GetTriple();
1114 llvm::Triple new_target_triple = target_arch.GetTriple();
1115 if (new_target_triple.getVendorName().size() == 0) {
1116 new_target_triple.setVendor(remote_triple.getVendor());
1117
1118 if (new_target_triple.getOSName().size() == 0) {
1119 new_target_triple.setOS(remote_triple.getOS());
1120
1121 if (new_target_triple.getEnvironmentName().size() == 0)
1122 new_target_triple.setEnvironment(
1123 remote_triple.getEnvironment());
1124 }
1125
1126 ArchSpec new_target_arch = target_arch;
1127 new_target_arch.SetTriple(new_target_triple);
1128 GetTarget().SetArchitecture(new_target_arch);
1129 }
1130 }
1131
1132 if (log)
1133 log->Printf("ProcessGDBRemote::%s final target arch after "
1134 "adjustments for remote architecture: %s %s",
1135 __FUNCTION__, target_arch.GetArchitectureName()
1136 ? target_arch.GetArchitectureName()
1137 : "<null>",
1138 target_arch.GetTriple().getTriple().c_str()
1139 ? target_arch.GetTriple().getTriple().c_str()
1140 : "<null>");
1141 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001142 // The target doesn't have a valid architecture yet, set it from the
1143 // architecture we got from the remote GDB server
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144 GetTarget().SetArchitecture(process_arch);
1145 }
1146 }
1147
Adrian Prantl05097242018-04-30 16:49:04 +00001148 // Find out which StructuredDataPlugins are supported by the debug monitor.
1149 // These plugins transmit data over async $J packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001150 auto supported_packets_array =
1151 m_gdb_comm.GetSupportedStructuredDataPlugins();
1152 if (supported_packets_array)
1153 MapSupportedStructuredDataPlugins(*supported_packets_array);
1154 }
1155}
1156
1157void ProcessGDBRemote::DidLaunch() {
1158 ArchSpec process_arch;
1159 DidLaunchOrAttach(process_arch);
1160}
1161
Zachary Turner97206d52017-05-12 04:51:55 +00001162Status ProcessGDBRemote::DoAttachToProcessWithID(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1164 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00001165 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166
1167 if (log)
1168 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1169
1170 // Clear out and clean up from any current state
1171 Clear();
1172 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1173 error = EstablishConnectionIfNeeded(attach_info);
1174 if (error.Success()) {
1175 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1176
1177 char packet[64];
1178 const int packet_len =
1179 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1180 SetID(attach_pid);
1181 m_async_broadcaster.BroadcastEvent(
1182 eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1183 } else
1184 SetExitStatus(-1, error.AsCString());
1185 }
1186
1187 return error;
1188}
1189
Zachary Turner97206d52017-05-12 04:51:55 +00001190Status ProcessGDBRemote::DoAttachToProcessWithName(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001191 const char *process_name, const ProcessAttachInfo &attach_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001192 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193 // Clear out and clean up from any current state
1194 Clear();
1195
1196 if (process_name && process_name[0]) {
1197 error = EstablishConnectionIfNeeded(attach_info);
1198 if (error.Success()) {
1199 StreamString packet;
1200
1201 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1202
1203 if (attach_info.GetWaitForLaunch()) {
1204 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1205 packet.PutCString("vAttachWait");
1206 } else {
1207 if (attach_info.GetIgnoreExisting())
1208 packet.PutCString("vAttachWait");
1209 else
1210 packet.PutCString("vAttachOrWait");
1211 }
1212 } else
1213 packet.PutCString("vAttachName");
1214 packet.PutChar(';');
1215 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1216 endian::InlHostByteOrder(),
1217 endian::InlHostByteOrder());
1218
1219 m_async_broadcaster.BroadcastEvent(
1220 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001221 new EventDataBytes(packet.GetString().data(), packet.GetSize()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001222
1223 } else
1224 SetExitStatus(-1, error.AsCString());
1225 }
1226 return error;
1227}
1228
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001229lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options,
1230 Status &error) {
1231 return m_gdb_comm.SendStartTracePacket(options, error);
1232}
1233
1234Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
1235 return m_gdb_comm.SendStopTracePacket(uid, thread_id);
1236}
1237
1238Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
1239 llvm::MutableArrayRef<uint8_t> &buffer,
1240 size_t offset) {
1241 return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset);
1242}
1243
1244Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
1245 llvm::MutableArrayRef<uint8_t> &buffer,
1246 size_t offset) {
1247 return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset);
1248}
1249
1250Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid,
1251 TraceOptions &options) {
1252 return m_gdb_comm.SendGetTraceConfigPacket(uid, options);
1253}
1254
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255void ProcessGDBRemote::DidExit() {
1256 // When we exit, disconnect from the GDB server communications
1257 m_gdb_comm.Disconnect();
1258}
1259
1260void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1261 // If you can figure out what the architecture is, fill it in here.
1262 process_arch.Clear();
1263 DidLaunchOrAttach(process_arch);
1264}
1265
Zachary Turner97206d52017-05-12 04:51:55 +00001266Status ProcessGDBRemote::WillResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001267 m_continue_c_tids.clear();
1268 m_continue_C_tids.clear();
1269 m_continue_s_tids.clear();
1270 m_continue_S_tids.clear();
1271 m_jstopinfo_sp.reset();
1272 m_jthreadsinfo_sp.reset();
Zachary Turner97206d52017-05-12 04:51:55 +00001273 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274}
1275
Zachary Turner97206d52017-05-12 04:51:55 +00001276Status ProcessGDBRemote::DoResume() {
1277 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1279 if (log)
1280 log->Printf("ProcessGDBRemote::Resume()");
1281
1282 ListenerSP listener_sp(
1283 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1284 if (listener_sp->StartListeningForEvents(
1285 &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
1286 listener_sp->StartListeningForEvents(
1287 &m_async_broadcaster,
1288 ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1289
1290 const size_t num_threads = GetThreadList().GetSize();
1291
1292 StreamString continue_packet;
1293 bool continue_packet_error = false;
1294 if (m_gdb_comm.HasAnyVContSupport()) {
1295 if (!GetTarget().GetNonStopModeEnabled() &&
1296 (m_continue_c_tids.size() == num_threads ||
1297 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1298 m_continue_s_tids.empty() && m_continue_S_tids.empty()))) {
1299 // All threads are continuing, just send a "c" packet
1300 continue_packet.PutCString("c");
1301 } else {
1302 continue_packet.PutCString("vCont");
1303
1304 if (!m_continue_c_tids.empty()) {
1305 if (m_gdb_comm.GetVContSupported('c')) {
1306 for (tid_collection::const_iterator
1307 t_pos = m_continue_c_tids.begin(),
1308 t_end = m_continue_c_tids.end();
1309 t_pos != t_end; ++t_pos)
1310 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1311 } else
1312 continue_packet_error = true;
1313 }
1314
1315 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1316 if (m_gdb_comm.GetVContSupported('C')) {
1317 for (tid_sig_collection::const_iterator
1318 s_pos = m_continue_C_tids.begin(),
1319 s_end = m_continue_C_tids.end();
1320 s_pos != s_end; ++s_pos)
1321 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
1322 s_pos->first);
1323 } else
1324 continue_packet_error = true;
1325 }
1326
1327 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1328 if (m_gdb_comm.GetVContSupported('s')) {
1329 for (tid_collection::const_iterator
1330 t_pos = m_continue_s_tids.begin(),
1331 t_end = m_continue_s_tids.end();
1332 t_pos != t_end; ++t_pos)
1333 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1334 } else
1335 continue_packet_error = true;
1336 }
1337
1338 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1339 if (m_gdb_comm.GetVContSupported('S')) {
1340 for (tid_sig_collection::const_iterator
1341 s_pos = m_continue_S_tids.begin(),
1342 s_end = m_continue_S_tids.end();
1343 s_pos != s_end; ++s_pos)
1344 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
1345 s_pos->first);
1346 } else
1347 continue_packet_error = true;
1348 }
1349
1350 if (continue_packet_error)
Zachary Turnerc1564272016-11-16 21:15:24 +00001351 continue_packet.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001352 }
1353 } else
1354 continue_packet_error = true;
1355
1356 if (continue_packet_error) {
Adrian Prantl05097242018-04-30 16:49:04 +00001357 // Either no vCont support, or we tried to use part of the vCont packet
1358 // that wasn't supported by the remote GDB server. We need to try and
1359 // make a simple packet that can do our continue
Kate Stoneb9c1b512016-09-06 20:57:50 +00001360 const size_t num_continue_c_tids = m_continue_c_tids.size();
1361 const size_t num_continue_C_tids = m_continue_C_tids.size();
1362 const size_t num_continue_s_tids = m_continue_s_tids.size();
1363 const size_t num_continue_S_tids = m_continue_S_tids.size();
1364 if (num_continue_c_tids > 0) {
1365 if (num_continue_c_tids == num_threads) {
1366 // All threads are resuming...
1367 m_gdb_comm.SetCurrentThreadForRun(-1);
1368 continue_packet.PutChar('c');
1369 continue_packet_error = false;
1370 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1371 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1372 // Only one thread is continuing
1373 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1374 continue_packet.PutChar('c');
1375 continue_packet_error = false;
1376 }
1377 }
1378
1379 if (continue_packet_error && num_continue_C_tids > 0) {
1380 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1381 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1382 num_continue_S_tids == 0) {
1383 const int continue_signo = m_continue_C_tids.front().second;
1384 // Only one thread is continuing
1385 if (num_continue_C_tids > 1) {
Adrian Prantl05097242018-04-30 16:49:04 +00001386 // More that one thread with a signal, yet we don't have vCont
1387 // support and we are being asked to resume each thread with a
1388 // signal, we need to make sure they are all the same signal, or we
1389 // can't issue the continue accurately with the current support...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001390 if (num_continue_C_tids > 1) {
1391 continue_packet_error = false;
1392 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1393 if (m_continue_C_tids[i].second != continue_signo)
1394 continue_packet_error = true;
1395 }
1396 }
1397 if (!continue_packet_error)
1398 m_gdb_comm.SetCurrentThreadForRun(-1);
1399 } else {
1400 // Set the continue thread ID
1401 continue_packet_error = false;
1402 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1403 }
1404 if (!continue_packet_error) {
1405 // Add threads continuing with the same signo...
1406 continue_packet.Printf("C%2.2x", continue_signo);
1407 }
1408 }
1409 }
1410
1411 if (continue_packet_error && num_continue_s_tids > 0) {
1412 if (num_continue_s_tids == num_threads) {
1413 // All threads are resuming...
1414 m_gdb_comm.SetCurrentThreadForRun(-1);
1415
1416 // If in Non-Stop-Mode use vCont when stepping
1417 if (GetTarget().GetNonStopModeEnabled()) {
1418 if (m_gdb_comm.GetVContSupported('s'))
1419 continue_packet.PutCString("vCont;s");
1420 else
1421 continue_packet.PutChar('s');
1422 } else
1423 continue_packet.PutChar('s');
1424
1425 continue_packet_error = false;
1426 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1427 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1428 // Only one thread is stepping
1429 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1430 continue_packet.PutChar('s');
1431 continue_packet_error = false;
1432 }
1433 }
1434
1435 if (!continue_packet_error && num_continue_S_tids > 0) {
1436 if (num_continue_S_tids == num_threads) {
1437 const int step_signo = m_continue_S_tids.front().second;
1438 // Are all threads trying to step with the same signal?
1439 continue_packet_error = false;
1440 if (num_continue_S_tids > 1) {
1441 for (size_t i = 1; i < num_threads; ++i) {
1442 if (m_continue_S_tids[i].second != step_signo)
1443 continue_packet_error = true;
1444 }
1445 }
1446 if (!continue_packet_error) {
1447 // Add threads stepping with the same signo...
1448 m_gdb_comm.SetCurrentThreadForRun(-1);
1449 continue_packet.Printf("S%2.2x", step_signo);
1450 }
1451 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1452 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1453 // Only one thread is stepping with signal
1454 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1455 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1456 continue_packet_error = false;
1457 }
1458 }
1459 }
1460
1461 if (continue_packet_error) {
1462 error.SetErrorString("can't make continue packet for this resume");
1463 } else {
1464 EventSP event_sp;
1465 if (!m_async_thread.IsJoinable()) {
1466 error.SetErrorString("Trying to resume but the async thread is dead.");
1467 if (log)
1468 log->Printf("ProcessGDBRemote::DoResume: Trying to resume but the "
1469 "async thread is dead.");
1470 return error;
1471 }
1472
1473 m_async_broadcaster.BroadcastEvent(
1474 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001475 new EventDataBytes(continue_packet.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476 continue_packet.GetSize()));
1477
Pavel Labathd35031e12016-11-30 10:41:42 +00001478 if (listener_sp->GetEvent(event_sp, std::chrono::seconds(5)) == false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001479 error.SetErrorString("Resume timed out.");
1480 if (log)
1481 log->Printf("ProcessGDBRemote::DoResume: Resume timed out.");
1482 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1483 error.SetErrorString("Broadcast continue, but the async thread was "
1484 "killed before we got an ack back.");
1485 if (log)
1486 log->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
1487 "async thread was killed before we got an ack back.");
1488 return error;
1489 }
1490 }
1491 }
1492
1493 return error;
1494}
1495
1496void ProcessGDBRemote::HandleStopReplySequence() {
1497 while (true) {
1498 // Send vStopped
1499 StringExtractorGDBRemote response;
1500 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1501
1502 // OK represents end of signal list
1503 if (response.IsOKResponse())
1504 break;
1505
1506 // If not OK or a normal packet we have a problem
1507 if (!response.IsNormalResponse())
1508 break;
1509
1510 SetLastStopPacket(response);
1511 }
1512}
1513
1514void ProcessGDBRemote::ClearThreadIDList() {
1515 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1516 m_thread_ids.clear();
1517 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00001518}
1519
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001520size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001521ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
1522 m_thread_ids.clear();
1523 m_thread_pcs.clear();
1524 size_t comma_pos;
1525 lldb::tid_t tid;
1526 while ((comma_pos = value.find(',')) != std::string::npos) {
1527 value[comma_pos] = '\0';
1528 // thread in big endian hex
1529 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001530 if (tid != LLDB_INVALID_THREAD_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001531 m_thread_ids.push_back(tid);
1532 value.erase(0, comma_pos + 1);
1533 }
1534 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1535 if (tid != LLDB_INVALID_THREAD_ID)
1536 m_thread_ids.push_back(tid);
1537 return m_thread_ids.size();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001538}
1539
Jason Molenda545304d2015-12-18 00:45:35 +00001540size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001541ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
1542 m_thread_pcs.clear();
1543 size_t comma_pos;
1544 lldb::addr_t pc;
1545 while ((comma_pos = value.find(',')) != std::string::npos) {
1546 value[comma_pos] = '\0';
1547 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1548 if (pc != LLDB_INVALID_ADDRESS)
1549 m_thread_pcs.push_back(pc);
1550 value.erase(0, comma_pos + 1);
1551 }
1552 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1553 if (pc != LLDB_INVALID_THREAD_ID)
1554 m_thread_pcs.push_back(pc);
1555 return m_thread_pcs.size();
Jason Molenda545304d2015-12-18 00:45:35 +00001556}
1557
Kate Stoneb9c1b512016-09-06 20:57:50 +00001558bool ProcessGDBRemote::UpdateThreadIDList() {
1559 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001560
Kate Stoneb9c1b512016-09-06 20:57:50 +00001561 if (m_jthreadsinfo_sp) {
1562 // If we have the JSON threads info, we can get the thread list from that
1563 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1564 if (thread_infos && thread_infos->GetSize() > 0) {
1565 m_thread_ids.clear();
1566 m_thread_pcs.clear();
1567 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1568 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1569 if (thread_dict) {
1570 // Set the thread stop info from the JSON dictionary
1571 SetThreadStopInfo(thread_dict);
1572 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1573 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1574 m_thread_ids.push_back(tid);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001575 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001576 return true; // Keep iterating through all thread_info objects
1577 });
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001578 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001579 if (!m_thread_ids.empty())
1580 return true;
1581 } else {
1582 // See if we can get the thread IDs from the current stop reply packets
1583 // that might contain a "threads" key/value pair
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001584
Kate Stoneb9c1b512016-09-06 20:57:50 +00001585 // Lock the thread stack while we access it
1586 // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1587 std::unique_lock<std::recursive_mutex> stop_stack_lock(
1588 m_last_stop_packet_mutex, std::defer_lock);
1589 if (stop_stack_lock.try_lock()) {
1590 // Get the number of stop packets on the stack
1591 int nItems = m_stop_packet_stack.size();
1592 // Iterate over them
1593 for (int i = 0; i < nItems; i++) {
1594 // Get the thread stop info
1595 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1596 const std::string &stop_info_str = stop_info.GetStringRef();
Jason Molenda545304d2015-12-18 00:45:35 +00001597
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598 m_thread_pcs.clear();
1599 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1600 if (thread_pcs_pos != std::string::npos) {
1601 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1602 const size_t end = stop_info_str.find(';', start);
1603 if (end != std::string::npos) {
1604 std::string value = stop_info_str.substr(start, end - start);
1605 UpdateThreadPCsFromStopReplyThreadsValue(value);
1606 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001607 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001608
Kate Stoneb9c1b512016-09-06 20:57:50 +00001609 const size_t threads_pos = stop_info_str.find(";threads:");
1610 if (threads_pos != std::string::npos) {
1611 const size_t start = threads_pos + strlen(";threads:");
1612 const size_t end = stop_info_str.find(';', start);
1613 if (end != std::string::npos) {
1614 std::string value = stop_info_str.substr(start, end - start);
1615 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1616 return true;
1617 }
1618 }
1619 }
1620 }
1621 }
1622
1623 bool sequence_mutex_unavailable = false;
1624 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1625 if (sequence_mutex_unavailable) {
1626 return false; // We just didn't get the list
1627 }
1628 return true;
1629}
1630
1631bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
1632 ThreadList &new_thread_list) {
1633 // locker will keep a mutex locked until it goes out of scope
1634 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
Pavel Labathe8a7b982017-02-06 19:31:09 +00001635 LLDB_LOGV(log, "pid = {0}", GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001636
1637 size_t num_thread_ids = m_thread_ids.size();
1638 // The "m_thread_ids" thread ID list should always be updated after each stop
1639 // reply packet, but in case it isn't, update it here.
1640 if (num_thread_ids == 0) {
1641 if (!UpdateThreadIDList())
1642 return false;
1643 num_thread_ids = m_thread_ids.size();
1644 }
1645
1646 ThreadList old_thread_list_copy(old_thread_list);
1647 if (num_thread_ids > 0) {
1648 for (size_t i = 0; i < num_thread_ids; ++i) {
1649 tid_t tid = m_thread_ids[i];
1650 ThreadSP thread_sp(
1651 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1652 if (!thread_sp) {
1653 thread_sp.reset(new ThreadGDBRemote(*this, tid));
Pavel Labathe8a7b982017-02-06 19:31:09 +00001654 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1655 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001656 } else {
Pavel Labathe8a7b982017-02-06 19:31:09 +00001657 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1658 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001659 }
Pavel Labathe0a5b572017-01-20 14:17:16 +00001660
1661 SetThreadPc(thread_sp, i);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1663 }
1664 }
1665
Adrian Prantl05097242018-04-30 16:49:04 +00001666 // Whatever that is left in old_thread_list_copy are not present in
1667 // new_thread_list. Remove non-existent threads from internal id table.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001668 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1669 for (size_t i = 0; i < old_num_thread_ids; i++) {
1670 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1671 if (old_thread_sp) {
1672 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1673 m_thread_id_to_index_id_map.erase(old_thread_id);
1674 }
1675 }
1676
1677 return true;
1678}
1679
Pavel Labathe0a5b572017-01-20 14:17:16 +00001680void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1681 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1682 GetByteOrder() != eByteOrderInvalid) {
1683 ThreadGDBRemote *gdb_thread =
1684 static_cast<ThreadGDBRemote *>(thread_sp.get());
1685 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1686 if (reg_ctx_sp) {
1687 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1688 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1689 if (pc_regnum != LLDB_INVALID_REGNUM) {
1690 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1691 }
1692 }
1693 }
1694}
1695
Kate Stoneb9c1b512016-09-06 20:57:50 +00001696bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1697 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1698 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1699 // packet
1700 if (thread_infos_sp) {
1701 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1702 if (thread_infos) {
1703 lldb::tid_t tid;
1704 const size_t n = thread_infos->GetSize();
1705 for (size_t i = 0; i < n; ++i) {
1706 StructuredData::Dictionary *thread_dict =
1707 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1708 if (thread_dict) {
1709 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1710 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1711 if (tid == thread->GetID())
1712 return (bool)SetThreadStopInfo(thread_dict);
1713 }
1714 }
1715 }
1716 }
1717 }
1718 return false;
1719}
1720
1721bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1722 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1723 // packet
1724 if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1725 return true;
1726
1727 // See if we got thread stop info for any threads valid stop info reasons
Adrian Prantl05097242018-04-30 16:49:04 +00001728 // threads via the "jstopinfo" packet stop reply packet key/value pair?
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729 if (m_jstopinfo_sp) {
1730 // If we have "jstopinfo" then we have stop descriptions for all threads
Adrian Prantl05097242018-04-30 16:49:04 +00001731 // that have stop reasons, and if there is no entry for a thread, then it
1732 // has no stop reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001733 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1734 if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1735 thread->SetStopInfo(StopInfoSP());
Greg Clayton9e920902012-04-10 02:25:43 +00001736 }
1737 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001738 }
1739
1740 // Fall back to using the qThreadStopInfo packet
1741 StringExtractorGDBRemote stop_packet;
1742 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1743 return SetThreadStopInfo(stop_packet) == eStateStopped;
1744 return false;
Greg Clayton9e920902012-04-10 02:25:43 +00001745}
1746
Kate Stoneb9c1b512016-09-06 20:57:50 +00001747ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1748 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1749 uint8_t signo, const std::string &thread_name, const std::string &reason,
1750 const std::string &description, uint32_t exc_type,
1751 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1752 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1753 // queue_serial are valid
1754 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1755 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1756 ThreadSP thread_sp;
1757 if (tid != LLDB_INVALID_THREAD_ID) {
1758 // Scope for "locker" below
Greg Clayton9e920902012-04-10 02:25:43 +00001759 {
Adrian Prantl05097242018-04-30 16:49:04 +00001760 // m_thread_list_real does have its own mutex, but we need to hold onto
1761 // the mutex between the call to m_thread_list_real.FindThreadByID(...)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001762 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1763 std::lock_guard<std::recursive_mutex> guard(
1764 m_thread_list_real.GetMutex());
1765 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1766
1767 if (!thread_sp) {
1768 // Create the thread if we need to
1769 thread_sp.reset(new ThreadGDBRemote(*this, tid));
1770 m_thread_list_real.AddThread(thread_sp);
1771 }
Greg Clayton9e920902012-04-10 02:25:43 +00001772 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001773
Kate Stoneb9c1b512016-09-06 20:57:50 +00001774 if (thread_sp) {
1775 ThreadGDBRemote *gdb_thread =
1776 static_cast<ThreadGDBRemote *>(thread_sp.get());
1777 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1778
Pavel Labathe0a5b572017-01-20 14:17:16 +00001779 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1780 if (iter != m_thread_ids.end()) {
1781 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1782 }
1783
Kate Stoneb9c1b512016-09-06 20:57:50 +00001784 for (const auto &pair : expedited_register_map) {
1785 StringExtractor reg_value_extractor;
1786 reg_value_extractor.GetStringRef() = pair.second;
1787 DataBufferSP buffer_sp(new DataBufferHeap(
1788 reg_value_extractor.GetStringRef().size() / 2, 0));
1789 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1790 gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
1791 }
1792
1793 thread_sp->SetName(thread_name.empty() ? NULL : thread_name.c_str());
1794
1795 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1796 // Check if the GDB server was able to provide the queue name, kind and
1797 // serial number
1798 if (queue_vars_valid)
1799 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1800 queue_serial, dispatch_queue_t,
1801 associated_with_dispatch_queue);
1802 else
1803 gdb_thread->ClearQueueInfo();
1804
1805 gdb_thread->SetAssociatedWithLibdispatchQueue(
1806 associated_with_dispatch_queue);
1807
1808 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1809 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1810
1811 // Make sure we update our thread stop reason just once
1812 if (!thread_sp->StopInfoIsUpToDate()) {
1813 thread_sp->SetStopInfo(StopInfoSP());
1814 // If there's a memory thread backed by this thread, we need to use it
Jonas Devlieghere8db3f7e2018-04-13 11:31:34 +00001815 // to calculate StopInfo.
1816 if (ThreadSP memory_thread_sp =
1817 m_thread_list.GetBackingThread(thread_sp))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001818 thread_sp = memory_thread_sp;
1819
1820 if (exc_type != 0) {
1821 const size_t exc_data_size = exc_data.size();
1822
1823 thread_sp->SetStopInfo(
1824 StopInfoMachException::CreateStopReasonWithMachException(
1825 *thread_sp, exc_type, exc_data_size,
1826 exc_data_size >= 1 ? exc_data[0] : 0,
1827 exc_data_size >= 2 ? exc_data[1] : 0,
1828 exc_data_size >= 3 ? exc_data[2] : 0));
1829 } else {
1830 bool handled = false;
1831 bool did_exec = false;
1832 if (!reason.empty()) {
1833 if (reason.compare("trace") == 0) {
1834 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1835 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1836 ->GetBreakpointSiteList()
1837 .FindByAddress(pc);
1838
Adrian Prantl05097242018-04-30 16:49:04 +00001839 // If the current pc is a breakpoint site then the StopInfo
1840 // should be set to Breakpoint Otherwise, it will be set to
1841 // Trace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001842 if (bp_site_sp &&
1843 bp_site_sp->ValidForThisThread(thread_sp.get())) {
1844 thread_sp->SetStopInfo(
1845 StopInfo::CreateStopReasonWithBreakpointSiteID(
1846 *thread_sp, bp_site_sp->GetID()));
1847 } else
1848 thread_sp->SetStopInfo(
1849 StopInfo::CreateStopReasonToTrace(*thread_sp));
1850 handled = true;
1851 } else if (reason.compare("breakpoint") == 0) {
1852 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1853 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1854 ->GetBreakpointSiteList()
1855 .FindByAddress(pc);
1856 if (bp_site_sp) {
1857 // If the breakpoint is for this thread, then we'll report the
Adrian Prantl05097242018-04-30 16:49:04 +00001858 // hit, but if it is for another thread, we can just report no
1859 // reason. We don't need to worry about stepping over the
1860 // breakpoint here, that will be taken care of when the thread
1861 // resumes and notices that there's a breakpoint under the pc.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862 handled = true;
1863 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1864 thread_sp->SetStopInfo(
1865 StopInfo::CreateStopReasonWithBreakpointSiteID(
1866 *thread_sp, bp_site_sp->GetID()));
1867 } else {
1868 StopInfoSP invalid_stop_info_sp;
1869 thread_sp->SetStopInfo(invalid_stop_info_sp);
Jason Molenda545304d2015-12-18 00:45:35 +00001870 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001871 }
1872 } else if (reason.compare("trap") == 0) {
1873 // Let the trap just use the standard signal stop reason below...
1874 } else if (reason.compare("watchpoint") == 0) {
1875 StringExtractor desc_extractor(description.c_str());
1876 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1877 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1878 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1879 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1880 if (wp_addr != LLDB_INVALID_ADDRESS) {
1881 WatchpointSP wp_sp;
1882 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1883 if ((core >= ArchSpec::kCore_mips_first &&
1884 core <= ArchSpec::kCore_mips_last) ||
1885 (core >= ArchSpec::eCore_arm_generic &&
1886 core <= ArchSpec::eCore_arm_aarch64))
1887 wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1888 wp_hit_addr);
1889 if (!wp_sp)
1890 wp_sp =
1891 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1892 if (wp_sp) {
1893 wp_sp->SetHardwareIndex(wp_index);
1894 watch_id = wp_sp->GetID();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001895 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001896 }
1897 if (watch_id == LLDB_INVALID_WATCH_ID) {
1898 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1899 GDBR_LOG_WATCHPOINTS));
1900 if (log)
1901 log->Printf("failed to find watchpoint");
1902 }
1903 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1904 *thread_sp, watch_id, wp_hit_addr));
1905 handled = true;
1906 } else if (reason.compare("exception") == 0) {
1907 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1908 *thread_sp, description.c_str()));
1909 handled = true;
1910 } else if (reason.compare("exec") == 0) {
1911 did_exec = true;
1912 thread_sp->SetStopInfo(
1913 StopInfo::CreateStopReasonWithExec(*thread_sp));
1914 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001915 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001916 } else if (!signo) {
1917 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1918 lldb::BreakpointSiteSP bp_site_sp =
1919 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1920 pc);
Greg Clayton2e309072015-07-17 23:42:28 +00001921
Kate Stoneb9c1b512016-09-06 20:57:50 +00001922 // If the current pc is a breakpoint site then the StopInfo should
Adrian Prantl05097242018-04-30 16:49:04 +00001923 // be set to Breakpoint even though the remote stub did not set it
1924 // as such. This can happen when the thread is involuntarily
1925 // interrupted (e.g. due to stops on other threads) just as it is
1926 // about to execute the breakpoint instruction.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001927 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
1928 thread_sp->SetStopInfo(
1929 StopInfo::CreateStopReasonWithBreakpointSiteID(
1930 *thread_sp, bp_site_sp->GetID()));
1931 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001932 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001933 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001934
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935 if (!handled && signo && did_exec == false) {
1936 if (signo == SIGTRAP) {
1937 // Currently we are going to assume SIGTRAP means we are either
1938 // hitting a breakpoint or hardware single stepping.
1939 handled = true;
1940 addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1941 m_breakpoint_pc_offset;
1942 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1943 ->GetBreakpointSiteList()
1944 .FindByAddress(pc);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001945
Kate Stoneb9c1b512016-09-06 20:57:50 +00001946 if (bp_site_sp) {
1947 // If the breakpoint is for this thread, then we'll report the
Adrian Prantl05097242018-04-30 16:49:04 +00001948 // hit, but if it is for another thread, we can just report no
1949 // reason. We don't need to worry about stepping over the
1950 // breakpoint here, that will be taken care of when the thread
1951 // resumes and notices that there's a breakpoint under the pc.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001952 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1953 if (m_breakpoint_pc_offset != 0)
1954 thread_sp->GetRegisterContext()->SetPC(pc);
1955 thread_sp->SetStopInfo(
1956 StopInfo::CreateStopReasonWithBreakpointSiteID(
1957 *thread_sp, bp_site_sp->GetID()));
1958 } else {
1959 StopInfoSP invalid_stop_info_sp;
1960 thread_sp->SetStopInfo(invalid_stop_info_sp);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001961 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001962 } else {
1963 // If we were stepping then assume the stop was the result of
Adrian Prantl05097242018-04-30 16:49:04 +00001964 // the trace. If we were not stepping then report the SIGTRAP.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001965 // FIXME: We are still missing the case where we single step
1966 // over a trap instruction.
1967 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1968 thread_sp->SetStopInfo(
1969 StopInfo::CreateStopReasonToTrace(*thread_sp));
Greg Clayton2e309072015-07-17 23:42:28 +00001970 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001971 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1972 *thread_sp, signo, description.c_str()));
1973 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001974 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001975 if (!handled)
1976 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1977 *thread_sp, signo, description.c_str()));
1978 }
1979
1980 if (!description.empty()) {
1981 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1982 if (stop_info_sp) {
1983 const char *stop_info_desc = stop_info_sp->GetDescription();
1984 if (!stop_info_desc || !stop_info_desc[0])
1985 stop_info_sp->SetDescription(description.c_str());
1986 } else {
1987 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1988 *thread_sp, description.c_str()));
1989 }
1990 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001991 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001992 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001993 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001994 }
1995 return thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001996}
1997
Greg Clayton2e309072015-07-17 23:42:28 +00001998lldb::ThreadSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00001999ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
2000 static ConstString g_key_tid("tid");
2001 static ConstString g_key_name("name");
2002 static ConstString g_key_reason("reason");
2003 static ConstString g_key_metype("metype");
2004 static ConstString g_key_medata("medata");
2005 static ConstString g_key_qaddr("qaddr");
2006 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2007 static ConstString g_key_associated_with_dispatch_queue(
2008 "associated_with_dispatch_queue");
2009 static ConstString g_key_queue_name("qname");
2010 static ConstString g_key_queue_kind("qkind");
2011 static ConstString g_key_queue_serial_number("qserialnum");
2012 static ConstString g_key_registers("registers");
2013 static ConstString g_key_memory("memory");
2014 static ConstString g_key_address("address");
2015 static ConstString g_key_bytes("bytes");
2016 static ConstString g_key_description("description");
2017 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002018
Kate Stoneb9c1b512016-09-06 20:57:50 +00002019 // Stop with signal and thread info
2020 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2021 uint8_t signo = 0;
2022 std::string value;
2023 std::string thread_name;
2024 std::string reason;
2025 std::string description;
2026 uint32_t exc_type = 0;
2027 std::vector<addr_t> exc_data;
2028 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2029 ExpeditedRegisterMap expedited_register_map;
2030 bool queue_vars_valid = false;
2031 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2032 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2033 std::string queue_name;
2034 QueueKind queue_kind = eQueueKindUnknown;
2035 uint64_t queue_serial_number = 0;
2036 // Iterate through all of the thread dictionary key/value pairs from the
2037 // structured data dictionary
2038
2039 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2040 &signo, &reason, &description, &exc_type, &exc_data,
2041 &thread_dispatch_qaddr, &queue_vars_valid,
2042 &associated_with_dispatch_queue, &dispatch_queue_t,
2043 &queue_name, &queue_kind, &queue_serial_number](
2044 ConstString key,
2045 StructuredData::Object *object) -> bool {
2046 if (key == g_key_tid) {
2047 // thread in big endian hex
2048 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2049 } else if (key == g_key_metype) {
2050 // exception type in big endian hex
2051 exc_type = object->GetIntegerValue(0);
2052 } else if (key == g_key_medata) {
2053 // exception data in big endian hex
2054 StructuredData::Array *array = object->GetAsArray();
2055 if (array) {
2056 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2057 exc_data.push_back(object->GetIntegerValue());
2058 return true; // Keep iterating through all array items
2059 });
2060 }
2061 } else if (key == g_key_name) {
2062 thread_name = object->GetStringValue();
2063 } else if (key == g_key_qaddr) {
2064 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2065 } else if (key == g_key_queue_name) {
2066 queue_vars_valid = true;
2067 queue_name = object->GetStringValue();
2068 } else if (key == g_key_queue_kind) {
2069 std::string queue_kind_str = object->GetStringValue();
2070 if (queue_kind_str == "serial") {
2071 queue_vars_valid = true;
2072 queue_kind = eQueueKindSerial;
2073 } else if (queue_kind_str == "concurrent") {
2074 queue_vars_valid = true;
2075 queue_kind = eQueueKindConcurrent;
2076 }
2077 } else if (key == g_key_queue_serial_number) {
2078 queue_serial_number = object->GetIntegerValue(0);
2079 if (queue_serial_number != 0)
2080 queue_vars_valid = true;
2081 } else if (key == g_key_dispatch_queue_t) {
2082 dispatch_queue_t = object->GetIntegerValue(0);
2083 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2084 queue_vars_valid = true;
2085 } else if (key == g_key_associated_with_dispatch_queue) {
2086 queue_vars_valid = true;
2087 bool associated = object->GetBooleanValue();
2088 if (associated)
2089 associated_with_dispatch_queue = eLazyBoolYes;
2090 else
2091 associated_with_dispatch_queue = eLazyBoolNo;
2092 } else if (key == g_key_reason) {
2093 reason = object->GetStringValue();
2094 } else if (key == g_key_description) {
2095 description = object->GetStringValue();
2096 } else if (key == g_key_registers) {
2097 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2098
2099 if (registers_dict) {
2100 registers_dict->ForEach(
2101 [&expedited_register_map](ConstString key,
2102 StructuredData::Object *object) -> bool {
2103 const uint32_t reg =
2104 StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
2105 if (reg != UINT32_MAX)
2106 expedited_register_map[reg] = object->GetStringValue();
2107 return true; // Keep iterating through all array items
2108 });
2109 }
2110 } else if (key == g_key_memory) {
2111 StructuredData::Array *array = object->GetAsArray();
2112 if (array) {
2113 array->ForEach([this](StructuredData::Object *object) -> bool {
2114 StructuredData::Dictionary *mem_cache_dict =
2115 object->GetAsDictionary();
2116 if (mem_cache_dict) {
2117 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2118 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2119 "address", mem_cache_addr)) {
2120 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
Zachary Turner28333212017-05-12 05:49:54 +00002121 llvm::StringRef str;
2122 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2123 StringExtractor bytes(str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002124 bytes.SetFilePos(0);
2125
2126 const size_t byte_size = bytes.GetStringRef().size() / 2;
2127 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2128 const size_t bytes_copied =
2129 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2130 if (bytes_copied == byte_size)
2131 m_memory_cache.AddL1CacheData(mem_cache_addr,
2132 data_buffer_sp);
2133 }
2134 }
2135 }
2136 }
2137 return true; // Keep iterating through all array items
2138 });
2139 }
2140
2141 } else if (key == g_key_signal)
2142 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2143 return true; // Keep iterating through all dictionary key/value pairs
2144 });
2145
2146 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2147 reason, description, exc_type, exc_data,
2148 thread_dispatch_qaddr, queue_vars_valid,
2149 associated_with_dispatch_queue, dispatch_queue_t,
2150 queue_name, queue_kind, queue_serial_number);
2151}
2152
2153StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2154 stop_packet.SetFilePos(0);
2155 const char stop_type = stop_packet.GetChar();
2156 switch (stop_type) {
2157 case 'T':
2158 case 'S': {
Adrian Prantl05097242018-04-30 16:49:04 +00002159 // This is a bit of a hack, but is is required. If we did exec, we need to
2160 // clear our thread lists and also know to rebuild our dynamic register
2161 // info before we lookup and threads and populate the expedited register
2162 // values so we need to know this right away so we can cleanup and update
2163 // our registers.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002164 const uint32_t stop_id = GetStopID();
2165 if (stop_id == 0) {
Adrian Prantl05097242018-04-30 16:49:04 +00002166 // Our first stop, make sure we have a process ID, and also make sure we
2167 // know about our registers
Kate Stoneb9c1b512016-09-06 20:57:50 +00002168 if (GetID() == LLDB_INVALID_PROCESS_ID) {
2169 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2170 if (pid != LLDB_INVALID_PROCESS_ID)
2171 SetID(pid);
2172 }
2173 BuildDynamicRegisterInfo(true);
2174 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002175 // Stop with signal and thread info
2176 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002177 const uint8_t signo = stop_packet.GetHexU8();
2178 llvm::StringRef key;
2179 llvm::StringRef value;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002180 std::string thread_name;
2181 std::string reason;
2182 std::string description;
2183 uint32_t exc_type = 0;
2184 std::vector<addr_t> exc_data;
2185 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002186 bool queue_vars_valid =
2187 false; // says if locals below that start with "queue_" are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002188 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2189 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002190 std::string queue_name;
2191 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002192 uint64_t queue_serial_number = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002193 ExpeditedRegisterMap expedited_register_map;
2194 while (stop_packet.GetNameColonValue(key, value)) {
2195 if (key.compare("metype") == 0) {
2196 // exception type in big endian hex
2197 value.getAsInteger(16, exc_type);
2198 } else if (key.compare("medata") == 0) {
2199 // exception data in big endian hex
2200 uint64_t x;
2201 value.getAsInteger(16, x);
2202 exc_data.push_back(x);
2203 } else if (key.compare("thread") == 0) {
2204 // thread in big endian hex
2205 if (value.getAsInteger(16, tid))
2206 tid = LLDB_INVALID_THREAD_ID;
2207 } else if (key.compare("threads") == 0) {
2208 std::lock_guard<std::recursive_mutex> guard(
2209 m_thread_list_real.GetMutex());
Greg Clayton358cf1e2015-06-25 21:46:34 +00002210
Kate Stoneb9c1b512016-09-06 20:57:50 +00002211 m_thread_ids.clear();
2212 // A comma separated list of all threads in the current
Adrian Prantl05097242018-04-30 16:49:04 +00002213 // process that includes the thread for this stop reply packet
Kate Stoneb9c1b512016-09-06 20:57:50 +00002214 lldb::tid_t tid;
2215 while (!value.empty()) {
2216 llvm::StringRef tid_str;
2217 std::tie(tid_str, value) = value.split(',');
2218 if (tid_str.getAsInteger(16, tid))
2219 tid = LLDB_INVALID_THREAD_ID;
2220 m_thread_ids.push_back(tid);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002221 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002222 } else if (key.compare("thread-pcs") == 0) {
2223 m_thread_pcs.clear();
2224 // A comma separated list of all threads in the current
Adrian Prantl05097242018-04-30 16:49:04 +00002225 // process that includes the thread for this stop reply packet
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226 lldb::addr_t pc;
2227 while (!value.empty()) {
2228 llvm::StringRef pc_str;
2229 std::tie(pc_str, value) = value.split(',');
2230 if (pc_str.getAsInteger(16, pc))
2231 pc = LLDB_INVALID_ADDRESS;
2232 m_thread_pcs.push_back(pc);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002233 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 } else if (key.compare("jstopinfo") == 0) {
2235 StringExtractor json_extractor(value);
2236 std::string json;
2237 // Now convert the HEX bytes into a string value
2238 json_extractor.GetHexByteString(json);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002239
Kate Stoneb9c1b512016-09-06 20:57:50 +00002240 // This JSON contains thread IDs and thread stop info for all threads.
2241 // It doesn't contain expedited registers, memory or queue info.
2242 m_jstopinfo_sp = StructuredData::ParseJSON(json);
2243 } else if (key.compare("hexname") == 0) {
2244 StringExtractor name_extractor(value);
2245 std::string name;
2246 // Now convert the HEX bytes into a string value
2247 name_extractor.GetHexByteString(thread_name);
2248 } else if (key.compare("name") == 0) {
2249 thread_name = value;
2250 } else if (key.compare("qaddr") == 0) {
2251 value.getAsInteger(16, thread_dispatch_qaddr);
2252 } else if (key.compare("dispatch_queue_t") == 0) {
2253 queue_vars_valid = true;
2254 value.getAsInteger(16, dispatch_queue_t);
2255 } else if (key.compare("qname") == 0) {
2256 queue_vars_valid = true;
2257 StringExtractor name_extractor(value);
2258 // Now convert the HEX bytes into a string value
2259 name_extractor.GetHexByteString(queue_name);
2260 } else if (key.compare("qkind") == 0) {
2261 queue_kind = llvm::StringSwitch<QueueKind>(value)
2262 .Case("serial", eQueueKindSerial)
2263 .Case("concurrent", eQueueKindConcurrent)
2264 .Default(eQueueKindUnknown);
2265 queue_vars_valid = queue_kind != eQueueKindUnknown;
2266 } else if (key.compare("qserialnum") == 0) {
2267 if (!value.getAsInteger(0, queue_serial_number))
2268 queue_vars_valid = true;
2269 } else if (key.compare("reason") == 0) {
2270 reason = value;
2271 } else if (key.compare("description") == 0) {
2272 StringExtractor desc_extractor(value);
2273 // Now convert the HEX bytes into a string value
2274 desc_extractor.GetHexByteString(description);
2275 } else if (key.compare("memory") == 0) {
2276 // Expedited memory. GDB servers can choose to send back expedited
Adrian Prantl05097242018-04-30 16:49:04 +00002277 // memory that can populate the L1 memory cache in the process so that
2278 // things like the frame pointer backchain can be expedited. This will
2279 // help stack backtracing be more efficient by not having to send as
2280 // many memory read requests down the remote GDB server.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002281
2282 // Key/value pair format: memory:<addr>=<bytes>;
2283 // <addr> is a number whose base will be interpreted by the prefix:
2284 // "0x[0-9a-fA-F]+" for hex
2285 // "0[0-7]+" for octal
2286 // "[1-9]+" for decimal
2287 // <bytes> is native endian ASCII hex bytes just like the register
2288 // values
2289 llvm::StringRef addr_str, bytes_str;
2290 std::tie(addr_str, bytes_str) = value.split('=');
2291 if (!addr_str.empty() && !bytes_str.empty()) {
2292 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2293 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2294 StringExtractor bytes(bytes_str);
2295 const size_t byte_size = bytes.GetBytesLeft() / 2;
2296 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2297 const size_t bytes_copied =
2298 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2299 if (bytes_copied == byte_size)
2300 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2301 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002302 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002303 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2304 key.compare("awatch") == 0) {
2305 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2306 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2307 value.getAsInteger(16, wp_addr);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002308
Kate Stoneb9c1b512016-09-06 20:57:50 +00002309 WatchpointSP wp_sp =
2310 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2311 uint32_t wp_index = LLDB_INVALID_INDEX32;
Eugene Zelenko0722f082015-10-24 01:28:05 +00002312
Kate Stoneb9c1b512016-09-06 20:57:50 +00002313 if (wp_sp)
2314 wp_index = wp_sp->GetHardwareIndex();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002315
Kate Stoneb9c1b512016-09-06 20:57:50 +00002316 reason = "watchpoint";
2317 StreamString ostr;
2318 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002319 description = ostr.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002320 } else if (key.compare("library") == 0) {
2321 LoadModules();
2322 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2323 uint32_t reg = UINT32_MAX;
2324 if (!key.getAsInteger(16, reg))
2325 expedited_register_map[reg] = std::move(value);
2326 }
2327 }
2328
2329 if (tid == LLDB_INVALID_THREAD_ID) {
2330 // A thread id may be invalid if the response is old style 'S' packet
2331 // which does not provide the
Adrian Prantl05097242018-04-30 16:49:04 +00002332 // thread information. So update the thread list and choose the first
2333 // one.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002334 UpdateThreadIDList();
2335
2336 if (!m_thread_ids.empty()) {
2337 tid = m_thread_ids.front();
2338 }
2339 }
2340
2341 ThreadSP thread_sp = SetThreadStopInfo(
2342 tid, expedited_register_map, signo, thread_name, reason, description,
2343 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2344 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2345 queue_kind, queue_serial_number);
2346
2347 return eStateStopped;
2348 } break;
2349
2350 case 'W':
2351 case 'X':
2352 // process exited
2353 return eStateExited;
2354
2355 default:
2356 break;
2357 }
2358 return eStateInvalid;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002359}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002360
Kate Stoneb9c1b512016-09-06 20:57:50 +00002361void ProcessGDBRemote::RefreshStateAfterStop() {
2362 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002363
Kate Stoneb9c1b512016-09-06 20:57:50 +00002364 m_thread_ids.clear();
2365 m_thread_pcs.clear();
Adrian Prantl05097242018-04-30 16:49:04 +00002366 // Set the thread stop info. It might have a "threads" key whose value is a
2367 // list of all thread IDs in the current process, so m_thread_ids might get
2368 // set.
Greg Claytona5801ad2015-07-15 22:59:03 +00002369
Kate Stoneb9c1b512016-09-06 20:57:50 +00002370 // Scope for the lock
2371 {
2372 // Lock the thread stack while we access it
2373 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2374 // Get the number of stop packets on the stack
2375 int nItems = m_stop_packet_stack.size();
2376 // Iterate over them
2377 for (int i = 0; i < nItems; i++) {
2378 // Get the thread stop info
2379 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2380 // Process thread stop info
2381 SetThreadStopInfo(stop_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002382 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002383 // Clear the thread stop stack
2384 m_stop_packet_stack.clear();
2385 }
2386
2387 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2388 if (m_thread_ids.empty()) {
2389 // No, we need to fetch the thread list manually
2390 UpdateThreadIDList();
2391 }
2392
2393 // If we have queried for a default thread id
2394 if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2395 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2396 m_initial_tid = LLDB_INVALID_THREAD_ID;
2397 }
2398
Adrian Prantl05097242018-04-30 16:49:04 +00002399 // Let all threads recover from stopping and do any clean up based on the
2400 // previous thread state (if any).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401 m_thread_list_real.RefreshStateAfterStop();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402}
2403
Zachary Turner97206d52017-05-12 04:51:55 +00002404Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2405 Status error;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002406
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00002408 // We are being asked to halt during an attach. We need to just close our
2409 // file handle and debugserver will go away, and we can be done...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 m_gdb_comm.Disconnect();
2411 } else
2412 caused_stop = m_gdb_comm.Interrupt();
2413 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002414}
2415
Zachary Turner97206d52017-05-12 04:51:55 +00002416Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2417 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2419 if (log)
2420 log->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002421
Kate Stoneb9c1b512016-09-06 20:57:50 +00002422 error = m_gdb_comm.Detach(keep_stopped);
2423 if (log) {
2424 if (error.Success())
2425 log->PutCString(
2426 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
Greg Clayton513c26c2011-01-29 07:10:55 +00002427 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002428 log->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2429 error.AsCString() ? error.AsCString() : "<unknown error>");
2430 }
2431
2432 if (!error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002434
2435 // Sleep for one second to let the process get all detached...
2436 StopAsyncThread();
2437
2438 SetPrivateState(eStateDetached);
2439 ResumePrivateStateThread();
2440
2441 // KillDebugserverProcess ();
2442 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002443}
2444
Zachary Turner97206d52017-05-12 04:51:55 +00002445Status ProcessGDBRemote::DoDestroy() {
2446 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2448 if (log)
2449 log->Printf("ProcessGDBRemote::DoDestroy()");
Ed Maste81b4c5f2016-01-04 01:43:47 +00002450
Kate Stoneb9c1b512016-09-06 20:57:50 +00002451 // There is a bug in older iOS debugservers where they don't shut down the
Adrian Prantl05097242018-04-30 16:49:04 +00002452 // process they are debugging properly. If the process is sitting at a
2453 // breakpoint or an exception, this can cause problems with restarting. So
2454 // we check to see if any of our threads are stopped at a breakpoint, and if
2455 // so we remove all the breakpoints, resume the process, and THEN destroy it
2456 // again.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002457 //
2458 // Note, we don't have a good way to test the version of debugserver, but I
Adrian Prantl05097242018-04-30 16:49:04 +00002459 // happen to know that the set of all the iOS debugservers which don't
2460 // support GetThreadSuffixSupported() and that of the debugservers with this
2461 // bug are equal. There really should be a better way to test this!
Kate Stoneb9c1b512016-09-06 20:57:50 +00002462 //
2463 // We also use m_destroy_tried_resuming to make sure we only do this once, if
Adrian Prantl05097242018-04-30 16:49:04 +00002464 // we resume and then halt and get called here to destroy again and we're
2465 // still at a breakpoint or exception, then we should just do the straight-
2466 // forward kill.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002467 //
2468 // And of course, if we weren't able to stop the process by the time we get
Adrian Prantl05097242018-04-30 16:49:04 +00002469 // here, it isn't necessary (or helpful) to do any of this.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002470
Kate Stoneb9c1b512016-09-06 20:57:50 +00002471 if (!m_gdb_comm.GetThreadSuffixSupported() &&
2472 m_public_state.GetValue() != eStateRunning) {
2473 PlatformSP platform_sp = GetTarget().GetPlatform();
Jim Inghamacff8952013-05-02 00:27:30 +00002474
Kate Stoneb9c1b512016-09-06 20:57:50 +00002475 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2476 if (platform_sp && platform_sp->GetName() &&
2477 platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2478 if (m_destroy_tried_resuming) {
Greg Clayton8cda7f02013-05-21 21:55:59 +00002479 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002480 log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2481 "destroy once already, not doing it again.");
2482 } else {
2483 // At present, the plans are discarded and the breakpoints disabled
Adrian Prantl05097242018-04-30 16:49:04 +00002484 // Process::Destroy, but we really need it to happen here and it
2485 // doesn't matter if we do it twice.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002486 m_thread_list.DiscardThreadPlans();
2487 DisableAllBreakpointSites();
Greg Clayton8cda7f02013-05-21 21:55:59 +00002488
Kate Stoneb9c1b512016-09-06 20:57:50 +00002489 bool stop_looks_like_crash = false;
2490 ThreadList &threads = GetThreadList();
2491
2492 {
2493 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2494
2495 size_t num_threads = threads.GetSize();
2496 for (size_t i = 0; i < num_threads; i++) {
2497 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2498 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2499 StopReason reason = eStopReasonInvalid;
2500 if (stop_info_sp)
2501 reason = stop_info_sp->GetStopReason();
2502 if (reason == eStopReasonBreakpoint ||
2503 reason == eStopReasonException) {
2504 if (log)
2505 log->Printf(
2506 "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2507 " stopped with reason: %s.",
2508 thread_sp->GetProtocolID(), stop_info_sp->GetDescription());
2509 stop_looks_like_crash = true;
2510 break;
2511 }
2512 }
2513 }
2514
2515 if (stop_looks_like_crash) {
2516 if (log)
2517 log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2518 "breakpoint, continue and then kill.");
2519 m_destroy_tried_resuming = true;
2520
2521 // If we are going to run again before killing, it would be good to
Adrian Prantl05097242018-04-30 16:49:04 +00002522 // suspend all the threads before resuming so they won't get into
2523 // more trouble. Sadly, for the threads stopped with the breakpoint
2524 // or exception, the exception doesn't get cleared if it is
2525 // suspended, so we do have to run the risk of letting those threads
2526 // proceed a bit.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002527
2528 {
2529 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2530
2531 size_t num_threads = threads.GetSize();
2532 for (size_t i = 0; i < num_threads; i++) {
2533 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2534 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2535 StopReason reason = eStopReasonInvalid;
2536 if (stop_info_sp)
2537 reason = stop_info_sp->GetStopReason();
2538 if (reason != eStopReasonBreakpoint &&
2539 reason != eStopReasonException) {
2540 if (log)
2541 log->Printf("ProcessGDBRemote::DoDestroy() - Suspending "
2542 "thread: 0x%4.4" PRIx64 " before running.",
2543 thread_sp->GetProtocolID());
2544 thread_sp->SetResumeState(eStateSuspended);
2545 }
2546 }
2547 }
2548 Resume();
2549 return Destroy(false);
2550 }
2551 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002552 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002553 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002554
Kate Stoneb9c1b512016-09-06 20:57:50 +00002555 // Interrupt if our inferior is running...
2556 int exit_status = SIGABRT;
2557 std::string exit_string;
Greg Clayton2e309072015-07-17 23:42:28 +00002558
Kate Stoneb9c1b512016-09-06 20:57:50 +00002559 if (m_gdb_comm.IsConnected()) {
2560 if (m_public_state.GetValue() != eStateAttaching) {
2561 StringExtractorGDBRemote response;
2562 bool send_async = true;
Pavel Labath3aa04912016-10-31 17:19:42 +00002563 GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2564 std::chrono::seconds(3));
Greg Clayton2e309072015-07-17 23:42:28 +00002565
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002566 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002567 GDBRemoteCommunication::PacketResult::Success) {
2568 char packet_cmd = response.GetChar(0);
2569
2570 if (packet_cmd == 'W' || packet_cmd == 'X') {
2571#if defined(__APPLE__)
2572 // For Native processes on Mac OS X, we launch through the Host
Adrian Prantl05097242018-04-30 16:49:04 +00002573 // Platform, then hand the process off to debugserver, which becomes
2574 // the parent process through "PT_ATTACH". Then when we go to kill
2575 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2576 // we call waitpid which returns with no error and the correct
2577 // status. But amusingly enough that doesn't seem to actually reap
Kate Stoneb9c1b512016-09-06 20:57:50 +00002578 // the process, but instead it is left around as a Zombie. Probably
Adrian Prantl05097242018-04-30 16:49:04 +00002579 // the kernel is in the process of switching ownership back to lldb
2580 // which was the original parent, and gets confused in the handoff.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002581 // Anyway, so call waitpid here to finally reap it.
2582 PlatformSP platform_sp(GetTarget().GetPlatform());
2583 if (platform_sp && platform_sp->IsHost()) {
2584 int status;
2585 ::pid_t reap_pid;
2586 reap_pid = waitpid(GetID(), &status, WNOHANG);
2587 if (log)
2588 log->Printf("Reaped pid: %d, status: %d.\n", reap_pid, status);
2589 }
2590#endif
2591 SetLastStopPacket(response);
2592 ClearThreadIDList();
2593 exit_status = response.GetHexU8();
2594 } else {
2595 if (log)
2596 log->Printf("ProcessGDBRemote::DoDestroy - got unexpected response "
2597 "to k packet: %s",
2598 response.GetStringRef().c_str());
2599 exit_string.assign("got unexpected response to k packet: ");
2600 exit_string.append(response.GetStringRef());
2601 }
2602 } else {
2603 if (log)
2604 log->Printf("ProcessGDBRemote::DoDestroy - failed to send k packet");
2605 exit_string.assign("failed to send the k packet");
2606 }
2607 } else {
2608 if (log)
2609 log->Printf("ProcessGDBRemote::DoDestroy - killed or interrupted while "
2610 "attaching");
2611 exit_string.assign("killed or interrupted while attaching.");
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002612 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002613 } else {
2614 // If we missed setting the exit status on the way out, do it here.
2615 // NB set exit status can be called multiple times, the first one sets the
2616 // status.
2617 exit_string.assign("destroying when not connected to debugserver");
2618 }
2619
2620 SetExitStatus(exit_status, exit_string.c_str());
2621
2622 StopAsyncThread();
2623 KillDebugserverProcess();
2624 return error;
Greg Clayton8cda7f02013-05-21 21:55:59 +00002625}
2626
Kate Stoneb9c1b512016-09-06 20:57:50 +00002627void ProcessGDBRemote::SetLastStopPacket(
2628 const StringExtractorGDBRemote &response) {
2629 const bool did_exec =
2630 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2631 if (did_exec) {
2632 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2633 if (log)
2634 log->Printf("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2635
2636 m_thread_list_real.Clear();
2637 m_thread_list.Clear();
2638 BuildDynamicRegisterInfo(true);
2639 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2640 }
2641
2642 // Scope the lock
2643 {
2644 // Lock the thread stack while we access it
2645 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2646
2647 // We are are not using non-stop mode, there can only be one last stop
2648 // reply packet, so clear the list.
2649 if (GetTarget().GetNonStopModeEnabled() == false)
2650 m_stop_packet_stack.clear();
2651
Adrian Prantl05097242018-04-30 16:49:04 +00002652 // Add this stop packet to the stop packet stack This stack will get popped
2653 // and examined when we switch to the Stopped state
Kate Stoneb9c1b512016-09-06 20:57:50 +00002654 m_stop_packet_stack.push_back(response);
2655 }
2656}
2657
2658void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2659 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
Chaoren Linc963a222015-09-01 16:58:45 +00002660}
2661
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002662//------------------------------------------------------------------
2663// Process Queries
2664//------------------------------------------------------------------
2665
Kate Stoneb9c1b512016-09-06 20:57:50 +00002666bool ProcessGDBRemote::IsAlive() {
2667 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002668}
2669
Kate Stoneb9c1b512016-09-06 20:57:50 +00002670addr_t ProcessGDBRemote::GetImageInfoAddress() {
2671 // request the link map address via the $qShlibInfoAddr packet
2672 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
Aidan Doddsc0c83852015-05-08 09:36:31 +00002673
Kate Stoneb9c1b512016-09-06 20:57:50 +00002674 // the loaded module list can also provides a link map address
2675 if (addr == LLDB_INVALID_ADDRESS) {
2676 LoadedModuleInfoList list;
2677 if (GetLoadedModuleList(list).Success())
2678 addr = list.m_link_map;
2679 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00002680
Kate Stoneb9c1b512016-09-06 20:57:50 +00002681 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002682}
2683
Kate Stoneb9c1b512016-09-06 20:57:50 +00002684void ProcessGDBRemote::WillPublicStop() {
Adrian Prantl05097242018-04-30 16:49:04 +00002685 // See if the GDB remote client supports the JSON threads info. If so, we
2686 // gather stop info for all threads, expedited registers, expedited memory,
2687 // runtime queue information (iOS and MacOSX only), and more. Expediting
2688 // memory will help stack backtracing be much faster. Expediting registers
2689 // will make sure we don't have to read the thread registers for GPRs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002690 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
Greg Clayton2e309072015-07-17 23:42:28 +00002691
Kate Stoneb9c1b512016-09-06 20:57:50 +00002692 if (m_jthreadsinfo_sp) {
2693 // Now set the stop info for each thread and also expedite any registers
2694 // and memory that was in the jThreadsInfo response.
2695 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2696 if (thread_infos) {
2697 const size_t n = thread_infos->GetSize();
2698 for (size_t i = 0; i < n; ++i) {
2699 StructuredData::Dictionary *thread_dict =
2700 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2701 if (thread_dict)
2702 SetThreadStopInfo(thread_dict);
2703 }
Greg Clayton2e309072015-07-17 23:42:28 +00002704 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002705 }
Greg Clayton2e309072015-07-17 23:42:28 +00002706}
2707
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002708//------------------------------------------------------------------
2709// Process Memory
2710//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002711size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002712 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002714 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2715 // M and m packets take 2 bytes for 1 byte of memory
2716 size_t max_memory_size =
2717 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2718 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002719 // Keep memory read sizes down to a sane limit. This function will be
2720 // called multiple times in order to complete the task by
2721 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002722 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724
Kate Stoneb9c1b512016-09-06 20:57:50 +00002725 char packet[64];
2726 int packet_len;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002727 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2728 binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2729 (uint64_t)size);
2730 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002731 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002732 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002733 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 GDBRemoteCommunication::PacketResult::Success) {
2735 if (response.IsNormalResponse()) {
2736 error.Clear();
2737 if (binary_memory_read) {
2738 // The lower level GDBRemoteCommunication packet receive layer has
Adrian Prantl05097242018-04-30 16:49:04 +00002739 // already de-quoted any 0x7d character escaping that was present in
2740 // the packet
Jason Molenda6076bf42014-05-06 04:34:52 +00002741
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742 size_t data_received_size = response.GetBytesLeft();
2743 if (data_received_size > size) {
2744 // Don't write past the end of BUF if the remote debug server gave us
Adrian Prantl05097242018-04-30 16:49:04 +00002745 // too much data for some reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002746 data_received_size = size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002747 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748 memcpy(buf, response.GetStringRef().data(), data_received_size);
2749 return data_received_size;
2750 } else {
2751 return response.GetHexBytes(
2752 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2753 }
2754 } else if (response.IsErrorResponse())
2755 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2756 else if (response.IsUnsupportedResponse())
2757 error.SetErrorStringWithFormat(
2758 "GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002759 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 error.SetErrorStringWithFormat(
2761 "unexpected response to GDB server memory read packet '%s': '%s'",
2762 packet, response.GetStringRef().c_str());
2763 } else {
2764 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2765 }
2766 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002767}
2768
Pavel Labath16064d32018-03-20 11:56:24 +00002769Status ProcessGDBRemote::WriteObjectFile(
2770 std::vector<ObjectFile::LoadableData> entries) {
2771 Status error;
2772 // Sort the entries by address because some writes, like those to flash
2773 // memory, must happen in order of increasing address.
2774 std::stable_sort(
2775 std::begin(entries), std::end(entries),
2776 [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2777 return a.Dest < b.Dest;
2778 });
2779 m_allow_flash_writes = true;
2780 error = Process::WriteObjectFile(entries);
2781 if (error.Success())
2782 error = FlashDone();
2783 else
Adrian Prantl05097242018-04-30 16:49:04 +00002784 // Even though some of the writing failed, try to send a flash done if some
2785 // of the writing succeeded so the flash state is reset to normal, but
2786 // don't stomp on the error status that was set in the write failure since
2787 // that's the one we want to report back.
Pavel Labath16064d32018-03-20 11:56:24 +00002788 FlashDone();
2789 m_allow_flash_writes = false;
2790 return error;
2791}
2792
2793bool ProcessGDBRemote::HasErased(FlashRange range) {
2794 auto size = m_erased_flash_ranges.GetSize();
2795 for (size_t i = 0; i < size; ++i)
2796 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2797 return true;
2798 return false;
2799}
2800
2801Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2802 Status status;
2803
2804 MemoryRegionInfo region;
2805 status = GetMemoryRegionInfo(addr, region);
2806 if (!status.Success())
2807 return status;
2808
2809 // The gdb spec doesn't say if erasures are allowed across multiple regions,
2810 // but we'll disallow it to be safe and to keep the logic simple by worring
2811 // about only one region's block size. DoMemoryWrite is this function's
2812 // primary user, and it can easily keep writes within a single memory region
2813 if (addr + size > region.GetRange().GetRangeEnd()) {
2814 status.SetErrorString("Unable to erase flash in multiple regions");
2815 return status;
2816 }
2817
2818 uint64_t blocksize = region.GetBlocksize();
2819 if (blocksize == 0) {
2820 status.SetErrorString("Unable to erase flash because blocksize is 0");
2821 return status;
2822 }
2823
2824 // Erasures can only be done on block boundary adresses, so round down addr
2825 // and round up size
2826 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2827 size += (addr - block_start_addr);
2828 if ((size % blocksize) != 0)
2829 size += (blocksize - size % blocksize);
2830
2831 FlashRange range(block_start_addr, size);
2832
2833 if (HasErased(range))
2834 return status;
2835
2836 // We haven't erased the entire range, but we may have erased part of it.
Adrian Prantl05097242018-04-30 16:49:04 +00002837 // (e.g., block A is already erased and range starts in A and ends in B). So,
2838 // adjust range if necessary to exclude already erased blocks.
Pavel Labath16064d32018-03-20 11:56:24 +00002839 if (!m_erased_flash_ranges.IsEmpty()) {
2840 // Assuming that writes and erasures are done in increasing addr order,
Adrian Prantl05097242018-04-30 16:49:04 +00002841 // because that is a requirement of the vFlashWrite command. Therefore, we
2842 // only need to look at the last range in the list for overlap.
Pavel Labath16064d32018-03-20 11:56:24 +00002843 const auto &last_range = *m_erased_flash_ranges.Back();
2844 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2845 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
Adrian Prantl05097242018-04-30 16:49:04 +00002846 // overlap will be less than range.GetByteSize() or else HasErased()
2847 // would have been true
Pavel Labath16064d32018-03-20 11:56:24 +00002848 range.SetByteSize(range.GetByteSize() - overlap);
2849 range.SetRangeBase(range.GetRangeBase() + overlap);
2850 }
2851 }
2852
2853 StreamString packet;
2854 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2855 (uint64_t)range.GetByteSize());
2856
2857 StringExtractorGDBRemote response;
2858 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2859 true) ==
2860 GDBRemoteCommunication::PacketResult::Success) {
2861 if (response.IsOKResponse()) {
2862 m_erased_flash_ranges.Insert(range, true);
2863 } else {
2864 if (response.IsErrorResponse())
2865 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2866 addr);
2867 else if (response.IsUnsupportedResponse())
2868 status.SetErrorStringWithFormat("GDB server does not support flashing");
2869 else
2870 status.SetErrorStringWithFormat(
2871 "unexpected response to GDB server flash erase packet '%s': '%s'",
2872 packet.GetData(), response.GetStringRef().c_str());
2873 }
2874 } else {
2875 status.SetErrorStringWithFormat("failed to send packet: '%s'",
2876 packet.GetData());
2877 }
2878 return status;
2879}
2880
2881Status ProcessGDBRemote::FlashDone() {
2882 Status status;
2883 // If we haven't erased any blocks, then we must not have written anything
2884 // either, so there is no need to actually send a vFlashDone command
2885 if (m_erased_flash_ranges.IsEmpty())
2886 return status;
2887 StringExtractorGDBRemote response;
2888 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, true) ==
2889 GDBRemoteCommunication::PacketResult::Success) {
2890 if (response.IsOKResponse()) {
2891 m_erased_flash_ranges.Clear();
2892 } else {
2893 if (response.IsErrorResponse())
2894 status.SetErrorStringWithFormat("flash done failed");
2895 else if (response.IsUnsupportedResponse())
2896 status.SetErrorStringWithFormat("GDB server does not support flashing");
2897 else
2898 status.SetErrorStringWithFormat(
2899 "unexpected response to GDB server flash done packet: '%s'",
2900 response.GetStringRef().c_str());
2901 }
2902 } else {
2903 status.SetErrorStringWithFormat("failed to send flash done packet");
2904 }
2905 return status;
2906}
2907
Kate Stoneb9c1b512016-09-06 20:57:50 +00002908size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
Zachary Turner97206d52017-05-12 04:51:55 +00002909 size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002910 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002911 // M and m packets take 2 bytes for 1 byte of memory
2912 size_t max_memory_size = m_max_memory_size / 2;
2913 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002914 // Keep memory read sizes down to a sane limit. This function will be
2915 // called multiple times in order to complete the task by
2916 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002917 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002918 }
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002919
Pavel Labath16064d32018-03-20 11:56:24 +00002920 StreamGDBRemote packet;
2921
2922 MemoryRegionInfo region;
2923 Status region_status = GetMemoryRegionInfo(addr, region);
2924
2925 bool is_flash =
2926 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2927
2928 if (is_flash) {
2929 if (!m_allow_flash_writes) {
2930 error.SetErrorString("Writing to flash memory is not allowed");
2931 return 0;
2932 }
2933 // Keep the write within a flash memory region
2934 if (addr + size > region.GetRange().GetRangeEnd())
2935 size = region.GetRange().GetRangeEnd() - addr;
2936 // Flash memory must be erased before it can be written
2937 error = FlashErase(addr, size);
2938 if (!error.Success())
2939 return 0;
2940 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2941 packet.PutEscapedBytes(buf, size);
2942 } else {
2943 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2944 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2945 endian::InlHostByteOrder());
2946 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002947 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002948 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2949 true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002950 GDBRemoteCommunication::PacketResult::Success) {
2951 if (response.IsOKResponse()) {
2952 error.Clear();
2953 return size;
2954 } else if (response.IsErrorResponse())
2955 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2956 addr);
2957 else if (response.IsUnsupportedResponse())
2958 error.SetErrorStringWithFormat(
2959 "GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002960 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002961 error.SetErrorStringWithFormat(
2962 "unexpected response to GDB server memory write packet '%s': '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00002963 packet.GetData(), response.GetStringRef().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 } else {
2965 error.SetErrorStringWithFormat("failed to send packet: '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00002966 packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002967 }
2968 return 0;
2969}
2970
2971lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2972 uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002973 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002974 Log *log(
2975 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
2976 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2977
2978 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2979 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2980 if (allocated_addr != LLDB_INVALID_ADDRESS ||
2981 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2982 return allocated_addr;
2983 }
2984
2985 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2986 // Call mmap() to create memory in the inferior..
2987 unsigned prot = 0;
2988 if (permissions & lldb::ePermissionsReadable)
2989 prot |= eMmapProtRead;
2990 if (permissions & lldb::ePermissionsWritable)
2991 prot |= eMmapProtWrite;
2992 if (permissions & lldb::ePermissionsExecutable)
2993 prot |= eMmapProtExec;
2994
2995 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2996 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2997 m_addr_to_mmap_size[allocated_addr] = size;
2998 else {
2999 allocated_addr = LLDB_INVALID_ADDRESS;
3000 if (log)
3001 log->Printf("ProcessGDBRemote::%s no direct stub support for memory "
3002 "allocation, and InferiorCallMmap also failed - is stub "
3003 "missing register context save/restore capability?",
3004 __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003005 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003006 }
3007
3008 if (allocated_addr == LLDB_INVALID_ADDRESS)
3009 error.SetErrorStringWithFormat(
3010 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
3011 (uint64_t)size, GetPermissionsAsCString(permissions));
3012 else
3013 error.Clear();
3014 return allocated_addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003015}
3016
Zachary Turner97206d52017-05-12 04:51:55 +00003017Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
3018 MemoryRegionInfo &region_info) {
Ed Maste81b4c5f2016-01-04 01:43:47 +00003019
Zachary Turner97206d52017-05-12 04:51:55 +00003020 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003021 return error;
3022}
3023
Zachary Turner97206d52017-05-12 04:51:55 +00003024Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003025
Zachary Turner97206d52017-05-12 04:51:55 +00003026 Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003027 return error;
3028}
3029
Zachary Turner97206d52017-05-12 04:51:55 +00003030Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
3031 Status error(m_gdb_comm.GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003032 num, after, GetTarget().GetArchitecture()));
3033 return error;
3034}
3035
Zachary Turner97206d52017-05-12 04:51:55 +00003036Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
3037 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003038 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3039
3040 switch (supported) {
3041 case eLazyBoolCalculate:
Adrian Prantl05097242018-04-30 16:49:04 +00003042 // We should never be deallocating memory without allocating memory first
3043 // so we should never get eLazyBoolCalculate
Kate Stoneb9c1b512016-09-06 20:57:50 +00003044 error.SetErrorString(
3045 "tried to deallocate memory without ever allocating memory");
3046 break;
3047
3048 case eLazyBoolYes:
3049 if (!m_gdb_comm.DeallocateMemory(addr))
3050 error.SetErrorStringWithFormat(
3051 "unable to deallocate memory at 0x%" PRIx64, addr);
3052 break;
3053
3054 case eLazyBoolNo:
3055 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2a48f522011-05-14 01:50:35 +00003056 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003057 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3058 if (pos != m_addr_to_mmap_size.end() &&
3059 InferiorCallMunmap(this, addr, pos->second))
3060 m_addr_to_mmap_size.erase(pos);
3061 else
3062 error.SetErrorStringWithFormat(
3063 "unable to deallocate memory at 0x%" PRIx64, addr);
Greg Claytoncec91ef2016-02-26 01:20:20 +00003064 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003065 break;
3066 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003067
Kate Stoneb9c1b512016-09-06 20:57:50 +00003068 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003069}
3070
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003071//------------------------------------------------------------------
3072// Process STDIO
3073//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003074size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00003075 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003076 if (m_stdio_communication.IsConnected()) {
3077 ConnectionStatus status;
3078 m_stdio_communication.Write(src, src_len, status, NULL);
3079 } else if (m_stdin_forward) {
3080 m_gdb_comm.SendStdinNotification(src, src_len);
3081 }
3082 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003083}
3084
Zachary Turner97206d52017-05-12 04:51:55 +00003085Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
3086 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003087 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003088
Kate Stoneb9c1b512016-09-06 20:57:50 +00003089 // Get logging info
3090 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3091 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003092
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 // Get the breakpoint address
3094 const addr_t addr = bp_site->GetLoadAddress();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003095
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096 // Log that a breakpoint was requested
3097 if (log)
3098 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3099 ") address = 0x%" PRIx64,
3100 site_id, (uint64_t)addr);
3101
3102 // Breakpoint already exists and is enabled
3103 if (bp_site->IsEnabled()) {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003104 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003105 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3106 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3107 site_id, (uint64_t)addr);
3108 return error;
3109 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003110
Kate Stoneb9c1b512016-09-06 20:57:50 +00003111 // Get the software breakpoint trap opcode size
3112 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3113
3114 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
Adrian Prantl05097242018-04-30 16:49:04 +00003115 // breakpoint type is supported by the remote stub. These are set to true by
3116 // default, and later set to false only after we receive an unimplemented
3117 // response when sending a breakpoint packet. This means initially that
3118 // unless we were specifically instructed to use a hardware breakpoint, LLDB
3119 // will attempt to set a software breakpoint. HardwareRequired() also queries
3120 // a boolean variable which indicates if the user specifically asked for
3121 // hardware breakpoints. If true then we will skip over software
3122 // breakpoints.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003123 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3124 (!bp_site->HardwareRequired())) {
3125 // Try to send off a software breakpoint packet ($Z0)
3126 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3127 eBreakpointSoftware, true, addr, bp_op_size);
3128 if (error_no == 0) {
3129 // The breakpoint was placed successfully
3130 bp_site->SetEnabled(true);
3131 bp_site->SetType(BreakpointSite::eExternal);
3132 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003133 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003134
Adrian Prantl05097242018-04-30 16:49:04 +00003135 // SendGDBStoppointTypePacket() will return an error if it was unable to
3136 // set this breakpoint. We need to differentiate between a error specific
3137 // to placing this breakpoint or if we have learned that this breakpoint
3138 // type is unsupported. To do this, we must test the support boolean for
3139 // this breakpoint type to see if it now indicates that this breakpoint
3140 // type is unsupported. If they are still supported then we should return
Kate Stoneb9c1b512016-09-06 20:57:50 +00003141 // with the error code. If they are now unsupported, then we would like to
Adrian Prantl05097242018-04-30 16:49:04 +00003142 // fall through and try another form of breakpoint.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003143 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3144 if (error_no != UINT8_MAX)
3145 error.SetErrorStringWithFormat(
3146 "error: %d sending the breakpoint request", errno);
3147 else
3148 error.SetErrorString("error sending the breakpoint request");
3149 return error;
3150 }
3151
3152 // We reach here when software breakpoints have been found to be
Adrian Prantl05097242018-04-30 16:49:04 +00003153 // unsupported. For future calls to set a breakpoint, we will not attempt
3154 // to set a breakpoint with a type that is known not to be supported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003155 if (log)
3156 log->Printf("Software breakpoints are unsupported");
3157
3158 // So we will fall through and try a hardware breakpoint
3159 }
3160
Adrian Prantl05097242018-04-30 16:49:04 +00003161 // The process of setting a hardware breakpoint is much the same as above.
3162 // We check the supported boolean for this breakpoint type, and if it is
3163 // thought to be supported then we will try to set this breakpoint with a
3164 // hardware breakpoint.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003165 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3166 // Try to send off a hardware breakpoint packet ($Z1)
3167 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3168 eBreakpointHardware, true, addr, bp_op_size);
3169 if (error_no == 0) {
3170 // The breakpoint was placed successfully
3171 bp_site->SetEnabled(true);
3172 bp_site->SetType(BreakpointSite::eHardware);
3173 return error;
3174 }
3175
3176 // Check if the error was something other then an unsupported breakpoint
3177 // type
3178 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3179 // Unable to set this hardware breakpoint
3180 if (error_no != UINT8_MAX)
3181 error.SetErrorStringWithFormat(
3182 "error: %d sending the hardware breakpoint request "
3183 "(hardware breakpoint resources might be exhausted or unavailable)",
3184 error_no);
3185 else
3186 error.SetErrorString("error sending the hardware breakpoint request "
3187 "(hardware breakpoint resources "
3188 "might be exhausted or unavailable)");
3189 return error;
3190 }
3191
3192 // We will reach here when the stub gives an unsupported response to a
3193 // hardware breakpoint
3194 if (log)
3195 log->Printf("Hardware breakpoints are unsupported");
3196
3197 // Finally we will falling through to a #trap style breakpoint
3198 }
3199
3200 // Don't fall through when hardware breakpoints were specifically requested
3201 if (bp_site->HardwareRequired()) {
3202 error.SetErrorString("hardware breakpoints are not supported");
3203 return error;
3204 }
3205
Adrian Prantl05097242018-04-30 16:49:04 +00003206 // As a last resort we want to place a manual breakpoint. An instruction is
3207 // placed into the process memory using memory write packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003208 return EnableSoftwareBreakpoint(bp_site);
3209}
3210
Zachary Turner97206d52017-05-12 04:51:55 +00003211Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3212 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003213 assert(bp_site != NULL);
3214 addr_t addr = bp_site->GetLoadAddress();
3215 user_id_t site_id = bp_site->GetID();
3216 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3217 if (log)
3218 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3219 ") addr = 0x%8.8" PRIx64,
3220 site_id, (uint64_t)addr);
3221
3222 if (bp_site->IsEnabled()) {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003223 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3224
Kate Stoneb9c1b512016-09-06 20:57:50 +00003225 BreakpointSite::Type bp_type = bp_site->GetType();
3226 switch (bp_type) {
3227 case BreakpointSite::eSoftware:
3228 error = DisableSoftwareBreakpoint(bp_site);
3229 break;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003230
Kate Stoneb9c1b512016-09-06 20:57:50 +00003231 case BreakpointSite::eHardware:
3232 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3233 addr, bp_op_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003234 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003235 break;
3236
3237 case BreakpointSite::eExternal: {
3238 GDBStoppointType stoppoint_type;
3239 if (bp_site->IsHardware())
3240 stoppoint_type = eBreakpointHardware;
3241 else
3242 stoppoint_type = eBreakpointSoftware;
3243
3244 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr,
3245 bp_op_size))
3246 error.SetErrorToGenericError();
3247 } break;
3248 }
3249 if (error.Success())
3250 bp_site->SetEnabled(false);
3251 } else {
3252 if (log)
3253 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3254 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3255 site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003256 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003257 }
3258
3259 if (error.Success())
3260 error.SetErrorToGenericError();
3261 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003262}
3263
Johnny Chen11309a32011-09-06 22:38:36 +00003264// Pre-requisite: wp != NULL.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003265static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3266 assert(wp);
3267 bool watch_read = wp->WatchpointRead();
3268 bool watch_write = wp->WatchpointWrite();
Johnny Chen11309a32011-09-06 22:38:36 +00003269
Kate Stoneb9c1b512016-09-06 20:57:50 +00003270 // watch_read and watch_write cannot both be false.
3271 assert(watch_read || watch_write);
3272 if (watch_read && watch_write)
3273 return eWatchpointReadWrite;
3274 else if (watch_read)
3275 return eWatchpointRead;
3276 else // Must be watch_write, then.
3277 return eWatchpointWrite;
Johnny Chen11309a32011-09-06 22:38:36 +00003278}
3279
Zachary Turner97206d52017-05-12 04:51:55 +00003280Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3281 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003282 if (wp) {
3283 user_id_t watchID = wp->GetID();
3284 addr_t addr = wp->GetLoadAddress();
3285 Log *log(
3286 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003287 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003288 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3289 watchID);
3290 if (wp->IsEnabled()) {
3291 if (log)
3292 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3293 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3294 watchID, (uint64_t)addr);
3295 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003296 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003297
3298 GDBStoppointType type = GetGDBStoppointType(wp);
3299 // Pass down an appropriate z/Z packet...
3300 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3301 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3302 wp->GetByteSize()) == 0) {
3303 wp->SetEnabled(true, notify);
3304 return error;
3305 } else
3306 error.SetErrorString("sending gdb watchpoint packet failed");
3307 } else
3308 error.SetErrorString("watchpoints not supported");
3309 } else {
3310 error.SetErrorString("Watchpoint argument was NULL.");
3311 }
3312 if (error.Success())
3313 error.SetErrorToGenericError();
3314 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003315}
Kate Stoneb9c1b512016-09-06 20:57:50 +00003316
Zachary Turner97206d52017-05-12 04:51:55 +00003317Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3318 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003319 if (wp) {
3320 user_id_t watchID = wp->GetID();
3321
3322 Log *log(
3323 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3324
3325 addr_t addr = wp->GetLoadAddress();
3326
3327 if (log)
3328 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3329 ") addr = 0x%8.8" PRIx64,
3330 watchID, (uint64_t)addr);
3331
3332 if (!wp->IsEnabled()) {
3333 if (log)
3334 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3335 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3336 watchID, (uint64_t)addr);
Adrian Prantl05097242018-04-30 16:49:04 +00003337 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3338 // attempt might come from the user-supplied actions, we'll route it in
3339 // order for the watchpoint object to intelligently process this action.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003340 wp->SetEnabled(false, notify);
3341 return error;
3342 }
3343
3344 if (wp->IsHardware()) {
3345 GDBStoppointType type = GetGDBStoppointType(wp);
3346 // Pass down an appropriate z/Z packet...
3347 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3348 wp->GetByteSize()) == 0) {
3349 wp->SetEnabled(false, notify);
3350 return error;
3351 } else
3352 error.SetErrorString("sending gdb watchpoint packet failed");
3353 }
3354 // TODO: clear software watchpoints if we implement them
3355 } else {
3356 error.SetErrorString("Watchpoint argument was NULL.");
3357 }
3358 if (error.Success())
3359 error.SetErrorToGenericError();
3360 return error;
3361}
3362
3363void ProcessGDBRemote::Clear() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003364 m_thread_list_real.Clear();
3365 m_thread_list.Clear();
3366}
3367
Zachary Turner97206d52017-05-12 04:51:55 +00003368Status ProcessGDBRemote::DoSignal(int signo) {
3369 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003370 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3371 if (log)
3372 log->Printf("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3373
3374 if (!m_gdb_comm.SendAsyncSignal(signo))
3375 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3376 return error;
3377}
3378
Zachary Turner97206d52017-05-12 04:51:55 +00003379Status
3380ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003381 // Make sure we aren't already connected?
3382 if (m_gdb_comm.IsConnected())
Zachary Turner97206d52017-05-12 04:51:55 +00003383 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003384
3385 PlatformSP platform_sp(GetTarget().GetPlatform());
3386 if (platform_sp && !platform_sp->IsHost())
Zachary Turner97206d52017-05-12 04:51:55 +00003387 return Status("Lost debug server connection");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003388
3389 auto error = LaunchAndConnectToDebugserver(process_info);
3390 if (error.Fail()) {
3391 const char *error_string = error.AsCString();
3392 if (error_string == nullptr)
3393 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3394 }
3395 return error;
3396}
Eugene Zemtsov30153412017-09-25 17:41:16 +00003397#if !defined(_WIN32)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003398#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3399#endif
3400
3401#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Kate Stoneb9c1b512016-09-06 20:57:50 +00003402static bool SetCloexecFlag(int fd) {
3403#if defined(FD_CLOEXEC)
3404 int flags = ::fcntl(fd, F_GETFD);
3405 if (flags == -1)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003406 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003407 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3408#else
3409 return false;
Greg Claytonc6c420f2016-08-12 16:46:18 +00003410#endif
3411}
3412#endif
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003413
Zachary Turner97206d52017-05-12 04:51:55 +00003414Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003415 const ProcessInfo &process_info) {
3416 using namespace std::placeholders; // For _1, _2, etc.
Pavel Labath998bdc52016-05-11 16:59:04 +00003417
Zachary Turner97206d52017-05-12 04:51:55 +00003418 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003419 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3420 // If we locate debugserver, keep that located version around
3421 static FileSpec g_debugserver_file_spec;
3422
3423 ProcessLaunchInfo debugserver_launch_info;
Adrian Prantl05097242018-04-30 16:49:04 +00003424 // Make debugserver run in its own session so signals generated by special
3425 // terminal key sequences (^C) don't affect debugserver.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003426 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3427
3428 const std::weak_ptr<ProcessGDBRemote> this_wp =
3429 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3430 debugserver_launch_info.SetMonitorProcessCallback(
3431 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3432 debugserver_launch_info.SetUserID(process_info.GetUserID());
3433
3434 int communication_fd = -1;
3435#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Eugene Zemtsov30153412017-09-25 17:41:16 +00003436 // Use a socketpair on non-Windows systems for security and performance
3437 // reasons.
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003438 int sockets[2]; /* the pair of socket descriptors */
3439 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3440 error.SetErrorToErrno();
3441 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003442 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003443
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003444 int our_socket = sockets[0];
3445 int gdb_socket = sockets[1];
3446 CleanUp cleanup_our(close, our_socket);
3447 CleanUp cleanup_gdb(close, gdb_socket);
3448
Kate Stoneb9c1b512016-09-06 20:57:50 +00003449 // Don't let any child processes inherit our communication socket
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003450 SetCloexecFlag(our_socket);
3451 communication_fd = gdb_socket;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003452#endif
3453
3454 error = m_gdb_comm.StartDebugserverProcess(
3455 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3456 nullptr, nullptr, communication_fd);
3457
3458 if (error.Success())
3459 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3460 else
3461 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3462
3463 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3464#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Adrian Prantl05097242018-04-30 16:49:04 +00003465 // Our process spawned correctly, we can now set our connection to use
3466 // our end of the socket pair
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003467 cleanup_our.disable();
3468 m_gdb_comm.SetConnection(new ConnectionFileDescriptor(our_socket, true));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003469#endif
3470 StartAsyncThread();
3471 }
3472
3473 if (error.Fail()) {
3474 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3475
3476 if (log)
3477 log->Printf("failed to start debugserver process: %s",
3478 error.AsCString());
3479 return error;
3480 }
3481
3482 if (m_gdb_comm.IsConnected()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003483 // Finish the connection process by doing the handshake without
3484 // connecting (send NULL URL)
Zachary Turner31659452016-11-17 21:15:14 +00003485 ConnectToDebugserver("");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003486 } else {
3487 error.SetErrorString("connection failed");
3488 }
3489 }
3490 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003491}
3492
Kate Stoneb9c1b512016-09-06 20:57:50 +00003493bool ProcessGDBRemote::MonitorDebugserverProcess(
3494 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3495 bool exited, // True if the process did exit
3496 int signo, // Zero for no signal
3497 int exit_status // Exit value of process if signal is zero
3498 ) {
Adrian Prantl05097242018-04-30 16:49:04 +00003499 // "debugserver_pid" argument passed in is the process ID for debugserver
3500 // that we are tracking...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003501 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3502 const bool handled = true;
Greg Claytone4e45922011-11-16 05:37:56 +00003503
Kate Stoneb9c1b512016-09-06 20:57:50 +00003504 if (log)
3505 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3506 ", signo=%i (0x%x), exit_status=%i)",
3507 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00003508
Kate Stoneb9c1b512016-09-06 20:57:50 +00003509 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3510 if (log)
3511 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3512 static_cast<void *>(process_sp.get()));
3513 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
Pavel Labath194357c2016-05-12 11:10:01 +00003514 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003515
Adrian Prantl05097242018-04-30 16:49:04 +00003516 // Sleep for a half a second to make sure our inferior process has time to
3517 // set its exit status before we set it incorrectly when both the debugserver
3518 // and the inferior process shut down.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003519 usleep(500000);
Adrian Prantl05097242018-04-30 16:49:04 +00003520 // If our process hasn't yet exited, debugserver might have died. If the
3521 // process did exit, then we are reaping it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003522 const StateType state = process_sp->GetState();
3523
3524 if (state != eStateInvalid && state != eStateUnloaded &&
3525 state != eStateExited && state != eStateDetached) {
3526 char error_str[1024];
3527 if (signo) {
3528 const char *signal_cstr =
3529 process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3530 if (signal_cstr)
3531 ::snprintf(error_str, sizeof(error_str),
3532 DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3533 else
3534 ::snprintf(error_str, sizeof(error_str),
3535 DEBUGSERVER_BASENAME " died with signal %i", signo);
3536 } else {
3537 ::snprintf(error_str, sizeof(error_str),
3538 DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3539 exit_status);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003540 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003541
3542 process_sp->SetExitStatus(-1, error_str);
3543 }
Adrian Prantl05097242018-04-30 16:49:04 +00003544 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3545 // longer has a debugserver instance
Kate Stoneb9c1b512016-09-06 20:57:50 +00003546 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3547 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003548}
3549
Kate Stoneb9c1b512016-09-06 20:57:50 +00003550void ProcessGDBRemote::KillDebugserverProcess() {
3551 m_gdb_comm.Disconnect();
3552 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3553 Host::Kill(m_debugserver_pid, SIGINT);
3554 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3555 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003556}
3557
Kate Stoneb9c1b512016-09-06 20:57:50 +00003558void ProcessGDBRemote::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003559 static llvm::once_flag g_once_flag;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003560
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003561 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003562 PluginManager::RegisterPlugin(GetPluginNameStatic(),
3563 GetPluginDescriptionStatic(), CreateInstance,
3564 DebuggerInitialize);
3565 });
Greg Clayton7f982402013-07-15 22:54:20 +00003566}
3567
Kate Stoneb9c1b512016-09-06 20:57:50 +00003568void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3569 if (!PluginManager::GetSettingForProcessPlugin(
3570 debugger, PluginProperties::GetSettingName())) {
3571 const bool is_global_setting = true;
3572 PluginManager::CreateSettingForProcessPlugin(
3573 debugger, GetGlobalPluginProperties()->GetValueProperties(),
3574 ConstString("Properties for the gdb-remote process plug-in."),
3575 is_global_setting);
3576 }
3577}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003578
Kate Stoneb9c1b512016-09-06 20:57:50 +00003579bool ProcessGDBRemote::StartAsyncThread() {
3580 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3581
3582 if (log)
3583 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3584
3585 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3586 if (!m_async_thread.IsJoinable()) {
3587 // Create a thread that watches our internal state and controls which
3588 // events make it to clients (into the DCProcess event queue).
3589
3590 m_async_thread =
3591 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>",
3592 ProcessGDBRemote::AsyncThread, this, NULL);
3593 } else if (log)
3594 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
3595 "already running.",
3596 __FUNCTION__);
3597
3598 return m_async_thread.IsJoinable();
3599}
3600
3601void ProcessGDBRemote::StopAsyncThread() {
3602 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3603
3604 if (log)
3605 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3606
3607 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3608 if (m_async_thread.IsJoinable()) {
3609 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3610
3611 // This will shut down the async thread.
3612 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3613
3614 // Stop the stdio thread
3615 m_async_thread.Join(nullptr);
3616 m_async_thread.Reset();
3617 } else if (log)
3618 log->Printf(
3619 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3620 __FUNCTION__);
3621}
3622
3623bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3624 // get the packet at a string
3625 const std::string &pkt = packet.GetStringRef();
3626 // skip %stop:
3627 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3628
3629 // pass as a thread stop info packet
3630 SetLastStopPacket(stop_info);
3631
3632 // check for more stop reasons
3633 HandleStopReplySequence();
3634
Adrian Prantl05097242018-04-30 16:49:04 +00003635 // if the process is stopped then we need to fake a resume so that we can
3636 // stop properly with the new break. This is possible due to
3637 // SetPrivateState() broadcasting the state change as a side effect.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003638 if (GetPrivateState() == lldb::StateType::eStateStopped) {
3639 SetPrivateState(lldb::StateType::eStateRunning);
3640 }
3641
3642 // since we have some stopped packets we can halt the process
3643 SetPrivateState(lldb::StateType::eStateStopped);
3644
3645 return true;
3646}
3647
3648thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3649 ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3650
3651 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3652 if (log)
3653 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3654 ") thread starting...",
3655 __FUNCTION__, arg, process->GetID());
3656
3657 EventSP event_sp;
3658 bool done = false;
3659 while (!done) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003660 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003661 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3662 ") listener.WaitForEvent (NULL, event_sp)...",
3663 __FUNCTION__, arg, process->GetID());
Pavel Labathd35031e12016-11-30 10:41:42 +00003664 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003665 const uint32_t event_type = event_sp->GetType();
3666 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
Pavel Labath50556852015-09-03 09:36:22 +00003667 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003668 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3669 ") Got an event of type: %d...",
3670 __FUNCTION__, arg, process->GetID(), event_type);
Pavel Labath50556852015-09-03 09:36:22 +00003671
Kate Stoneb9c1b512016-09-06 20:57:50 +00003672 switch (event_type) {
3673 case eBroadcastBitAsyncContinue: {
3674 const EventDataBytes *continue_packet =
3675 EventDataBytes::GetEventDataFromEvent(event_sp.get());
Pavel Labath50556852015-09-03 09:36:22 +00003676
Kate Stoneb9c1b512016-09-06 20:57:50 +00003677 if (continue_packet) {
3678 const char *continue_cstr =
3679 (const char *)continue_packet->GetBytes();
3680 const size_t continue_cstr_len = continue_packet->GetByteSize();
Pavel Labath50556852015-09-03 09:36:22 +00003681 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003682 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3683 ") got eBroadcastBitAsyncContinue: %s",
3684 __FUNCTION__, arg, process->GetID(), continue_cstr);
3685
3686 if (::strstr(continue_cstr, "vAttach") == NULL)
3687 process->SetPrivateState(eStateRunning);
3688 StringExtractorGDBRemote response;
3689
3690 // If in Non-Stop-Mode
3691 if (process->GetTarget().GetNonStopModeEnabled()) {
3692 // send the vCont packet
3693 if (!process->GetGDBRemote().SendvContPacket(
3694 llvm::StringRef(continue_cstr, continue_cstr_len),
3695 response)) {
3696 // Something went wrong
3697 done = true;
3698 break;
3699 }
3700 }
3701 // If in All-Stop-Mode
3702 else {
3703 StateType stop_state =
3704 process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3705 *process, *process->GetUnixSignals(),
3706 llvm::StringRef(continue_cstr, continue_cstr_len),
3707 response);
3708
3709 // We need to immediately clear the thread ID list so we are sure
Adrian Prantl05097242018-04-30 16:49:04 +00003710 // to get a valid list of threads. The thread ID list might be
3711 // contained within the "response", or the stop reply packet that
Kate Stoneb9c1b512016-09-06 20:57:50 +00003712 // caused the stop. So clear it now before we give the stop reply
Adrian Prantl05097242018-04-30 16:49:04 +00003713 // packet to the process using the
3714 // process->SetLastStopPacket()...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003715 process->ClearThreadIDList();
3716
3717 switch (stop_state) {
3718 case eStateStopped:
3719 case eStateCrashed:
3720 case eStateSuspended:
3721 process->SetLastStopPacket(response);
3722 process->SetPrivateState(stop_state);
3723 break;
3724
3725 case eStateExited: {
3726 process->SetLastStopPacket(response);
3727 process->ClearThreadIDList();
3728 response.SetFilePos(1);
3729
3730 int exit_status = response.GetHexU8();
3731 std::string desc_string;
3732 if (response.GetBytesLeft() > 0 &&
3733 response.GetChar('-') == ';') {
3734 llvm::StringRef desc_str;
3735 llvm::StringRef desc_token;
3736 while (response.GetNameColonValue(desc_token, desc_str)) {
3737 if (desc_token != "description")
3738 continue;
3739 StringExtractor extractor(desc_str);
3740 extractor.GetHexByteString(desc_string);
3741 }
3742 }
3743 process->SetExitStatus(exit_status, desc_string.c_str());
3744 done = true;
3745 break;
3746 }
3747 case eStateInvalid: {
3748 // Check to see if we were trying to attach and if we got back
3749 // the "E87" error code from debugserver -- this indicates that
3750 // the process is not debuggable. Return a slightly more
Adrian Prantl05097242018-04-30 16:49:04 +00003751 // helpful error message about why the attach failed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003752 if (::strstr(continue_cstr, "vAttach") != NULL &&
3753 response.GetError() == 0x87) {
3754 process->SetExitStatus(-1, "cannot attach to process due to "
3755 "System Integrity Protection");
Pavel Labathacebc432018-04-18 11:56:21 +00003756 } else if (::strstr(continue_cstr, "vAttach") != NULL &&
3757 response.GetStatus().Fail()) {
3758 process->SetExitStatus(-1, response.GetStatus().AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003759 } else {
3760 process->SetExitStatus(-1, "lost connection");
3761 }
3762 break;
3763 }
3764
3765 default:
3766 process->SetPrivateState(stop_state);
3767 break;
3768 } // switch(stop_state)
3769 } // else // if in All-stop-mode
3770 } // if (continue_packet)
3771 } // case eBroadcastBitAysncContinue
3772 break;
3773
3774 case eBroadcastBitAsyncThreadShouldExit:
3775 if (log)
3776 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3777 ") got eBroadcastBitAsyncThreadShouldExit...",
3778 __FUNCTION__, arg, process->GetID());
3779 done = true;
3780 break;
3781
3782 default:
3783 if (log)
3784 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3785 ") got unknown event 0x%8.8x",
3786 __FUNCTION__, arg, process->GetID(), event_type);
3787 done = true;
3788 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003789 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003790 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3791 switch (event_type) {
3792 case Communication::eBroadcastBitReadThreadDidExit:
3793 process->SetExitStatus(-1, "lost connection");
3794 done = true;
3795 break;
3796
3797 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3798 lldb_private::Event *event = event_sp.get();
3799 const EventDataBytes *continue_packet =
3800 EventDataBytes::GetEventDataFromEvent(event);
3801 StringExtractorGDBRemote notify(
3802 (const char *)continue_packet->GetBytes());
3803 // Hand this over to the process to handle
3804 process->HandleNotifyPacket(notify);
3805 break;
3806 }
3807
3808 default:
3809 if (log)
3810 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3811 ") got unknown event 0x%8.8x",
3812 __FUNCTION__, arg, process->GetID(), event_type);
3813 done = true;
3814 break;
3815 }
3816 }
3817 } else {
3818 if (log)
3819 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3820 ") listener.WaitForEvent (NULL, event_sp) => false",
3821 __FUNCTION__, arg, process->GetID());
3822 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003823 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003824 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003825
Kate Stoneb9c1b512016-09-06 20:57:50 +00003826 if (log)
3827 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3828 ") thread exiting...",
3829 __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003830
Kate Stoneb9c1b512016-09-06 20:57:50 +00003831 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003832}
3833
Kate Stoneb9c1b512016-09-06 20:57:50 +00003834// uint32_t
3835// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3836// &matches, std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00003837//{
Kate Stoneb9c1b512016-09-06 20:57:50 +00003838// // If we are planning to launch the debugserver remotely, then we need to
3839// fire up a debugserver
3840// // process and ask it for the list of processes. But if we are local, we
3841// can let the Host do it.
Greg Claytone996fd32011-03-08 22:40:15 +00003842// if (m_local_debugserver)
3843// {
3844// return Host::ListProcessesMatchingName (name, matches, pids);
3845// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003846// else
Greg Claytone996fd32011-03-08 22:40:15 +00003847// {
3848// // FIXME: Implement talking to the remote debugserver.
3849// return 0;
3850// }
3851//
3852//}
3853//
Kate Stoneb9c1b512016-09-06 20:57:50 +00003854bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3855 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3856 lldb::user_id_t break_loc_id) {
3857 // I don't think I have to do anything here, just make sure I notice the new
3858 // thread when it starts to
3859 // run so I can stop it if that's what I want to do.
3860 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3861 if (log)
3862 log->Printf("Hit New Thread Notification breakpoint.");
3863 return false;
Jim Ingham1c823b42011-01-22 01:33:44 +00003864}
3865
Zachary Turner97206d52017-05-12 04:51:55 +00003866Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003867 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3868 LLDB_LOG(log, "Check if need to update ignored signals");
3869
Adrian Prantl05097242018-04-30 16:49:04 +00003870 // QPassSignals package is not supported by the server, there is no way we
3871 // can ignore any signals on server side.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003872 if (!m_gdb_comm.GetQPassSignalsSupported())
Zachary Turner97206d52017-05-12 04:51:55 +00003873 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003874
3875 // No signals, nothing to send.
3876 if (m_unix_signals_sp == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00003877 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003878
3879 // Signals' version hasn't changed, no need to send anything.
3880 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3881 if (new_signals_version == m_last_signals_version) {
3882 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3883 m_last_signals_version);
Zachary Turner97206d52017-05-12 04:51:55 +00003884 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003885 }
3886
3887 auto signals_to_ignore =
3888 m_unix_signals_sp->GetFilteredSignals(false, false, false);
Zachary Turner97206d52017-05-12 04:51:55 +00003889 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003890
3891 LLDB_LOG(log,
3892 "Signals' version changed. old version={0}, new version={1}, "
3893 "signals ignored={2}, update result={3}",
3894 m_last_signals_version, new_signals_version,
3895 signals_to_ignore.size(), error);
3896
3897 if (error.Success())
3898 m_last_signals_version = new_signals_version;
3899
3900 return error;
3901}
3902
Kate Stoneb9c1b512016-09-06 20:57:50 +00003903bool ProcessGDBRemote::StartNoticingNewThreads() {
3904 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3905 if (m_thread_create_bp_sp) {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003906 if (log && log->GetVerbose())
Kate Stoneb9c1b512016-09-06 20:57:50 +00003907 log->Printf("Enabled noticing new thread breakpoint.");
3908 m_thread_create_bp_sp->SetEnabled(true);
3909 } else {
3910 PlatformSP platform_sp(GetTarget().GetPlatform());
3911 if (platform_sp) {
3912 m_thread_create_bp_sp =
3913 platform_sp->SetThreadCreationBreakpoint(GetTarget());
3914 if (m_thread_create_bp_sp) {
3915 if (log && log->GetVerbose())
3916 log->Printf(
3917 "Successfully created new thread notification breakpoint %i",
3918 m_thread_create_bp_sp->GetID());
3919 m_thread_create_bp_sp->SetCallback(
3920 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3921 } else {
3922 if (log)
3923 log->Printf("Failed to create new thread notification breakpoint.");
3924 }
Jason Molendaa3329782014-03-29 18:54:20 +00003925 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003926 }
3927 return m_thread_create_bp_sp.get() != NULL;
Jason Molendaa3329782014-03-29 18:54:20 +00003928}
3929
Kate Stoneb9c1b512016-09-06 20:57:50 +00003930bool ProcessGDBRemote::StopNoticingNewThreads() {
3931 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3932 if (log && log->GetVerbose())
3933 log->Printf("Disabling new thread notification breakpoint.");
3934
3935 if (m_thread_create_bp_sp)
3936 m_thread_create_bp_sp->SetEnabled(false);
3937
3938 return true;
3939}
3940
3941DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3942 if (m_dyld_ap.get() == NULL)
3943 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, NULL));
3944 return m_dyld_ap.get();
3945}
3946
Zachary Turner97206d52017-05-12 04:51:55 +00003947Status ProcessGDBRemote::SendEventData(const char *data) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003948 int return_value;
3949 bool was_supported;
3950
Zachary Turner97206d52017-05-12 04:51:55 +00003951 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003952
3953 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3954 if (return_value != 0) {
3955 if (!was_supported)
3956 error.SetErrorString("Sending events is not supported for this process.");
3957 else
3958 error.SetErrorStringWithFormat("Error sending event data: %d.",
3959 return_value);
3960 }
3961 return error;
3962}
3963
3964const DataBufferSP ProcessGDBRemote::GetAuxvData() {
3965 DataBufferSP buf;
3966 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3967 std::string response_string;
3968 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
3969 response_string) ==
3970 GDBRemoteCommunication::PacketResult::Success)
3971 buf.reset(new DataBufferHeap(response_string.c_str(),
3972 response_string.length()));
3973 }
3974 return buf;
Steve Pucci03904ac2014-03-04 23:18:46 +00003975}
3976
Jason Molenda705b1802014-06-13 02:37:02 +00003977StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00003978ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3979 StructuredData::ObjectSP object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00003980
Kate Stoneb9c1b512016-09-06 20:57:50 +00003981 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003982 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003983 SystemRuntime *runtime = GetSystemRuntime();
3984 if (runtime) {
3985 runtime->AddThreadExtendedInfoPacketHints(args_dict);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003986 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003987 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003988
Kate Stoneb9c1b512016-09-06 20:57:50 +00003989 StreamString packet;
3990 packet << "jThreadExtendedInfo:";
3991 args_dict->Dump(packet, false);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003992
Kate Stoneb9c1b512016-09-06 20:57:50 +00003993 // FIXME the final character of a JSON dictionary, '}', is the escape
3994 // character in gdb-remote binary mode. lldb currently doesn't escape
Adrian Prantl05097242018-04-30 16:49:04 +00003995 // these characters in its packet output -- so we add the quoted version of
3996 // the } character here manually in case we talk to a debugserver which un-
3997 // escapes the characters at packet read time.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003998 packet << (char)(0x7d ^ 0x20);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003999
Kate Stoneb9c1b512016-09-06 20:57:50 +00004000 StringExtractorGDBRemote response;
4001 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004002 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4003 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004004 GDBRemoteCommunication::PacketResult::Success) {
4005 StringExtractorGDBRemote::ResponseType response_type =
4006 response.GetResponseType();
4007 if (response_type == StringExtractorGDBRemote::eResponse) {
4008 if (!response.Empty()) {
4009 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda705b1802014-06-13 02:37:02 +00004010 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004011 }
Jason Molenda705b1802014-06-13 02:37:02 +00004012 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004013 }
4014 return object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00004015}
4016
Kate Stoneb9c1b512016-09-06 20:57:50 +00004017StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4018 lldb::addr_t image_list_address, lldb::addr_t image_count) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004019
Kate Stoneb9c1b512016-09-06 20:57:50 +00004020 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4021 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4022 image_list_address);
4023 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004024
Kate Stoneb9c1b512016-09-06 20:57:50 +00004025 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4026}
4027
4028StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
4029 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4030
4031 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4032
4033 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4034}
4035
4036StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4037 const std::vector<lldb::addr_t> &load_addresses) {
4038 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4039 StructuredData::ArraySP addresses(new StructuredData::Array);
4040
4041 for (auto addr : load_addresses) {
4042 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
4043 addresses->AddItem(addr_sp);
4044 }
4045
4046 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4047
4048 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4049}
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004050
Jason Molenda37397352016-07-22 00:17:55 +00004051StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004052ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
4053 StructuredData::ObjectSP args_dict) {
4054 StructuredData::ObjectSP object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00004055
Kate Stoneb9c1b512016-09-06 20:57:50 +00004056 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4057 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +00004058 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
4059 std::chrono::seconds(10));
Jason Molenda37397352016-07-22 00:17:55 +00004060
Kate Stoneb9c1b512016-09-06 20:57:50 +00004061 StreamString packet;
4062 packet << "jGetLoadedDynamicLibrariesInfos:";
4063 args_dict->Dump(packet, false);
Jason Molenda37397352016-07-22 00:17:55 +00004064
Kate Stoneb9c1b512016-09-06 20:57:50 +00004065 // FIXME the final character of a JSON dictionary, '}', is the escape
4066 // character in gdb-remote binary mode. lldb currently doesn't escape
Adrian Prantl05097242018-04-30 16:49:04 +00004067 // these characters in its packet output -- so we add the quoted version of
4068 // the } character here manually in case we talk to a debugserver which un-
4069 // escapes the characters at packet read time.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004070 packet << (char)(0x7d ^ 0x20);
4071
4072 StringExtractorGDBRemote response;
4073 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004074 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4075 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004076 GDBRemoteCommunication::PacketResult::Success) {
4077 StringExtractorGDBRemote::ResponseType response_type =
4078 response.GetResponseType();
4079 if (response_type == StringExtractorGDBRemote::eResponse) {
4080 if (!response.Empty()) {
4081 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda37397352016-07-22 00:17:55 +00004082 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004083 }
Jason Molenda37397352016-07-22 00:17:55 +00004084 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004085 }
4086 return object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00004087}
4088
Kate Stoneb9c1b512016-09-06 20:57:50 +00004089StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
4090 StructuredData::ObjectSP object_sp;
4091 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4092
4093 if (m_gdb_comm.GetSharedCacheInfoSupported()) {
4094 StreamString packet;
4095 packet << "jGetSharedCacheInfo:";
4096 args_dict->Dump(packet, false);
4097
4098 // FIXME the final character of a JSON dictionary, '}', is the escape
4099 // character in gdb-remote binary mode. lldb currently doesn't escape
Adrian Prantl05097242018-04-30 16:49:04 +00004100 // these characters in its packet output -- so we add the quoted version of
4101 // the } character here manually in case we talk to a debugserver which un-
4102 // escapes the characters at packet read time.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004103 packet << (char)(0x7d ^ 0x20);
4104
4105 StringExtractorGDBRemote response;
4106 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004107 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4108 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004109 GDBRemoteCommunication::PacketResult::Success) {
4110 StringExtractorGDBRemote::ResponseType response_type =
4111 response.GetResponseType();
4112 if (response_type == StringExtractorGDBRemote::eResponse) {
4113 if (!response.Empty()) {
4114 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4115 }
4116 }
4117 }
4118 }
4119 return object_sp;
4120}
4121
Zachary Turner97206d52017-05-12 04:51:55 +00004122Status ProcessGDBRemote::ConfigureStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004123 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
4124 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
Todd Fiala75930012016-08-19 04:21:48 +00004125}
Jason Molenda37397352016-07-22 00:17:55 +00004126
Adrian Prantl05097242018-04-30 16:49:04 +00004127// Establish the largest memory read/write payloads we should use. If the
4128// remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004129//
Adrian Prantl05097242018-04-30 16:49:04 +00004130// If the remote stub's max packet size is crazy large, use a reasonable
4131// largeish default.
Jason Molenda6076bf42014-05-06 04:34:52 +00004132//
Adrian Prantl05097242018-04-30 16:49:04 +00004133// If the remote stub doesn't advertise a max packet size, use a conservative
4134// default.
Jason Molenda6076bf42014-05-06 04:34:52 +00004135
Kate Stoneb9c1b512016-09-06 20:57:50 +00004136void ProcessGDBRemote::GetMaxMemorySize() {
4137 const uint64_t reasonable_largeish_default = 128 * 1024;
4138 const uint64_t conservative_default = 512;
Jason Molenda6076bf42014-05-06 04:34:52 +00004139
Kate Stoneb9c1b512016-09-06 20:57:50 +00004140 if (m_max_memory_size == 0) {
4141 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4142 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4143 // Save the stub's claimed maximum packet size
4144 m_remote_stub_max_memory_size = stub_max_size;
Jason Molenda6076bf42014-05-06 04:34:52 +00004145
Adrian Prantl05097242018-04-30 16:49:04 +00004146 // Even if the stub says it can support ginormous packets, don't exceed
4147 // our reasonable largeish default packet size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004148 if (stub_max_size > reasonable_largeish_default) {
4149 stub_max_size = reasonable_largeish_default;
4150 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004151
Adrian Prantl05097242018-04-30 16:49:04 +00004152 // Memory packet have other overheads too like Maddr,size:#NN Instead of
4153 // calculating the bytes taken by size and addr every time, we take a
4154 // maximum guess here.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00004155 if (stub_max_size > 70)
4156 stub_max_size -= 32 + 32 + 6;
4157 else {
4158 // In unlikely scenario that max packet size is less then 70, we will
4159 // hope that data being written is small enough to fit.
4160 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4161 GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4162 if (log)
4163 log->Warning("Packet size is too small. "
4164 "LLDB may face problems while writing memory");
4165 }
4166
Kate Stoneb9c1b512016-09-06 20:57:50 +00004167 m_max_memory_size = stub_max_size;
4168 } else {
4169 m_max_memory_size = conservative_default;
Jason Molenda6076bf42014-05-06 04:34:52 +00004170 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004171 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004172}
4173
Kate Stoneb9c1b512016-09-06 20:57:50 +00004174void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4175 uint64_t user_specified_max) {
4176 if (user_specified_max != 0) {
4177 GetMaxMemorySize();
Jason Molenda6076bf42014-05-06 04:34:52 +00004178
Kate Stoneb9c1b512016-09-06 20:57:50 +00004179 if (m_remote_stub_max_memory_size != 0) {
4180 if (m_remote_stub_max_memory_size < user_specified_max) {
4181 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4182 // packet size too
4183 // big, go as big
4184 // as the remote stub says we can go.
4185 } else {
4186 m_max_memory_size = user_specified_max; // user's packet size is good
4187 }
4188 } else {
4189 m_max_memory_size =
4190 user_specified_max; // user's packet size is probably fine
Jason Molenda6076bf42014-05-06 04:34:52 +00004191 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004192 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004193}
4194
Kate Stoneb9c1b512016-09-06 20:57:50 +00004195bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4196 const ArchSpec &arch,
4197 ModuleSpec &module_spec) {
4198 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004199
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004200 const ModuleCacheKey key(module_file_spec.GetPath(),
4201 arch.GetTriple().getTriple());
4202 auto cached = m_cached_module_specs.find(key);
4203 if (cached != m_cached_module_specs.end()) {
4204 module_spec = cached->second;
4205 return bool(module_spec);
4206 }
4207
Kate Stoneb9c1b512016-09-06 20:57:50 +00004208 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004209 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004210 log->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4211 __FUNCTION__, module_file_spec.GetPath().c_str(),
4212 arch.GetTriple().getTriple().c_str());
4213 return false;
4214 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004215
Kate Stoneb9c1b512016-09-06 20:57:50 +00004216 if (log) {
4217 StreamString stream;
4218 module_spec.Dump(stream);
4219 log->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4220 __FUNCTION__, module_file_spec.GetPath().c_str(),
Zachary Turnerc1564272016-11-16 21:15:24 +00004221 arch.GetTriple().getTriple().c_str(), stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004222 }
4223
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004224 m_cached_module_specs[key] = module_spec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004225 return true;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004226}
4227
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004228void ProcessGDBRemote::PrefetchModuleSpecs(
4229 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4230 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4231 if (module_specs) {
4232 for (const FileSpec &spec : module_file_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004233 m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4234 triple.getTriple())] = ModuleSpec();
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004235 for (const ModuleSpec &spec : *module_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004236 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4237 triple.getTriple())] = spec;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004238 }
4239}
4240
Kate Stoneb9c1b512016-09-06 20:57:50 +00004241bool ProcessGDBRemote::GetHostOSVersion(uint32_t &major, uint32_t &minor,
4242 uint32_t &update) {
4243 if (m_gdb_comm.GetOSVersion(major, minor, update))
4244 return true;
Adrian Prantl05097242018-04-30 16:49:04 +00004245 // We failed to get the host OS version, defer to the base implementation to
4246 // correctly invalidate the arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004247 return Process::GetHostOSVersion(major, minor, update);
Jim Ingham13c30d22015-11-05 22:33:17 +00004248}
4249
Colin Rileyc3c95b22015-04-16 15:51:33 +00004250namespace {
4251
4252typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004253
4254typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004255struct RegisterSetInfo {
4256 ConstString name;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004257};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004258
Greg Claytond04f0ed2015-05-26 18:00:51 +00004259typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004260
Kate Stoneb9c1b512016-09-06 20:57:50 +00004261struct GdbServerTargetInfo {
4262 std::string arch;
4263 std::string osabi;
4264 stringVec includes;
4265 RegisterSetMap reg_set_map;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004266};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004267
Kate Stoneb9c1b512016-09-06 20:57:50 +00004268bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4269 GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4270 uint32_t &cur_reg_num, uint32_t &reg_offset) {
4271 if (!feature_node)
4272 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004273
Kate Stoneb9c1b512016-09-06 20:57:50 +00004274 feature_node.ForEachChildElementWithName(
4275 "reg", [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset,
4276 &abi_sp](const XMLNode &reg_node) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004277 std::string gdb_group;
4278 std::string gdb_type;
4279 ConstString reg_name;
4280 ConstString alt_name;
4281 ConstString set_name;
4282 std::vector<uint32_t> value_regs;
4283 std::vector<uint32_t> invalidate_regs;
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004284 std::vector<uint8_t> dwarf_opcode_bytes;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004285 bool encoding_set = false;
4286 bool format_set = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004287 RegisterInfo reg_info = {
4288 NULL, // Name
4289 NULL, // Alt name
4290 0, // byte size
4291 reg_offset, // offset
4292 eEncodingUint, // encoding
4293 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004294 {
Jason Molendabf67a302015-09-01 05:17:01 +00004295 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004296 LLDB_INVALID_REGNUM, // DWARF reg num
4297 LLDB_INVALID_REGNUM, // generic reg num
Kate Stoneb9c1b512016-09-06 20:57:50 +00004298 cur_reg_num, // process plugin reg num
4299 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004300 },
4301 NULL,
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004302 NULL,
Kate Stoneb9c1b512016-09-06 20:57:50 +00004303 NULL, // Dwarf Expression opcode bytes pointer
4304 0 // Dwarf Expression opcode bytes length
Greg Claytond04f0ed2015-05-26 18:00:51 +00004305 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004306
Kate Stoneb9c1b512016-09-06 20:57:50 +00004307 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4308 &reg_name, &alt_name, &set_name, &value_regs,
4309 &invalidate_regs, &encoding_set, &format_set,
Zachary Turner3bc714b2017-03-02 00:05:25 +00004310 &reg_info, &reg_offset, &dwarf_opcode_bytes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004311 const llvm::StringRef &name,
4312 const llvm::StringRef &value) -> bool {
4313 if (name == "name") {
4314 reg_name.SetString(value);
4315 } else if (name == "bitsize") {
4316 reg_info.byte_size =
4317 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4318 } else if (name == "type") {
4319 gdb_type = value.str();
4320 } else if (name == "group") {
4321 gdb_group = value.str();
4322 } else if (name == "regnum") {
4323 const uint32_t regnum =
4324 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4325 if (regnum != LLDB_INVALID_REGNUM) {
4326 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004327 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004328 } else if (name == "offset") {
4329 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4330 } else if (name == "altname") {
4331 alt_name.SetString(value);
4332 } else if (name == "encoding") {
4333 encoding_set = true;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004334 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004335 } else if (name == "format") {
4336 format_set = true;
4337 Format format = eFormatInvalid;
Pavel Labath47cbf4a2018-04-10 09:03:59 +00004338 if (OptionArgParser::ToFormat(value.data(), format, NULL).Success())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004339 reg_info.format = format;
4340 else if (value == "vector-sint8")
4341 reg_info.format = eFormatVectorOfSInt8;
4342 else if (value == "vector-uint8")
4343 reg_info.format = eFormatVectorOfUInt8;
4344 else if (value == "vector-sint16")
4345 reg_info.format = eFormatVectorOfSInt16;
4346 else if (value == "vector-uint16")
4347 reg_info.format = eFormatVectorOfUInt16;
4348 else if (value == "vector-sint32")
4349 reg_info.format = eFormatVectorOfSInt32;
4350 else if (value == "vector-uint32")
4351 reg_info.format = eFormatVectorOfUInt32;
4352 else if (value == "vector-float32")
4353 reg_info.format = eFormatVectorOfFloat32;
Valentina Giusticda0ae42016-09-08 14:16:45 +00004354 else if (value == "vector-uint64")
4355 reg_info.format = eFormatVectorOfUInt64;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004356 else if (value == "vector-uint128")
4357 reg_info.format = eFormatVectorOfUInt128;
4358 } else if (name == "group_id") {
4359 const uint32_t set_id =
4360 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4361 RegisterSetMap::const_iterator pos =
4362 target_info.reg_set_map.find(set_id);
4363 if (pos != target_info.reg_set_map.end())
4364 set_name = pos->second.name;
4365 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4366 reg_info.kinds[eRegisterKindEHFrame] =
4367 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4368 } else if (name == "dwarf_regnum") {
4369 reg_info.kinds[eRegisterKindDWARF] =
4370 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4371 } else if (name == "generic") {
4372 reg_info.kinds[eRegisterKindGeneric] =
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004373 Args::StringToGenericRegister(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004374 } else if (name == "value_regnums") {
4375 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4376 } else if (name == "invalidate_regnums") {
4377 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4378 } else if (name == "dynamic_size_dwarf_expr_bytes") {
4379 StringExtractor opcode_extractor;
4380 std::string opcode_string = value.str();
4381 size_t dwarf_opcode_len = opcode_string.length() / 2;
4382 assert(dwarf_opcode_len > 0);
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004383
Kate Stoneb9c1b512016-09-06 20:57:50 +00004384 dwarf_opcode_bytes.resize(dwarf_opcode_len);
4385 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4386 opcode_extractor.GetStringRef().swap(opcode_string);
4387 uint32_t ret_val =
4388 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4389 assert(dwarf_opcode_len == ret_val);
Hafiz Abid Qadeer05008ca2017-01-19 15:11:01 +00004390 UNUSED_IF_ASSERT_DISABLED(ret_val);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004391 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4392 } else {
4393 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4394 }
4395 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004396 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004397
Kate Stoneb9c1b512016-09-06 20:57:50 +00004398 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4399 if (gdb_type.find("int") == 0) {
4400 reg_info.format = eFormatHex;
4401 reg_info.encoding = eEncodingUint;
4402 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4403 reg_info.format = eFormatAddressInfo;
4404 reg_info.encoding = eEncodingUint;
4405 } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4406 reg_info.format = eFormatFloat;
4407 reg_info.encoding = eEncodingIEEE754;
4408 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004409 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004410
Kate Stoneb9c1b512016-09-06 20:57:50 +00004411 // Only update the register set name if we didn't get a "reg_set"
Adrian Prantl05097242018-04-30 16:49:04 +00004412 // attribute. "set_name" will be empty if we didn't have a "reg_set"
Kate Stoneb9c1b512016-09-06 20:57:50 +00004413 // attribute.
Greg Claytond04f0ed2015-05-26 18:00:51 +00004414 if (!set_name && !gdb_group.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004415 set_name.SetCString(gdb_group.c_str());
Ed Maste81b4c5f2016-01-04 01:43:47 +00004416
Greg Claytond04f0ed2015-05-26 18:00:51 +00004417 reg_info.byte_offset = reg_offset;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004418 assert(reg_info.byte_size != 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004419 reg_offset += reg_info.byte_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004420 if (!value_regs.empty()) {
4421 value_regs.push_back(LLDB_INVALID_REGNUM);
4422 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004423 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004424 if (!invalidate_regs.empty()) {
4425 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4426 reg_info.invalidate_regs = invalidate_regs.data();
Greg Claytond04f0ed2015-05-26 18:00:51 +00004427 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004428
Jason Molenda63bd0db2015-09-15 23:20:34 +00004429 ++cur_reg_num;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004430 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004431 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004432
Greg Claytond04f0ed2015-05-26 18:00:51 +00004433 return true; // Keep iterating through all "reg" elements
Kate Stoneb9c1b512016-09-06 20:57:50 +00004434 });
4435 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004436}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004437
Eugene Zelenko0722f082015-10-24 01:28:05 +00004438} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004439
Adrian Prantl05097242018-04-30 16:49:04 +00004440// query the target of gdb-remote for extended target information return:
4441// 'true' on success
Colin Rileyc3c95b22015-04-16 15:51:33 +00004442// 'false' on failure
Kate Stoneb9c1b512016-09-06 20:57:50 +00004443bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4444 // Make sure LLDB has an XML parser it can use first
4445 if (!XMLDocument::XMLEnabled())
4446 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004447
Kate Stoneb9c1b512016-09-06 20:57:50 +00004448 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004449
Kate Stoneb9c1b512016-09-06 20:57:50 +00004450 GDBRemoteCommunicationClient &comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004451
Kate Stoneb9c1b512016-09-06 20:57:50 +00004452 // check that we have extended feature read support
4453 if (!comm.GetQXferFeaturesReadSupported())
4454 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004455
Kate Stoneb9c1b512016-09-06 20:57:50 +00004456 // request the target xml file
4457 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004458 lldb_private::Status lldberr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004459 if (!comm.ReadExtFeature(ConstString("features"), ConstString("target.xml"),
4460 raw, lldberr)) {
4461 return false;
4462 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004463
Kate Stoneb9c1b512016-09-06 20:57:50 +00004464 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004465
Kate Stoneb9c1b512016-09-06 20:57:50 +00004466 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) {
4467 GdbServerTargetInfo target_info;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004468
Kate Stoneb9c1b512016-09-06 20:57:50 +00004469 XMLNode target_node = xml_document.GetRootElement("target");
4470 if (target_node) {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004471 std::vector<XMLNode> feature_nodes;
4472 target_node.ForEachChildElement([&target_info, &feature_nodes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004473 const XMLNode &node) -> bool {
4474 llvm::StringRef name = node.GetName();
4475 if (name == "architecture") {
4476 node.GetElementText(target_info.arch);
4477 } else if (name == "osabi") {
4478 node.GetElementText(target_info.osabi);
4479 } else if (name == "xi:include" || name == "include") {
4480 llvm::StringRef href = node.GetAttributeValue("href");
4481 if (!href.empty())
4482 target_info.includes.push_back(href.str());
4483 } else if (name == "feature") {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004484 feature_nodes.push_back(node);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004485 } else if (name == "groups") {
4486 node.ForEachChildElementWithName(
4487 "group", [&target_info](const XMLNode &node) -> bool {
4488 uint32_t set_id = UINT32_MAX;
4489 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004490
Kate Stoneb9c1b512016-09-06 20:57:50 +00004491 node.ForEachAttribute(
4492 [&set_id, &set_info](const llvm::StringRef &name,
4493 const llvm::StringRef &value) -> bool {
4494 if (name == "id")
4495 set_id = StringConvert::ToUInt32(value.data(),
4496 UINT32_MAX, 0);
4497 if (name == "name")
4498 set_info.name = ConstString(value);
4499 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004500 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004501
Kate Stoneb9c1b512016-09-06 20:57:50 +00004502 if (set_id != UINT32_MAX)
4503 target_info.reg_set_map[set_id] = set_info;
4504 return true; // Keep iterating through all "group" elements
4505 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004506 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004507 return true; // Keep iterating through all children of the target_node
4508 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004509
Jason Molendac4dd04c2018-01-12 01:16:13 +00004510 // If the target.xml includes an architecture entry like
4511 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4512 // <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board)
4513 // use that if we don't have anything better.
4514 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4515 if (target_info.arch == "i386:x86-64")
4516 {
4517 // We don't have any information about vendor or OS.
4518 arch_to_use.SetTriple("x86_64--");
4519 GetTarget().MergeArchitecture(arch_to_use);
4520 }
4521 }
4522
Kate Stoneb9c1b512016-09-06 20:57:50 +00004523 // Initialize these outside of ParseRegisters, since they should not be
4524 // reset inside each include feature
4525 uint32_t cur_reg_num = 0;
4526 uint32_t reg_offset = 0;
4527
Adrian Prantl05097242018-04-30 16:49:04 +00004528 // Don't use Process::GetABI, this code gets called from DidAttach, and
4529 // in that context we haven't set the Target's architecture yet, so the
4530 // ABI is also potentially incorrect.
Jason Molenda43294c92017-06-29 02:57:03 +00004531 ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004532 for (auto &feature_node : feature_nodes) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004533 ParseRegisters(feature_node, target_info, this->m_register_info,
4534 abi_to_use_sp, cur_reg_num, reg_offset);
4535 }
4536
4537 for (const auto &include : target_info.includes) {
4538 // request register file
4539 std::string xml_data;
4540 if (!comm.ReadExtFeature(ConstString("features"), ConstString(include),
4541 xml_data, lldberr))
4542 continue;
4543
4544 XMLDocument include_xml_document;
4545 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(),
4546 include.c_str());
4547 XMLNode include_feature_node =
4548 include_xml_document.GetRootElement("feature");
4549 if (include_feature_node) {
4550 ParseRegisters(include_feature_node, target_info,
4551 this->m_register_info, abi_to_use_sp, cur_reg_num,
4552 reg_offset);
4553 }
4554 }
4555 this->m_register_info.Finalize(arch_to_use);
4556 }
4557 }
4558
4559 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004560}
4561
Zachary Turner97206d52017-05-12 04:51:55 +00004562Status ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004563 // Make sure LLDB has an XML parser it can use first
4564 if (!XMLDocument::XMLEnabled())
Zachary Turner97206d52017-05-12 04:51:55 +00004565 return Status(0, ErrorType::eErrorTypeGeneric);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004566
Kate Stoneb9c1b512016-09-06 20:57:50 +00004567 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
4568 if (log)
4569 log->Printf("ProcessGDBRemote::%s", __FUNCTION__);
4570
4571 GDBRemoteCommunicationClient &comm = m_gdb_comm;
4572
4573 // check that we have extended feature read support
4574 if (comm.GetQXferLibrariesSVR4ReadSupported()) {
4575 list.clear();
4576
4577 // request the loaded library list
4578 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004579 lldb_private::Status lldberr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004580
4581 if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4582 raw, lldberr))
Zachary Turner97206d52017-05-12 04:51:55 +00004583 return Status(0, ErrorType::eErrorTypeGeneric);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004584
4585 // parse the xml file in memory
Aidan Doddsc0c83852015-05-08 09:36:31 +00004586 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004587 log->Printf("parsing: %s", raw.c_str());
4588 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004589
Kate Stoneb9c1b512016-09-06 20:57:50 +00004590 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Zachary Turner97206d52017-05-12 04:51:55 +00004591 return Status(0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004592
Kate Stoneb9c1b512016-09-06 20:57:50 +00004593 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4594 if (!root_element)
Zachary Turner97206d52017-05-12 04:51:55 +00004595 return Status();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004596
Kate Stoneb9c1b512016-09-06 20:57:50 +00004597 // main link map structure
4598 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4599 if (!main_lm.empty()) {
4600 list.m_link_map =
4601 StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4602 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004603
Kate Stoneb9c1b512016-09-06 20:57:50 +00004604 root_element.ForEachChildElementWithName(
4605 "library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004606
Kate Stoneb9c1b512016-09-06 20:57:50 +00004607 LoadedModuleInfoList::LoadedModuleInfo module;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004608
Kate Stoneb9c1b512016-09-06 20:57:50 +00004609 library.ForEachAttribute(
Zachary Turner3bc714b2017-03-02 00:05:25 +00004610 [&module](const llvm::StringRef &name,
4611 const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004612
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004613 if (name == "name")
Kate Stoneb9c1b512016-09-06 20:57:50 +00004614 module.set_name(value.str());
4615 else if (name == "lm") {
4616 // the address of the link_map struct.
4617 module.set_link_map(StringConvert::ToUInt64(
4618 value.data(), LLDB_INVALID_ADDRESS, 0));
4619 } else if (name == "l_addr") {
4620 // the displacement as read from the field 'l_addr' of the
4621 // link_map struct.
4622 module.set_base(StringConvert::ToUInt64(
4623 value.data(), LLDB_INVALID_ADDRESS, 0));
4624 // base address is always a displacement, not an absolute
4625 // value.
4626 module.set_base_is_offset(true);
4627 } else if (name == "l_ld") {
4628 // the memory address of the libraries PT_DYAMIC section.
4629 module.set_dynamic(StringConvert::ToUInt64(
4630 value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004631 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004632
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004633 return true; // Keep iterating over all properties of "library"
Kate Stoneb9c1b512016-09-06 20:57:50 +00004634 });
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004635
Kate Stoneb9c1b512016-09-06 20:57:50 +00004636 if (log) {
4637 std::string name;
4638 lldb::addr_t lm = 0, base = 0, ld = 0;
4639 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004640
Kate Stoneb9c1b512016-09-06 20:57:50 +00004641 module.get_name(name);
4642 module.get_link_map(lm);
4643 module.get_base(base);
4644 module.get_base_is_offset(base_is_offset);
4645 module.get_dynamic(ld);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004646
Kate Stoneb9c1b512016-09-06 20:57:50 +00004647 log->Printf("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4648 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4649 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4650 name.c_str());
4651 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004652
Kate Stoneb9c1b512016-09-06 20:57:50 +00004653 list.add(module);
4654 return true; // Keep iterating over all "library" elements in the root
4655 // node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004656 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004657
Kate Stoneb9c1b512016-09-06 20:57:50 +00004658 if (log)
4659 log->Printf("found %" PRId32 " modules in total",
4660 (int)list.m_list.size());
4661 } else if (comm.GetQXferLibrariesReadSupported()) {
4662 list.clear();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004663
Kate Stoneb9c1b512016-09-06 20:57:50 +00004664 // request the loaded library list
4665 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004666 lldb_private::Status lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004667
Kate Stoneb9c1b512016-09-06 20:57:50 +00004668 if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4669 lldberr))
Zachary Turner97206d52017-05-12 04:51:55 +00004670 return Status(0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004671
Kate Stoneb9c1b512016-09-06 20:57:50 +00004672 if (log)
4673 log->Printf("parsing: %s", raw.c_str());
4674 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004675
Kate Stoneb9c1b512016-09-06 20:57:50 +00004676 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Zachary Turner97206d52017-05-12 04:51:55 +00004677 return Status(0, ErrorType::eErrorTypeGeneric);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004678
Kate Stoneb9c1b512016-09-06 20:57:50 +00004679 XMLNode root_element = doc.GetRootElement("library-list");
4680 if (!root_element)
Zachary Turner97206d52017-05-12 04:51:55 +00004681 return Status();
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004682
Kate Stoneb9c1b512016-09-06 20:57:50 +00004683 root_element.ForEachChildElementWithName(
4684 "library", [log, &list](const XMLNode &library) -> bool {
4685 LoadedModuleInfoList::LoadedModuleInfo module;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004686
Kate Stoneb9c1b512016-09-06 20:57:50 +00004687 llvm::StringRef name = library.GetAttributeValue("name");
4688 module.set_name(name.str());
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004689
Kate Stoneb9c1b512016-09-06 20:57:50 +00004690 // The base address of a given library will be the address of its
4691 // first section. Most remotes send only one section for Windows
4692 // targets for example.
4693 const XMLNode &section =
4694 library.FindFirstChildElementWithName("section");
4695 llvm::StringRef address = section.GetAttributeValue("address");
4696 module.set_base(
4697 StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4698 // These addresses are absolute values.
4699 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004700
Kate Stoneb9c1b512016-09-06 20:57:50 +00004701 if (log) {
4702 std::string name;
4703 lldb::addr_t base = 0;
4704 bool base_is_offset;
4705 module.get_name(name);
4706 module.get_base(base);
4707 module.get_base_is_offset(base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004708
Kate Stoneb9c1b512016-09-06 20:57:50 +00004709 log->Printf("found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4710 (base_is_offset ? "offset" : "absolute"), name.c_str());
4711 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004712
Kate Stoneb9c1b512016-09-06 20:57:50 +00004713 list.add(module);
4714 return true; // Keep iterating over all "library" elements in the root
4715 // node
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004716 });
4717
Kate Stoneb9c1b512016-09-06 20:57:50 +00004718 if (log)
4719 log->Printf("found %" PRId32 " modules in total",
4720 (int)list.m_list.size());
4721 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00004722 return Status(0, ErrorType::eErrorTypeGeneric);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004723 }
4724
Zachary Turner97206d52017-05-12 04:51:55 +00004725 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004726}
4727
4728lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4729 lldb::addr_t link_map,
4730 lldb::addr_t base_addr,
4731 bool value_is_offset) {
4732 DynamicLoader *loader = GetDynamicLoader();
4733 if (!loader)
4734 return nullptr;
4735
4736 return loader->LoadModuleAtAddress(file, link_map, base_addr,
4737 value_is_offset);
4738}
4739
4740size_t ProcessGDBRemote::LoadModules(LoadedModuleInfoList &module_list) {
4741 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4742
4743 // request a list of loaded libraries from GDBServer
4744 if (GetLoadedModuleList(module_list).Fail())
4745 return 0;
4746
4747 // get a list of all the modules
4748 ModuleList new_modules;
4749
4750 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list.m_list) {
4751 std::string mod_name;
4752 lldb::addr_t mod_base;
4753 lldb::addr_t link_map;
4754 bool mod_base_is_offset;
4755
4756 bool valid = true;
4757 valid &= modInfo.get_name(mod_name);
4758 valid &= modInfo.get_base(mod_base);
4759 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4760 if (!valid)
4761 continue;
4762
4763 if (!modInfo.get_link_map(link_map))
4764 link_map = LLDB_INVALID_ADDRESS;
4765
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00004766 FileSpec file(mod_name, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004767 lldb::ModuleSP module_sp =
4768 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4769
4770 if (module_sp.get())
4771 new_modules.Append(module_sp);
4772 }
4773
4774 if (new_modules.GetSize() > 0) {
4775 ModuleList removed_modules;
4776 Target &target = GetTarget();
4777 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4778
4779 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4780 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4781
4782 bool found = false;
4783 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4784 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4785 found = true;
4786 }
4787
4788 // The main executable will never be included in libraries-svr4, don't
4789 // remove it
4790 if (!found &&
4791 loaded_module.get() != target.GetExecutableModulePointer()) {
4792 removed_modules.Append(loaded_module);
4793 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004794 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004795
Kate Stoneb9c1b512016-09-06 20:57:50 +00004796 loaded_modules.Remove(removed_modules);
4797 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4798
4799 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4800 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4801 if (!obj)
4802 return true;
4803
4804 if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4805 return true;
4806
4807 lldb::ModuleSP module_copy_sp = module_sp;
4808 target.SetExecutableModule(module_copy_sp, false);
4809 return false;
4810 });
4811
4812 loaded_modules.AppendIfNeeded(new_modules);
4813 m_process->GetTarget().ModulesDidLoad(new_modules);
4814 }
4815
4816 return new_modules.GetSize();
4817}
4818
4819size_t ProcessGDBRemote::LoadModules() {
4820 LoadedModuleInfoList module_list;
4821 return LoadModules(module_list);
4822}
4823
Zachary Turner97206d52017-05-12 04:51:55 +00004824Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4825 bool &is_loaded,
4826 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004827 is_loaded = false;
4828 load_addr = LLDB_INVALID_ADDRESS;
4829
4830 std::string file_path = file.GetPath(false);
4831 if (file_path.empty())
Zachary Turner97206d52017-05-12 04:51:55 +00004832 return Status("Empty file name specified");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004833
4834 StreamString packet;
4835 packet.PutCString("qFileLoadAddress:");
4836 packet.PutCStringAsRawHex8(file_path.c_str());
4837
4838 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004839 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4840 false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00004841 GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00004842 return Status("Sending qFileLoadAddress packet failed");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004843
4844 if (response.IsErrorResponse()) {
4845 if (response.GetError() == 1) {
4846 // The file is not loaded into the inferior
4847 is_loaded = false;
4848 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00004849 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004850 }
4851
Zachary Turner97206d52017-05-12 04:51:55 +00004852 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004853 "Fetching file load address from remote server returned an error");
4854 }
4855
4856 if (response.IsNormalResponse()) {
4857 is_loaded = true;
4858 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
Zachary Turner97206d52017-05-12 04:51:55 +00004859 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004860 }
4861
Zachary Turner97206d52017-05-12 04:51:55 +00004862 return Status(
4863 "Unknown error happened during sending the load address packet");
Aidan Doddsc0c83852015-05-08 09:36:31 +00004864}
4865
Kate Stoneb9c1b512016-09-06 20:57:50 +00004866void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4867 // We must call the lldb_private::Process::ModulesDidLoad () first before we
4868 // do anything
4869 Process::ModulesDidLoad(module_list);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004870
Adrian Prantl05097242018-04-30 16:49:04 +00004871 // After loading shared libraries, we can ask our remote GDB server if it
4872 // needs any symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004873 m_gdb_comm.ServeSymbolLookups(this);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004874}
4875
Kate Stoneb9c1b512016-09-06 20:57:50 +00004876void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4877 AppendSTDOUT(out.data(), out.size());
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004878}
4879
4880static const char *end_delimiter = "--end--;";
4881static const int end_delimiter_len = 8;
4882
Kate Stoneb9c1b512016-09-06 20:57:50 +00004883void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4884 std::string input = data.str(); // '1' to move beyond 'A'
4885 if (m_partial_profile_data.length() > 0) {
4886 m_partial_profile_data.append(input);
4887 input = m_partial_profile_data;
4888 m_partial_profile_data.clear();
4889 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004890
Kate Stoneb9c1b512016-09-06 20:57:50 +00004891 size_t found, pos = 0, len = input.length();
4892 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4893 StringExtractorGDBRemote profileDataExtractor(
4894 input.substr(pos, found).c_str());
4895 std::string profile_data =
4896 HarmonizeThreadIdsForProfileData(profileDataExtractor);
4897 BroadcastAsyncProfileData(profile_data);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004898
Kate Stoneb9c1b512016-09-06 20:57:50 +00004899 pos = found + end_delimiter_len;
4900 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004901
Kate Stoneb9c1b512016-09-06 20:57:50 +00004902 if (pos < len) {
4903 // Last incomplete chunk.
4904 m_partial_profile_data = input.substr(pos);
4905 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004906}
4907
Kate Stoneb9c1b512016-09-06 20:57:50 +00004908std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4909 StringExtractorGDBRemote &profileDataExtractor) {
4910 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4911 std::string output;
4912 llvm::raw_string_ostream output_stream(output);
4913 llvm::StringRef name, value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004914
Kate Stoneb9c1b512016-09-06 20:57:50 +00004915 // Going to assuming thread_used_usec comes first, else bail out.
4916 while (profileDataExtractor.GetNameColonValue(name, value)) {
4917 if (name.compare("thread_used_id") == 0) {
4918 StringExtractor threadIDHexExtractor(value);
4919 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004920
Kate Stoneb9c1b512016-09-06 20:57:50 +00004921 bool has_used_usec = false;
4922 uint32_t curr_used_usec = 0;
4923 llvm::StringRef usec_name, usec_value;
4924 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4925 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4926 if (usec_name.equals("thread_used_usec")) {
4927 has_used_usec = true;
4928 usec_value.getAsInteger(0, curr_used_usec);
4929 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004930 // We didn't find what we want, it is probably an older version. Bail
4931 // out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004932 profileDataExtractor.SetFilePos(input_file_pos);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004933 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004934 }
4935
4936 if (has_used_usec) {
4937 uint32_t prev_used_usec = 0;
4938 std::map<uint64_t, uint32_t>::iterator iterator =
4939 m_thread_id_to_used_usec_map.find(thread_id);
4940 if (iterator != m_thread_id_to_used_usec_map.end()) {
4941 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004942 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004943
4944 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4945 // A good first time record is one that runs for at least 0.25 sec
4946 bool good_first_time =
4947 (prev_used_usec == 0) && (real_used_usec > 250000);
4948 bool good_subsequent_time =
4949 (prev_used_usec > 0) &&
4950 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4951
4952 if (good_first_time || good_subsequent_time) {
Adrian Prantl05097242018-04-30 16:49:04 +00004953 // We try to avoid doing too many index id reservation, resulting in
4954 // fast increase of index ids.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004955
4956 output_stream << name << ":";
4957 int32_t index_id = AssignIndexIDToThread(thread_id);
4958 output_stream << index_id << ";";
4959
4960 output_stream << usec_name << ":" << usec_value << ";";
4961 } else {
4962 // Skip past 'thread_used_name'.
4963 llvm::StringRef local_name, local_value;
4964 profileDataExtractor.GetNameColonValue(local_name, local_value);
4965 }
4966
4967 // Store current time as previous time so that they can be compared
4968 // later.
4969 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4970 } else {
4971 // Bail out and use old string.
4972 output_stream << name << ":" << value << ";";
4973 }
4974 } else {
4975 output_stream << name << ":" << value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004976 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004977 }
4978 output_stream << end_delimiter;
4979 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004980
Kate Stoneb9c1b512016-09-06 20:57:50 +00004981 return output_stream.str();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004982}
4983
Kate Stoneb9c1b512016-09-06 20:57:50 +00004984void ProcessGDBRemote::HandleStopReply() {
4985 if (GetStopID() != 0)
4986 return;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004987
Kate Stoneb9c1b512016-09-06 20:57:50 +00004988 if (GetID() == LLDB_INVALID_PROCESS_ID) {
4989 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
4990 if (pid != LLDB_INVALID_PROCESS_ID)
4991 SetID(pid);
4992 }
4993 BuildDynamicRegisterInfo(true);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004994}
Eugene Zelenko0722f082015-10-24 01:28:05 +00004995
Todd Fialafcdb1af2016-09-10 00:06:29 +00004996static const char *const s_async_json_packet_prefix = "JSON-async:";
4997
4998static StructuredData::ObjectSP
4999ParseStructuredDataPacket(llvm::StringRef packet) {
5000 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
5001
5002 if (!packet.consume_front(s_async_json_packet_prefix)) {
5003 if (log) {
5004 log->Printf(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +00005005 "GDBRemoteCommunicationClientBase::%s() received $J packet "
Todd Fialafcdb1af2016-09-10 00:06:29 +00005006 "but was not a StructuredData packet: packet starts with "
5007 "%s",
5008 __FUNCTION__,
5009 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
5010 }
5011 return StructuredData::ObjectSP();
5012 }
5013
Adrian Prantl05097242018-04-30 16:49:04 +00005014 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
Todd Fialafcdb1af2016-09-10 00:06:29 +00005015 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
5016 if (log) {
5017 if (json_sp) {
5018 StreamString json_str;
5019 json_sp->Dump(json_str);
5020 json_str.Flush();
5021 log->Printf("ProcessGDBRemote::%s() "
5022 "received Async StructuredData packet: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00005023 __FUNCTION__, json_str.GetData());
Todd Fialafcdb1af2016-09-10 00:06:29 +00005024 } else {
5025 log->Printf("ProcessGDBRemote::%s"
5026 "() received StructuredData packet:"
5027 " parse failure",
5028 __FUNCTION__);
5029 }
5030 }
5031 return json_sp;
5032}
5033
5034void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
5035 auto structured_data_sp = ParseStructuredDataPacket(data);
5036 if (structured_data_sp)
5037 RouteAsyncStructuredData(structured_data_sp);
Todd Fiala75930012016-08-19 04:21:48 +00005038}
5039
Kate Stoneb9c1b512016-09-06 20:57:50 +00005040class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
Greg Claytone034a042015-05-21 20:52:06 +00005041public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005042 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
5043 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5044 "Tests packet speeds of various sizes to determine "
5045 "the performance characteristics of the GDB remote "
5046 "connection. ",
5047 NULL),
5048 m_option_group(),
5049 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5050 "The number of packets to send of each varying size "
5051 "(default is 1000).",
5052 1000),
5053 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5054 "The maximum number of bytes to send in a packet. Sizes "
5055 "increase in powers of 2 while the size is less than or "
5056 "equal to this option value. (default 1024).",
5057 1024),
5058 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5059 "The maximum number of bytes to receive in a packet. Sizes "
5060 "increase in powers of 2 while the size is less than or "
5061 "equal to this option value. (default 1024).",
5062 1024),
5063 m_json(LLDB_OPT_SET_1, false, "json", 'j',
5064 "Print the output as JSON data for easy parsing.", false, true) {
5065 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5066 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5067 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5068 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5069 m_option_group.Finalize();
5070 }
Greg Claytone034a042015-05-21 20:52:06 +00005071
Kate Stoneb9c1b512016-09-06 20:57:50 +00005072 ~CommandObjectProcessGDBRemoteSpeedTest() {}
Eugene Zelenko0722f082015-10-24 01:28:05 +00005073
Kate Stoneb9c1b512016-09-06 20:57:50 +00005074 Options *GetOptions() override { return &m_option_group; }
Greg Claytone034a042015-05-21 20:52:06 +00005075
Kate Stoneb9c1b512016-09-06 20:57:50 +00005076 bool DoExecute(Args &command, CommandReturnObject &result) override {
5077 const size_t argc = command.GetArgumentCount();
5078 if (argc == 0) {
5079 ProcessGDBRemote *process =
5080 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5081 .GetProcessPtr();
5082 if (process) {
5083 StreamSP output_stream_sp(
5084 m_interpreter.GetDebugger().GetAsyncOutputStream());
5085 result.SetImmediateOutputStream(output_stream_sp);
Greg Claytone034a042015-05-21 20:52:06 +00005086
Kate Stoneb9c1b512016-09-06 20:57:50 +00005087 const uint32_t num_packets =
5088 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5089 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5090 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5091 const bool json = m_json.GetOptionValue().GetCurrentValue();
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00005092 const uint64_t k_recv_amount =
5093 4 * 1024 * 1024; // Receive amount in bytes
5094 process->GetGDBRemote().TestPacketSpeed(
5095 num_packets, max_send, max_recv, k_recv_amount, json,
5096 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005097 result.SetStatus(eReturnStatusSuccessFinishResult);
5098 return true;
5099 }
5100 } else {
5101 result.AppendErrorWithFormat("'%s' takes no arguments",
5102 m_cmd_name.c_str());
Greg Claytone034a042015-05-21 20:52:06 +00005103 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005104 result.SetStatus(eReturnStatusFailed);
5105 return false;
5106 }
5107
Greg Claytone034a042015-05-21 20:52:06 +00005108protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005109 OptionGroupOptions m_option_group;
5110 OptionGroupUInt64 m_num_packets;
5111 OptionGroupUInt64 m_max_send;
5112 OptionGroupUInt64 m_max_recv;
5113 OptionGroupBoolean m_json;
Greg Claytone034a042015-05-21 20:52:06 +00005114};
5115
Kate Stoneb9c1b512016-09-06 20:57:50 +00005116class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005117private:
Greg Clayton998255b2012-10-13 02:07:45 +00005118public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005119 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5120 : CommandObjectParsed(interpreter, "process plugin packet history",
5121 "Dumps the packet history buffer. ", NULL) {}
5122
5123 ~CommandObjectProcessGDBRemotePacketHistory() {}
5124
5125 bool DoExecute(Args &command, CommandReturnObject &result) override {
5126 const size_t argc = command.GetArgumentCount();
5127 if (argc == 0) {
5128 ProcessGDBRemote *process =
5129 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5130 .GetProcessPtr();
5131 if (process) {
5132 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5133 result.SetStatus(eReturnStatusSuccessFinishResult);
5134 return true;
5135 }
5136 } else {
5137 result.AppendErrorWithFormat("'%s' takes no arguments",
5138 m_cmd_name.c_str());
5139 }
5140 result.SetStatus(eReturnStatusFailed);
5141 return false;
5142 }
5143};
5144
5145class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5146private:
5147public:
5148 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5149 : CommandObjectParsed(
5150 interpreter, "process plugin packet xfer-size",
5151 "Maximum size that lldb will try to read/write one one chunk.",
5152 NULL) {}
5153
5154 ~CommandObjectProcessGDBRemotePacketXferSize() {}
5155
5156 bool DoExecute(Args &command, CommandReturnObject &result) override {
5157 const size_t argc = command.GetArgumentCount();
5158 if (argc == 0) {
5159 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5160 "amount to be transferred when "
5161 "reading/writing",
5162 m_cmd_name.c_str());
5163 result.SetStatus(eReturnStatusFailed);
5164 return false;
Greg Clayton998255b2012-10-13 02:07:45 +00005165 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005166
Kate Stoneb9c1b512016-09-06 20:57:50 +00005167 ProcessGDBRemote *process =
5168 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5169 if (process) {
5170 const char *packet_size = command.GetArgumentAtIndex(0);
5171 errno = 0;
5172 uint64_t user_specified_max = strtoul(packet_size, NULL, 10);
5173 if (errno == 0 && user_specified_max != 0) {
5174 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5175 result.SetStatus(eReturnStatusSuccessFinishResult);
5176 return true;
5177 }
5178 }
5179 result.SetStatus(eReturnStatusFailed);
5180 return false;
5181 }
5182};
5183
5184class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5185private:
5186public:
5187 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5188 : CommandObjectParsed(interpreter, "process plugin packet send",
5189 "Send a custom packet through the GDB remote "
5190 "protocol and print the answer. "
5191 "The packet header and footer will automatically "
5192 "be added to the packet prior to sending and "
5193 "stripped from the result.",
5194 NULL) {}
5195
5196 ~CommandObjectProcessGDBRemotePacketSend() {}
5197
5198 bool DoExecute(Args &command, CommandReturnObject &result) override {
5199 const size_t argc = command.GetArgumentCount();
5200 if (argc == 0) {
5201 result.AppendErrorWithFormat(
5202 "'%s' takes a one or more packet content arguments",
5203 m_cmd_name.c_str());
5204 result.SetStatus(eReturnStatusFailed);
5205 return false;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005206 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005207
Kate Stoneb9c1b512016-09-06 20:57:50 +00005208 ProcessGDBRemote *process =
5209 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5210 if (process) {
5211 for (size_t i = 0; i < argc; ++i) {
5212 const char *packet_cstr = command.GetArgumentAtIndex(0);
5213 bool send_async = true;
5214 StringExtractorGDBRemote response;
5215 process->GetGDBRemote().SendPacketAndWaitForResponse(
5216 packet_cstr, response, send_async);
5217 result.SetStatus(eReturnStatusSuccessFinishResult);
5218 Stream &output_strm = result.GetOutputStream();
5219 output_strm.Printf(" packet: %s\n", packet_cstr);
5220 std::string &response_str = response.GetStringRef();
5221
5222 if (strstr(packet_cstr, "qGetProfileData") != NULL) {
5223 response_str = process->HarmonizeThreadIdsForProfileData(response);
Greg Clayton02686b82012-10-15 22:42:16 +00005224 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005225
5226 if (response_str.empty())
5227 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
Greg Clayton02686b82012-10-15 22:42:16 +00005228 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005229 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5230 }
Greg Clayton02686b82012-10-15 22:42:16 +00005231 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005232 return true;
5233 }
Greg Clayton02686b82012-10-15 22:42:16 +00005234};
5235
Kate Stoneb9c1b512016-09-06 20:57:50 +00005236class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005237private:
Jason Molenda6076bf42014-05-06 04:34:52 +00005238public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005239 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5240 : CommandObjectRaw(interpreter, "process plugin packet monitor",
5241 "Send a qRcmd packet through the GDB remote protocol "
5242 "and print the response."
5243 "The argument passed to this command will be hex "
5244 "encoded into a valid 'qRcmd' packet, sent and the "
Zachary Turnera4496982016-10-05 21:14:38 +00005245 "response will be printed.") {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005246
5247 ~CommandObjectProcessGDBRemotePacketMonitor() {}
5248
5249 bool DoExecute(const char *command, CommandReturnObject &result) override {
5250 if (command == NULL || command[0] == '\0') {
5251 result.AppendErrorWithFormat("'%s' takes a command string argument",
5252 m_cmd_name.c_str());
5253 result.SetStatus(eReturnStatusFailed);
5254 return false;
Jason Molenda6076bf42014-05-06 04:34:52 +00005255 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005256
Kate Stoneb9c1b512016-09-06 20:57:50 +00005257 ProcessGDBRemote *process =
5258 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5259 if (process) {
5260 StreamString packet;
5261 packet.PutCString("qRcmd,");
5262 packet.PutBytesAsRawHex8(command, strlen(command));
Ed Maste81b4c5f2016-01-04 01:43:47 +00005263
Kate Stoneb9c1b512016-09-06 20:57:50 +00005264 bool send_async = true;
5265 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005266 Stream &output_strm = result.GetOutputStream();
Pavel Labath7da84752018-01-10 14:39:08 +00005267 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5268 packet.GetString(), response, send_async,
5269 [&output_strm](llvm::StringRef output) { output_strm << output; });
5270 result.SetStatus(eReturnStatusSuccessFinishResult);
Zachary Turnerc1564272016-11-16 21:15:24 +00005271 output_strm.Printf(" packet: %s\n", packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005272 const std::string &response_str = response.GetStringRef();
Jason Molenda6076bf42014-05-06 04:34:52 +00005273
Kate Stoneb9c1b512016-09-06 20:57:50 +00005274 if (response_str.empty())
5275 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5276 else
5277 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
Jason Molenda6076bf42014-05-06 04:34:52 +00005278 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005279 return true;
5280 }
Jason Molenda6076bf42014-05-06 04:34:52 +00005281};
5282
Kate Stoneb9c1b512016-09-06 20:57:50 +00005283class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005284private:
Greg Clayton02686b82012-10-15 22:42:16 +00005285public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005286 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5287 : CommandObjectMultiword(interpreter, "process plugin packet",
5288 "Commands that deal with GDB remote packets.",
5289 NULL) {
5290 LoadSubCommand(
5291 "history",
5292 CommandObjectSP(
5293 new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5294 LoadSubCommand(
5295 "send", CommandObjectSP(
5296 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5297 LoadSubCommand(
5298 "monitor",
5299 CommandObjectSP(
5300 new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5301 LoadSubCommand(
5302 "xfer-size",
5303 CommandObjectSP(
5304 new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5305 LoadSubCommand("speed-test",
5306 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5307 interpreter)));
5308 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005309
Kate Stoneb9c1b512016-09-06 20:57:50 +00005310 ~CommandObjectProcessGDBRemotePacket() {}
Greg Clayton998255b2012-10-13 02:07:45 +00005311};
5312
Kate Stoneb9c1b512016-09-06 20:57:50 +00005313class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
Greg Claytonba4a0a52013-02-01 23:03:47 +00005314public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005315 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5316 : CommandObjectMultiword(
5317 interpreter, "process plugin",
5318 "Commands for operating on a ProcessGDBRemote process.",
5319 "process plugin <subcommand> [<subcommand-options>]") {
5320 LoadSubCommand(
5321 "packet",
5322 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5323 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005324
Kate Stoneb9c1b512016-09-06 20:57:50 +00005325 ~CommandObjectMultiwordProcessGDBRemote() {}
Greg Claytonba4a0a52013-02-01 23:03:47 +00005326};
5327
Kate Stoneb9c1b512016-09-06 20:57:50 +00005328CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5329 if (!m_command_sp)
5330 m_command_sp.reset(new CommandObjectMultiwordProcessGDBRemote(
5331 GetTarget().GetDebugger().GetCommandInterpreter()));
5332 return m_command_sp.get();
Greg Clayton998255b2012-10-13 02:07:45 +00005333}