blob: e65f2f3e3b1d0f85a5c5e93624d780f1d653b4b5 [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)
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000827 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false,
828 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829 if (!stdout_file_spec)
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000830 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false,
831 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832 if (!stderr_file_spec)
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000833 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false,
834 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835 } else if (platform_sp && platform_sp->IsHost()) {
836 // If the debugserver is local and we aren't disabling STDIO, lets use
837 // a pseudo terminal to instead of relying on the 'O' packets for stdio
838 // since 'O' packets can really slow down debugging if the inferior
839 // does a lot of output.
840 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
841 pty.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, NULL, 0)) {
842 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
Chaoren Lind3173f32015-05-29 19:52:29 +0000843
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844 if (!stdin_file_spec)
845 stdin_file_spec = slave_name;
Chaoren Lind3173f32015-05-29 19:52:29 +0000846
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 if (!stdout_file_spec)
848 stdout_file_spec = slave_name;
Greg Clayton71337622011-02-24 22:24:29 +0000849
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 if (!stderr_file_spec)
851 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000852 }
Vince Harron1b5a74e2015-01-21 22:42:49 +0000853 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 log->Printf(
855 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
856 "(IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
857 __FUNCTION__,
858 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
859 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
860 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
861 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000862
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863 if (log)
864 log->Printf("ProcessGDBRemote::%s final STDIO paths after all "
865 "adjustments: stdin=%s, stdout=%s, stderr=%s",
866 __FUNCTION__,
867 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
868 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
869 stderr_file_spec ? stderr_file_spec.GetCString()
870 : "<null>");
Ed Maste81b4c5f2016-01-04 01:43:47 +0000871
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872 if (stdin_file_spec)
873 m_gdb_comm.SetSTDIN(stdin_file_spec);
874 if (stdout_file_spec)
875 m_gdb_comm.SetSTDOUT(stdout_file_spec);
876 if (stderr_file_spec)
877 m_gdb_comm.SetSTDERR(stderr_file_spec);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
880 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000881
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882 m_gdb_comm.SendLaunchArchPacket(
883 GetTarget().GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 const char *launch_event_data = launch_info.GetLaunchEventData();
886 if (launch_event_data != NULL && *launch_event_data != '\0')
887 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
Eugene Zelenko0722f082015-10-24 01:28:05 +0000888
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889 if (working_dir) {
890 m_gdb_comm.SetWorkingDir(working_dir);
891 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000892
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893 // Send the environment and the program + arguments after we connect
Pavel Labath62930e52018-01-10 11:57:31 +0000894 m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
Ewan Crawford78baa192015-05-13 09:18:18 +0000895
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 {
897 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +0000898 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
899 std::chrono::seconds(10));
Ewan Crawford78baa192015-05-13 09:18:18 +0000900
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901 int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
902 if (arg_packet_err == 0) {
903 std::string error_str;
904 if (m_gdb_comm.GetLaunchSuccess(error_str)) {
905 SetID(m_gdb_comm.GetCurrentProcessID());
906 } else {
907 error.SetErrorString(error_str.c_str());
908 }
909 } else {
910 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
911 arg_packet_err);
912 }
913 }
914
915 if (GetID() == LLDB_INVALID_PROCESS_ID) {
916 if (log)
917 log->Printf("failed to connect to debugserver: %s",
918 error.AsCString());
919 KillDebugserverProcess();
920 return error;
921 }
922
923 StringExtractorGDBRemote response;
924 if (m_gdb_comm.GetStopReply(response)) {
Ewan Crawford78baa192015-05-13 09:18:18 +0000925 SetLastStopPacket(response);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 // '?' Packets must be handled differently in non-stop mode
927 if (GetTarget().GetNonStopModeEnabled())
928 HandleStopReplySequence();
929
930 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
931
932 if (process_arch.IsValid()) {
933 GetTarget().MergeArchitecture(process_arch);
934 } else {
935 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
936 if (host_arch.IsValid())
937 GetTarget().MergeArchitecture(host_arch);
938 }
939
940 SetPrivateState(SetThreadStopInfo(response));
941
942 if (!disable_stdio) {
Pavel Labath07d6f882017-12-11 10:09:14 +0000943 if (pty.GetMasterFileDescriptor() != PseudoTerminal::invalid_fd)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000944 SetSTDIOFileDescriptor(pty.ReleaseMasterFileDescriptor());
945 }
946 }
947 } else {
948 if (log)
949 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Ewan Crawford78baa192015-05-13 09:18:18 +0000950 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 } else {
952 // Set our user ID to an invalid process ID.
953 SetID(LLDB_INVALID_PROCESS_ID);
954 error.SetErrorStringWithFormat(
955 "failed to get object file from '%s' for arch %s",
956 exe_module->GetFileSpec().GetFilename().AsCString(),
957 exe_module->GetArchitecture().GetArchitectureName());
958 }
959 return error;
Ewan Crawford78baa192015-05-13 09:18:18 +0000960}
961
Zachary Turner97206d52017-05-12 04:51:55 +0000962Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
963 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 // Only connect if we have a valid connect URL
965 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
966
Zachary Turner31659452016-11-17 21:15:14 +0000967 if (!connect_url.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 if (log)
969 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
Zachary Turner31659452016-11-17 21:15:14 +0000970 connect_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
972 new ConnectionFileDescriptor());
973 if (conn_ap.get()) {
974 const uint32_t max_retry_count = 50;
975 uint32_t retry_count = 0;
976 while (!m_gdb_comm.IsConnected()) {
977 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) {
978 m_gdb_comm.SetConnection(conn_ap.release());
979 break;
980 } else if (error.WasInterrupted()) {
981 // If we were interrupted, don't keep retrying.
982 break;
983 }
984
985 retry_count++;
986
987 if (retry_count >= max_retry_count)
988 break;
989
990 usleep(100000);
991 }
992 }
993 }
994
995 if (!m_gdb_comm.IsConnected()) {
996 if (error.Success())
997 error.SetErrorString("not connected to remote gdb server");
998 return error;
999 }
1000
Adrian Prantl05097242018-04-30 16:49:04 +00001001 // Start the communications read thread so all incoming data can be parsed
1002 // into packets and queued as they arrive.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 if (GetTarget().GetNonStopModeEnabled())
1004 m_gdb_comm.StartReadThread();
1005
Adrian Prantl05097242018-04-30 16:49:04 +00001006 // We always seem to be able to open a connection to a local port so we need
1007 // to make sure we can then send data to it. If we can't then we aren't
1008 // actually connected to anything, so try and do the handshake with the
1009 // remote GDB server and make sure that goes alright.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 if (!m_gdb_comm.HandshakeWithServer(&error)) {
1011 m_gdb_comm.Disconnect();
1012 if (error.Success())
1013 error.SetErrorString("not connected to remote gdb server");
1014 return error;
1015 }
1016
1017 // Send $QNonStop:1 packet on startup if required
1018 if (GetTarget().GetNonStopModeEnabled())
1019 GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true));
1020
1021 m_gdb_comm.GetEchoSupported();
1022 m_gdb_comm.GetThreadSuffixSupported();
1023 m_gdb_comm.GetListThreadsInStopReplySupported();
1024 m_gdb_comm.GetHostInfo();
1025 m_gdb_comm.GetVContSupported('c');
1026 m_gdb_comm.GetVAttachOrWaitSupported();
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001027 m_gdb_comm.EnableErrorStringInPacket();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028
1029 // Ask the remote server for the default thread id
1030 if (GetTarget().GetNonStopModeEnabled())
1031 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1032
1033 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1034 for (size_t idx = 0; idx < num_cmds; idx++) {
1035 StringExtractorGDBRemote response;
1036 m_gdb_comm.SendPacketAndWaitForResponse(
1037 GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1038 }
1039 return error;
1040}
1041
1042void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
1043 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1044 if (log)
1045 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1046 if (GetID() != LLDB_INVALID_PROCESS_ID) {
1047 BuildDynamicRegisterInfo(false);
1048
1049 // See if the GDB server supports the qHostInfo information
1050
Adrian Prantl05097242018-04-30 16:49:04 +00001051 // See if the GDB server supports the qProcessInfo packet, if so prefer
1052 // that over the Host information as it will be more specific to our
1053 // process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054
1055 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1056 if (remote_process_arch.IsValid()) {
1057 process_arch = remote_process_arch;
1058 if (log)
1059 log->Printf("ProcessGDBRemote::%s gdb-remote had process architecture, "
1060 "using %s %s",
1061 __FUNCTION__, process_arch.GetArchitectureName()
1062 ? process_arch.GetArchitectureName()
1063 : "<null>",
1064 process_arch.GetTriple().getTriple().c_str()
1065 ? process_arch.GetTriple().getTriple().c_str()
1066 : "<null>");
1067 } else {
1068 process_arch = m_gdb_comm.GetHostArchitecture();
1069 if (log)
1070 log->Printf("ProcessGDBRemote::%s gdb-remote did not have process "
1071 "architecture, using gdb-remote host architecture %s %s",
1072 __FUNCTION__, process_arch.GetArchitectureName()
1073 ? process_arch.GetArchitectureName()
1074 : "<null>",
1075 process_arch.GetTriple().getTriple().c_str()
1076 ? process_arch.GetTriple().getTriple().c_str()
1077 : "<null>");
1078 }
1079
1080 if (process_arch.IsValid()) {
1081 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1082 if (target_arch.IsValid()) {
1083 if (log)
1084 log->Printf(
1085 "ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1086 __FUNCTION__, target_arch.GetArchitectureName()
1087 ? target_arch.GetArchitectureName()
1088 : "<null>",
1089 target_arch.GetTriple().getTriple().c_str()
1090 ? target_arch.GetTriple().getTriple().c_str()
1091 : "<null>");
1092
1093 // If the remote host is ARM and we have apple as the vendor, then
1094 // ARM executables and shared libraries can have mixed ARM
1095 // architectures.
1096 // You can have an armv6 executable, and if the host is armv7, then the
1097 // system will load the best possible architecture for all shared
Adrian Prantl05097242018-04-30 16:49:04 +00001098 // libraries it has, so we really need to take the remote host
1099 // architecture as our defacto architecture in this case.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100
1101 if ((process_arch.GetMachine() == llvm::Triple::arm ||
1102 process_arch.GetMachine() == llvm::Triple::thumb) &&
1103 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1104 GetTarget().SetArchitecture(process_arch);
1105 if (log)
1106 log->Printf("ProcessGDBRemote::%s remote process is ARM/Apple, "
1107 "setting target arch to %s %s",
1108 __FUNCTION__, process_arch.GetArchitectureName()
1109 ? process_arch.GetArchitectureName()
1110 : "<null>",
1111 process_arch.GetTriple().getTriple().c_str()
1112 ? process_arch.GetTriple().getTriple().c_str()
1113 : "<null>");
1114 } else {
1115 // Fill in what is missing in the triple
1116 const llvm::Triple &remote_triple = process_arch.GetTriple();
1117 llvm::Triple new_target_triple = target_arch.GetTriple();
1118 if (new_target_triple.getVendorName().size() == 0) {
1119 new_target_triple.setVendor(remote_triple.getVendor());
1120
1121 if (new_target_triple.getOSName().size() == 0) {
1122 new_target_triple.setOS(remote_triple.getOS());
1123
1124 if (new_target_triple.getEnvironmentName().size() == 0)
1125 new_target_triple.setEnvironment(
1126 remote_triple.getEnvironment());
1127 }
1128
1129 ArchSpec new_target_arch = target_arch;
1130 new_target_arch.SetTriple(new_target_triple);
1131 GetTarget().SetArchitecture(new_target_arch);
1132 }
1133 }
1134
1135 if (log)
1136 log->Printf("ProcessGDBRemote::%s final target arch after "
1137 "adjustments for remote architecture: %s %s",
1138 __FUNCTION__, target_arch.GetArchitectureName()
1139 ? target_arch.GetArchitectureName()
1140 : "<null>",
1141 target_arch.GetTriple().getTriple().c_str()
1142 ? target_arch.GetTriple().getTriple().c_str()
1143 : "<null>");
1144 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001145 // The target doesn't have a valid architecture yet, set it from the
1146 // architecture we got from the remote GDB server
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147 GetTarget().SetArchitecture(process_arch);
1148 }
1149 }
1150
Adrian Prantl05097242018-04-30 16:49:04 +00001151 // Find out which StructuredDataPlugins are supported by the debug monitor.
1152 // These plugins transmit data over async $J packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153 auto supported_packets_array =
1154 m_gdb_comm.GetSupportedStructuredDataPlugins();
1155 if (supported_packets_array)
1156 MapSupportedStructuredDataPlugins(*supported_packets_array);
1157 }
1158}
1159
1160void ProcessGDBRemote::DidLaunch() {
1161 ArchSpec process_arch;
1162 DidLaunchOrAttach(process_arch);
1163}
1164
Zachary Turner97206d52017-05-12 04:51:55 +00001165Status ProcessGDBRemote::DoAttachToProcessWithID(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1167 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00001168 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169
1170 if (log)
1171 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1172
1173 // Clear out and clean up from any current state
1174 Clear();
1175 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1176 error = EstablishConnectionIfNeeded(attach_info);
1177 if (error.Success()) {
1178 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1179
1180 char packet[64];
1181 const int packet_len =
1182 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1183 SetID(attach_pid);
1184 m_async_broadcaster.BroadcastEvent(
1185 eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1186 } else
1187 SetExitStatus(-1, error.AsCString());
1188 }
1189
1190 return error;
1191}
1192
Zachary Turner97206d52017-05-12 04:51:55 +00001193Status ProcessGDBRemote::DoAttachToProcessWithName(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194 const char *process_name, const ProcessAttachInfo &attach_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001195 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001196 // Clear out and clean up from any current state
1197 Clear();
1198
1199 if (process_name && process_name[0]) {
1200 error = EstablishConnectionIfNeeded(attach_info);
1201 if (error.Success()) {
1202 StreamString packet;
1203
1204 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1205
1206 if (attach_info.GetWaitForLaunch()) {
1207 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1208 packet.PutCString("vAttachWait");
1209 } else {
1210 if (attach_info.GetIgnoreExisting())
1211 packet.PutCString("vAttachWait");
1212 else
1213 packet.PutCString("vAttachOrWait");
1214 }
1215 } else
1216 packet.PutCString("vAttachName");
1217 packet.PutChar(';');
1218 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1219 endian::InlHostByteOrder(),
1220 endian::InlHostByteOrder());
1221
1222 m_async_broadcaster.BroadcastEvent(
1223 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001224 new EventDataBytes(packet.GetString().data(), packet.GetSize()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001225
1226 } else
1227 SetExitStatus(-1, error.AsCString());
1228 }
1229 return error;
1230}
1231
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001232lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options,
1233 Status &error) {
1234 return m_gdb_comm.SendStartTracePacket(options, error);
1235}
1236
1237Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
1238 return m_gdb_comm.SendStopTracePacket(uid, thread_id);
1239}
1240
1241Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
1242 llvm::MutableArrayRef<uint8_t> &buffer,
1243 size_t offset) {
1244 return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset);
1245}
1246
1247Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
1248 llvm::MutableArrayRef<uint8_t> &buffer,
1249 size_t offset) {
1250 return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset);
1251}
1252
1253Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid,
1254 TraceOptions &options) {
1255 return m_gdb_comm.SendGetTraceConfigPacket(uid, options);
1256}
1257
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258void ProcessGDBRemote::DidExit() {
1259 // When we exit, disconnect from the GDB server communications
1260 m_gdb_comm.Disconnect();
1261}
1262
1263void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1264 // If you can figure out what the architecture is, fill it in here.
1265 process_arch.Clear();
1266 DidLaunchOrAttach(process_arch);
1267}
1268
Zachary Turner97206d52017-05-12 04:51:55 +00001269Status ProcessGDBRemote::WillResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 m_continue_c_tids.clear();
1271 m_continue_C_tids.clear();
1272 m_continue_s_tids.clear();
1273 m_continue_S_tids.clear();
1274 m_jstopinfo_sp.reset();
1275 m_jthreadsinfo_sp.reset();
Zachary Turner97206d52017-05-12 04:51:55 +00001276 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001277}
1278
Zachary Turner97206d52017-05-12 04:51:55 +00001279Status ProcessGDBRemote::DoResume() {
1280 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001281 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1282 if (log)
1283 log->Printf("ProcessGDBRemote::Resume()");
1284
1285 ListenerSP listener_sp(
1286 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1287 if (listener_sp->StartListeningForEvents(
1288 &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
1289 listener_sp->StartListeningForEvents(
1290 &m_async_broadcaster,
1291 ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1292
1293 const size_t num_threads = GetThreadList().GetSize();
1294
1295 StreamString continue_packet;
1296 bool continue_packet_error = false;
1297 if (m_gdb_comm.HasAnyVContSupport()) {
1298 if (!GetTarget().GetNonStopModeEnabled() &&
1299 (m_continue_c_tids.size() == num_threads ||
1300 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1301 m_continue_s_tids.empty() && m_continue_S_tids.empty()))) {
1302 // All threads are continuing, just send a "c" packet
1303 continue_packet.PutCString("c");
1304 } else {
1305 continue_packet.PutCString("vCont");
1306
1307 if (!m_continue_c_tids.empty()) {
1308 if (m_gdb_comm.GetVContSupported('c')) {
1309 for (tid_collection::const_iterator
1310 t_pos = m_continue_c_tids.begin(),
1311 t_end = m_continue_c_tids.end();
1312 t_pos != t_end; ++t_pos)
1313 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1314 } else
1315 continue_packet_error = true;
1316 }
1317
1318 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1319 if (m_gdb_comm.GetVContSupported('C')) {
1320 for (tid_sig_collection::const_iterator
1321 s_pos = m_continue_C_tids.begin(),
1322 s_end = m_continue_C_tids.end();
1323 s_pos != s_end; ++s_pos)
1324 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
1325 s_pos->first);
1326 } else
1327 continue_packet_error = true;
1328 }
1329
1330 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1331 if (m_gdb_comm.GetVContSupported('s')) {
1332 for (tid_collection::const_iterator
1333 t_pos = m_continue_s_tids.begin(),
1334 t_end = m_continue_s_tids.end();
1335 t_pos != t_end; ++t_pos)
1336 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1337 } else
1338 continue_packet_error = true;
1339 }
1340
1341 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1342 if (m_gdb_comm.GetVContSupported('S')) {
1343 for (tid_sig_collection::const_iterator
1344 s_pos = m_continue_S_tids.begin(),
1345 s_end = m_continue_S_tids.end();
1346 s_pos != s_end; ++s_pos)
1347 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
1348 s_pos->first);
1349 } else
1350 continue_packet_error = true;
1351 }
1352
1353 if (continue_packet_error)
Zachary Turnerc1564272016-11-16 21:15:24 +00001354 continue_packet.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001355 }
1356 } else
1357 continue_packet_error = true;
1358
1359 if (continue_packet_error) {
Adrian Prantl05097242018-04-30 16:49:04 +00001360 // Either no vCont support, or we tried to use part of the vCont packet
1361 // that wasn't supported by the remote GDB server. We need to try and
1362 // make a simple packet that can do our continue
Kate Stoneb9c1b512016-09-06 20:57:50 +00001363 const size_t num_continue_c_tids = m_continue_c_tids.size();
1364 const size_t num_continue_C_tids = m_continue_C_tids.size();
1365 const size_t num_continue_s_tids = m_continue_s_tids.size();
1366 const size_t num_continue_S_tids = m_continue_S_tids.size();
1367 if (num_continue_c_tids > 0) {
1368 if (num_continue_c_tids == num_threads) {
1369 // All threads are resuming...
1370 m_gdb_comm.SetCurrentThreadForRun(-1);
1371 continue_packet.PutChar('c');
1372 continue_packet_error = false;
1373 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1374 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1375 // Only one thread is continuing
1376 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1377 continue_packet.PutChar('c');
1378 continue_packet_error = false;
1379 }
1380 }
1381
1382 if (continue_packet_error && num_continue_C_tids > 0) {
1383 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1384 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1385 num_continue_S_tids == 0) {
1386 const int continue_signo = m_continue_C_tids.front().second;
1387 // Only one thread is continuing
1388 if (num_continue_C_tids > 1) {
Adrian Prantl05097242018-04-30 16:49:04 +00001389 // More that one thread with a signal, yet we don't have vCont
1390 // support and we are being asked to resume each thread with a
1391 // signal, we need to make sure they are all the same signal, or we
1392 // can't issue the continue accurately with the current support...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001393 if (num_continue_C_tids > 1) {
1394 continue_packet_error = false;
1395 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1396 if (m_continue_C_tids[i].second != continue_signo)
1397 continue_packet_error = true;
1398 }
1399 }
1400 if (!continue_packet_error)
1401 m_gdb_comm.SetCurrentThreadForRun(-1);
1402 } else {
1403 // Set the continue thread ID
1404 continue_packet_error = false;
1405 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1406 }
1407 if (!continue_packet_error) {
1408 // Add threads continuing with the same signo...
1409 continue_packet.Printf("C%2.2x", continue_signo);
1410 }
1411 }
1412 }
1413
1414 if (continue_packet_error && num_continue_s_tids > 0) {
1415 if (num_continue_s_tids == num_threads) {
1416 // All threads are resuming...
1417 m_gdb_comm.SetCurrentThreadForRun(-1);
1418
1419 // If in Non-Stop-Mode use vCont when stepping
1420 if (GetTarget().GetNonStopModeEnabled()) {
1421 if (m_gdb_comm.GetVContSupported('s'))
1422 continue_packet.PutCString("vCont;s");
1423 else
1424 continue_packet.PutChar('s');
1425 } else
1426 continue_packet.PutChar('s');
1427
1428 continue_packet_error = false;
1429 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1430 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1431 // Only one thread is stepping
1432 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1433 continue_packet.PutChar('s');
1434 continue_packet_error = false;
1435 }
1436 }
1437
1438 if (!continue_packet_error && num_continue_S_tids > 0) {
1439 if (num_continue_S_tids == num_threads) {
1440 const int step_signo = m_continue_S_tids.front().second;
1441 // Are all threads trying to step with the same signal?
1442 continue_packet_error = false;
1443 if (num_continue_S_tids > 1) {
1444 for (size_t i = 1; i < num_threads; ++i) {
1445 if (m_continue_S_tids[i].second != step_signo)
1446 continue_packet_error = true;
1447 }
1448 }
1449 if (!continue_packet_error) {
1450 // Add threads stepping with the same signo...
1451 m_gdb_comm.SetCurrentThreadForRun(-1);
1452 continue_packet.Printf("S%2.2x", step_signo);
1453 }
1454 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1455 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1456 // Only one thread is stepping with signal
1457 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1458 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1459 continue_packet_error = false;
1460 }
1461 }
1462 }
1463
1464 if (continue_packet_error) {
1465 error.SetErrorString("can't make continue packet for this resume");
1466 } else {
1467 EventSP event_sp;
1468 if (!m_async_thread.IsJoinable()) {
1469 error.SetErrorString("Trying to resume but the async thread is dead.");
1470 if (log)
1471 log->Printf("ProcessGDBRemote::DoResume: Trying to resume but the "
1472 "async thread is dead.");
1473 return error;
1474 }
1475
1476 m_async_broadcaster.BroadcastEvent(
1477 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001478 new EventDataBytes(continue_packet.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001479 continue_packet.GetSize()));
1480
Pavel Labathd35031e12016-11-30 10:41:42 +00001481 if (listener_sp->GetEvent(event_sp, std::chrono::seconds(5)) == false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001482 error.SetErrorString("Resume timed out.");
1483 if (log)
1484 log->Printf("ProcessGDBRemote::DoResume: Resume timed out.");
1485 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1486 error.SetErrorString("Broadcast continue, but the async thread was "
1487 "killed before we got an ack back.");
1488 if (log)
1489 log->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
1490 "async thread was killed before we got an ack back.");
1491 return error;
1492 }
1493 }
1494 }
1495
1496 return error;
1497}
1498
1499void ProcessGDBRemote::HandleStopReplySequence() {
1500 while (true) {
1501 // Send vStopped
1502 StringExtractorGDBRemote response;
1503 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1504
1505 // OK represents end of signal list
1506 if (response.IsOKResponse())
1507 break;
1508
1509 // If not OK or a normal packet we have a problem
1510 if (!response.IsNormalResponse())
1511 break;
1512
1513 SetLastStopPacket(response);
1514 }
1515}
1516
1517void ProcessGDBRemote::ClearThreadIDList() {
1518 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1519 m_thread_ids.clear();
1520 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00001521}
1522
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001523size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001524ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
1525 m_thread_ids.clear();
1526 m_thread_pcs.clear();
1527 size_t comma_pos;
1528 lldb::tid_t tid;
1529 while ((comma_pos = value.find(',')) != std::string::npos) {
1530 value[comma_pos] = '\0';
1531 // thread in big endian hex
1532 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001533 if (tid != LLDB_INVALID_THREAD_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001534 m_thread_ids.push_back(tid);
1535 value.erase(0, comma_pos + 1);
1536 }
1537 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1538 if (tid != LLDB_INVALID_THREAD_ID)
1539 m_thread_ids.push_back(tid);
1540 return m_thread_ids.size();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001541}
1542
Jason Molenda545304d2015-12-18 00:45:35 +00001543size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001544ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
1545 m_thread_pcs.clear();
1546 size_t comma_pos;
1547 lldb::addr_t pc;
1548 while ((comma_pos = value.find(',')) != std::string::npos) {
1549 value[comma_pos] = '\0';
1550 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1551 if (pc != LLDB_INVALID_ADDRESS)
1552 m_thread_pcs.push_back(pc);
1553 value.erase(0, comma_pos + 1);
1554 }
1555 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1556 if (pc != LLDB_INVALID_THREAD_ID)
1557 m_thread_pcs.push_back(pc);
1558 return m_thread_pcs.size();
Jason Molenda545304d2015-12-18 00:45:35 +00001559}
1560
Kate Stoneb9c1b512016-09-06 20:57:50 +00001561bool ProcessGDBRemote::UpdateThreadIDList() {
1562 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001563
Kate Stoneb9c1b512016-09-06 20:57:50 +00001564 if (m_jthreadsinfo_sp) {
1565 // If we have the JSON threads info, we can get the thread list from that
1566 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1567 if (thread_infos && thread_infos->GetSize() > 0) {
1568 m_thread_ids.clear();
1569 m_thread_pcs.clear();
1570 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1571 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1572 if (thread_dict) {
1573 // Set the thread stop info from the JSON dictionary
1574 SetThreadStopInfo(thread_dict);
1575 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1576 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1577 m_thread_ids.push_back(tid);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001578 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001579 return true; // Keep iterating through all thread_info objects
1580 });
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001582 if (!m_thread_ids.empty())
1583 return true;
1584 } else {
1585 // See if we can get the thread IDs from the current stop reply packets
1586 // that might contain a "threads" key/value pair
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001587
Kate Stoneb9c1b512016-09-06 20:57:50 +00001588 // Lock the thread stack while we access it
1589 // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1590 std::unique_lock<std::recursive_mutex> stop_stack_lock(
1591 m_last_stop_packet_mutex, std::defer_lock);
1592 if (stop_stack_lock.try_lock()) {
1593 // Get the number of stop packets on the stack
1594 int nItems = m_stop_packet_stack.size();
1595 // Iterate over them
1596 for (int i = 0; i < nItems; i++) {
1597 // Get the thread stop info
1598 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1599 const std::string &stop_info_str = stop_info.GetStringRef();
Jason Molenda545304d2015-12-18 00:45:35 +00001600
Kate Stoneb9c1b512016-09-06 20:57:50 +00001601 m_thread_pcs.clear();
1602 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1603 if (thread_pcs_pos != std::string::npos) {
1604 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1605 const size_t end = stop_info_str.find(';', start);
1606 if (end != std::string::npos) {
1607 std::string value = stop_info_str.substr(start, end - start);
1608 UpdateThreadPCsFromStopReplyThreadsValue(value);
1609 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001610 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001611
Kate Stoneb9c1b512016-09-06 20:57:50 +00001612 const size_t threads_pos = stop_info_str.find(";threads:");
1613 if (threads_pos != std::string::npos) {
1614 const size_t start = threads_pos + strlen(";threads:");
1615 const size_t end = stop_info_str.find(';', start);
1616 if (end != std::string::npos) {
1617 std::string value = stop_info_str.substr(start, end - start);
1618 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1619 return true;
1620 }
1621 }
1622 }
1623 }
1624 }
1625
1626 bool sequence_mutex_unavailable = false;
1627 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1628 if (sequence_mutex_unavailable) {
1629 return false; // We just didn't get the list
1630 }
1631 return true;
1632}
1633
1634bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
1635 ThreadList &new_thread_list) {
1636 // locker will keep a mutex locked until it goes out of scope
1637 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
Pavel Labathe8a7b982017-02-06 19:31:09 +00001638 LLDB_LOGV(log, "pid = {0}", GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001639
1640 size_t num_thread_ids = m_thread_ids.size();
1641 // The "m_thread_ids" thread ID list should always be updated after each stop
1642 // reply packet, but in case it isn't, update it here.
1643 if (num_thread_ids == 0) {
1644 if (!UpdateThreadIDList())
1645 return false;
1646 num_thread_ids = m_thread_ids.size();
1647 }
1648
1649 ThreadList old_thread_list_copy(old_thread_list);
1650 if (num_thread_ids > 0) {
1651 for (size_t i = 0; i < num_thread_ids; ++i) {
1652 tid_t tid = m_thread_ids[i];
1653 ThreadSP thread_sp(
1654 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1655 if (!thread_sp) {
1656 thread_sp.reset(new ThreadGDBRemote(*this, tid));
Pavel Labathe8a7b982017-02-06 19:31:09 +00001657 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1658 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001659 } else {
Pavel Labathe8a7b982017-02-06 19:31:09 +00001660 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1661 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662 }
Pavel Labathe0a5b572017-01-20 14:17:16 +00001663
1664 SetThreadPc(thread_sp, i);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1666 }
1667 }
1668
Adrian Prantl05097242018-04-30 16:49:04 +00001669 // Whatever that is left in old_thread_list_copy are not present in
1670 // new_thread_list. Remove non-existent threads from internal id table.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1672 for (size_t i = 0; i < old_num_thread_ids; i++) {
1673 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1674 if (old_thread_sp) {
1675 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1676 m_thread_id_to_index_id_map.erase(old_thread_id);
1677 }
1678 }
1679
1680 return true;
1681}
1682
Pavel Labathe0a5b572017-01-20 14:17:16 +00001683void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1684 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1685 GetByteOrder() != eByteOrderInvalid) {
1686 ThreadGDBRemote *gdb_thread =
1687 static_cast<ThreadGDBRemote *>(thread_sp.get());
1688 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1689 if (reg_ctx_sp) {
1690 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1691 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1692 if (pc_regnum != LLDB_INVALID_REGNUM) {
1693 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1694 }
1695 }
1696 }
1697}
1698
Kate Stoneb9c1b512016-09-06 20:57:50 +00001699bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1700 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1701 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1702 // packet
1703 if (thread_infos_sp) {
1704 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1705 if (thread_infos) {
1706 lldb::tid_t tid;
1707 const size_t n = thread_infos->GetSize();
1708 for (size_t i = 0; i < n; ++i) {
1709 StructuredData::Dictionary *thread_dict =
1710 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1711 if (thread_dict) {
1712 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1713 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1714 if (tid == thread->GetID())
1715 return (bool)SetThreadStopInfo(thread_dict);
1716 }
1717 }
1718 }
1719 }
1720 }
1721 return false;
1722}
1723
1724bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1725 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1726 // packet
1727 if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1728 return true;
1729
1730 // See if we got thread stop info for any threads valid stop info reasons
Adrian Prantl05097242018-04-30 16:49:04 +00001731 // threads via the "jstopinfo" packet stop reply packet key/value pair?
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732 if (m_jstopinfo_sp) {
1733 // If we have "jstopinfo" then we have stop descriptions for all threads
Adrian Prantl05097242018-04-30 16:49:04 +00001734 // that have stop reasons, and if there is no entry for a thread, then it
1735 // has no stop reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001736 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1737 if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1738 thread->SetStopInfo(StopInfoSP());
Greg Clayton9e920902012-04-10 02:25:43 +00001739 }
1740 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001741 }
1742
1743 // Fall back to using the qThreadStopInfo packet
1744 StringExtractorGDBRemote stop_packet;
1745 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1746 return SetThreadStopInfo(stop_packet) == eStateStopped;
1747 return false;
Greg Clayton9e920902012-04-10 02:25:43 +00001748}
1749
Kate Stoneb9c1b512016-09-06 20:57:50 +00001750ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1751 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1752 uint8_t signo, const std::string &thread_name, const std::string &reason,
1753 const std::string &description, uint32_t exc_type,
1754 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1755 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1756 // queue_serial are valid
1757 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1758 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1759 ThreadSP thread_sp;
1760 if (tid != LLDB_INVALID_THREAD_ID) {
1761 // Scope for "locker" below
Greg Clayton9e920902012-04-10 02:25:43 +00001762 {
Adrian Prantl05097242018-04-30 16:49:04 +00001763 // m_thread_list_real does have its own mutex, but we need to hold onto
1764 // the mutex between the call to m_thread_list_real.FindThreadByID(...)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1766 std::lock_guard<std::recursive_mutex> guard(
1767 m_thread_list_real.GetMutex());
1768 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1769
1770 if (!thread_sp) {
1771 // Create the thread if we need to
1772 thread_sp.reset(new ThreadGDBRemote(*this, tid));
1773 m_thread_list_real.AddThread(thread_sp);
1774 }
Greg Clayton9e920902012-04-10 02:25:43 +00001775 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001776
Kate Stoneb9c1b512016-09-06 20:57:50 +00001777 if (thread_sp) {
1778 ThreadGDBRemote *gdb_thread =
1779 static_cast<ThreadGDBRemote *>(thread_sp.get());
1780 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1781
Pavel Labathe0a5b572017-01-20 14:17:16 +00001782 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1783 if (iter != m_thread_ids.end()) {
1784 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1785 }
1786
Kate Stoneb9c1b512016-09-06 20:57:50 +00001787 for (const auto &pair : expedited_register_map) {
1788 StringExtractor reg_value_extractor;
1789 reg_value_extractor.GetStringRef() = pair.second;
1790 DataBufferSP buffer_sp(new DataBufferHeap(
1791 reg_value_extractor.GetStringRef().size() / 2, 0));
1792 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1793 gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
1794 }
1795
1796 thread_sp->SetName(thread_name.empty() ? NULL : thread_name.c_str());
1797
1798 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1799 // Check if the GDB server was able to provide the queue name, kind and
1800 // serial number
1801 if (queue_vars_valid)
1802 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1803 queue_serial, dispatch_queue_t,
1804 associated_with_dispatch_queue);
1805 else
1806 gdb_thread->ClearQueueInfo();
1807
1808 gdb_thread->SetAssociatedWithLibdispatchQueue(
1809 associated_with_dispatch_queue);
1810
1811 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1812 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1813
1814 // Make sure we update our thread stop reason just once
1815 if (!thread_sp->StopInfoIsUpToDate()) {
1816 thread_sp->SetStopInfo(StopInfoSP());
1817 // If there's a memory thread backed by this thread, we need to use it
Jonas Devlieghere8db3f7e2018-04-13 11:31:34 +00001818 // to calculate StopInfo.
1819 if (ThreadSP memory_thread_sp =
1820 m_thread_list.GetBackingThread(thread_sp))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001821 thread_sp = memory_thread_sp;
1822
1823 if (exc_type != 0) {
1824 const size_t exc_data_size = exc_data.size();
1825
1826 thread_sp->SetStopInfo(
1827 StopInfoMachException::CreateStopReasonWithMachException(
1828 *thread_sp, exc_type, exc_data_size,
1829 exc_data_size >= 1 ? exc_data[0] : 0,
1830 exc_data_size >= 2 ? exc_data[1] : 0,
1831 exc_data_size >= 3 ? exc_data[2] : 0));
1832 } else {
1833 bool handled = false;
1834 bool did_exec = false;
1835 if (!reason.empty()) {
1836 if (reason.compare("trace") == 0) {
1837 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1838 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1839 ->GetBreakpointSiteList()
1840 .FindByAddress(pc);
1841
Adrian Prantl05097242018-04-30 16:49:04 +00001842 // If the current pc is a breakpoint site then the StopInfo
1843 // should be set to Breakpoint Otherwise, it will be set to
1844 // Trace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001845 if (bp_site_sp &&
1846 bp_site_sp->ValidForThisThread(thread_sp.get())) {
1847 thread_sp->SetStopInfo(
1848 StopInfo::CreateStopReasonWithBreakpointSiteID(
1849 *thread_sp, bp_site_sp->GetID()));
1850 } else
1851 thread_sp->SetStopInfo(
1852 StopInfo::CreateStopReasonToTrace(*thread_sp));
1853 handled = true;
1854 } else if (reason.compare("breakpoint") == 0) {
1855 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1856 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1857 ->GetBreakpointSiteList()
1858 .FindByAddress(pc);
1859 if (bp_site_sp) {
1860 // If the breakpoint is for this thread, then we'll report the
Adrian Prantl05097242018-04-30 16:49:04 +00001861 // hit, but if it is for another thread, we can just report no
1862 // reason. We don't need to worry about stepping over the
1863 // breakpoint here, that will be taken care of when the thread
1864 // resumes and notices that there's a breakpoint under the pc.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001865 handled = true;
1866 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1867 thread_sp->SetStopInfo(
1868 StopInfo::CreateStopReasonWithBreakpointSiteID(
1869 *thread_sp, bp_site_sp->GetID()));
1870 } else {
1871 StopInfoSP invalid_stop_info_sp;
1872 thread_sp->SetStopInfo(invalid_stop_info_sp);
Jason Molenda545304d2015-12-18 00:45:35 +00001873 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001874 }
1875 } else if (reason.compare("trap") == 0) {
1876 // Let the trap just use the standard signal stop reason below...
1877 } else if (reason.compare("watchpoint") == 0) {
1878 StringExtractor desc_extractor(description.c_str());
1879 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1880 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1881 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1882 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1883 if (wp_addr != LLDB_INVALID_ADDRESS) {
1884 WatchpointSP wp_sp;
1885 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1886 if ((core >= ArchSpec::kCore_mips_first &&
1887 core <= ArchSpec::kCore_mips_last) ||
1888 (core >= ArchSpec::eCore_arm_generic &&
1889 core <= ArchSpec::eCore_arm_aarch64))
1890 wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1891 wp_hit_addr);
1892 if (!wp_sp)
1893 wp_sp =
1894 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1895 if (wp_sp) {
1896 wp_sp->SetHardwareIndex(wp_index);
1897 watch_id = wp_sp->GetID();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001898 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001899 }
1900 if (watch_id == LLDB_INVALID_WATCH_ID) {
1901 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1902 GDBR_LOG_WATCHPOINTS));
1903 if (log)
1904 log->Printf("failed to find watchpoint");
1905 }
1906 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1907 *thread_sp, watch_id, wp_hit_addr));
1908 handled = true;
1909 } else if (reason.compare("exception") == 0) {
1910 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1911 *thread_sp, description.c_str()));
1912 handled = true;
1913 } else if (reason.compare("exec") == 0) {
1914 did_exec = true;
1915 thread_sp->SetStopInfo(
1916 StopInfo::CreateStopReasonWithExec(*thread_sp));
1917 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001918 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001919 } else if (!signo) {
1920 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1921 lldb::BreakpointSiteSP bp_site_sp =
1922 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1923 pc);
Greg Clayton2e309072015-07-17 23:42:28 +00001924
Kate Stoneb9c1b512016-09-06 20:57:50 +00001925 // If the current pc is a breakpoint site then the StopInfo should
Adrian Prantl05097242018-04-30 16:49:04 +00001926 // be set to Breakpoint even though the remote stub did not set it
1927 // as such. This can happen when the thread is involuntarily
1928 // interrupted (e.g. due to stops on other threads) just as it is
1929 // about to execute the breakpoint instruction.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001930 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
1931 thread_sp->SetStopInfo(
1932 StopInfo::CreateStopReasonWithBreakpointSiteID(
1933 *thread_sp, bp_site_sp->GetID()));
1934 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001935 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001936 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001937
Kate Stoneb9c1b512016-09-06 20:57:50 +00001938 if (!handled && signo && did_exec == false) {
1939 if (signo == SIGTRAP) {
1940 // Currently we are going to assume SIGTRAP means we are either
1941 // hitting a breakpoint or hardware single stepping.
1942 handled = true;
1943 addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1944 m_breakpoint_pc_offset;
1945 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1946 ->GetBreakpointSiteList()
1947 .FindByAddress(pc);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001948
Kate Stoneb9c1b512016-09-06 20:57:50 +00001949 if (bp_site_sp) {
1950 // If the breakpoint is for this thread, then we'll report the
Adrian Prantl05097242018-04-30 16:49:04 +00001951 // hit, but if it is for another thread, we can just report no
1952 // reason. We don't need to worry about stepping over the
1953 // breakpoint here, that will be taken care of when the thread
1954 // resumes and notices that there's a breakpoint under the pc.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1956 if (m_breakpoint_pc_offset != 0)
1957 thread_sp->GetRegisterContext()->SetPC(pc);
1958 thread_sp->SetStopInfo(
1959 StopInfo::CreateStopReasonWithBreakpointSiteID(
1960 *thread_sp, bp_site_sp->GetID()));
1961 } else {
1962 StopInfoSP invalid_stop_info_sp;
1963 thread_sp->SetStopInfo(invalid_stop_info_sp);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001964 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001965 } else {
1966 // If we were stepping then assume the stop was the result of
Adrian Prantl05097242018-04-30 16:49:04 +00001967 // the trace. If we were not stepping then report the SIGTRAP.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001968 // FIXME: We are still missing the case where we single step
1969 // over a trap instruction.
1970 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1971 thread_sp->SetStopInfo(
1972 StopInfo::CreateStopReasonToTrace(*thread_sp));
Greg Clayton2e309072015-07-17 23:42:28 +00001973 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001974 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1975 *thread_sp, signo, description.c_str()));
1976 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001977 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001978 if (!handled)
1979 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1980 *thread_sp, signo, description.c_str()));
1981 }
1982
1983 if (!description.empty()) {
1984 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1985 if (stop_info_sp) {
1986 const char *stop_info_desc = stop_info_sp->GetDescription();
1987 if (!stop_info_desc || !stop_info_desc[0])
1988 stop_info_sp->SetDescription(description.c_str());
1989 } else {
1990 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1991 *thread_sp, description.c_str()));
1992 }
1993 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001994 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001995 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001996 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001997 }
1998 return thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001999}
2000
Greg Clayton2e309072015-07-17 23:42:28 +00002001lldb::ThreadSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00002002ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
2003 static ConstString g_key_tid("tid");
2004 static ConstString g_key_name("name");
2005 static ConstString g_key_reason("reason");
2006 static ConstString g_key_metype("metype");
2007 static ConstString g_key_medata("medata");
2008 static ConstString g_key_qaddr("qaddr");
2009 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2010 static ConstString g_key_associated_with_dispatch_queue(
2011 "associated_with_dispatch_queue");
2012 static ConstString g_key_queue_name("qname");
2013 static ConstString g_key_queue_kind("qkind");
2014 static ConstString g_key_queue_serial_number("qserialnum");
2015 static ConstString g_key_registers("registers");
2016 static ConstString g_key_memory("memory");
2017 static ConstString g_key_address("address");
2018 static ConstString g_key_bytes("bytes");
2019 static ConstString g_key_description("description");
2020 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002021
Kate Stoneb9c1b512016-09-06 20:57:50 +00002022 // Stop with signal and thread info
2023 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2024 uint8_t signo = 0;
2025 std::string value;
2026 std::string thread_name;
2027 std::string reason;
2028 std::string description;
2029 uint32_t exc_type = 0;
2030 std::vector<addr_t> exc_data;
2031 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2032 ExpeditedRegisterMap expedited_register_map;
2033 bool queue_vars_valid = false;
2034 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2035 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2036 std::string queue_name;
2037 QueueKind queue_kind = eQueueKindUnknown;
2038 uint64_t queue_serial_number = 0;
2039 // Iterate through all of the thread dictionary key/value pairs from the
2040 // structured data dictionary
2041
2042 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2043 &signo, &reason, &description, &exc_type, &exc_data,
2044 &thread_dispatch_qaddr, &queue_vars_valid,
2045 &associated_with_dispatch_queue, &dispatch_queue_t,
2046 &queue_name, &queue_kind, &queue_serial_number](
2047 ConstString key,
2048 StructuredData::Object *object) -> bool {
2049 if (key == g_key_tid) {
2050 // thread in big endian hex
2051 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2052 } else if (key == g_key_metype) {
2053 // exception type in big endian hex
2054 exc_type = object->GetIntegerValue(0);
2055 } else if (key == g_key_medata) {
2056 // exception data in big endian hex
2057 StructuredData::Array *array = object->GetAsArray();
2058 if (array) {
2059 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2060 exc_data.push_back(object->GetIntegerValue());
2061 return true; // Keep iterating through all array items
2062 });
2063 }
2064 } else if (key == g_key_name) {
2065 thread_name = object->GetStringValue();
2066 } else if (key == g_key_qaddr) {
2067 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2068 } else if (key == g_key_queue_name) {
2069 queue_vars_valid = true;
2070 queue_name = object->GetStringValue();
2071 } else if (key == g_key_queue_kind) {
2072 std::string queue_kind_str = object->GetStringValue();
2073 if (queue_kind_str == "serial") {
2074 queue_vars_valid = true;
2075 queue_kind = eQueueKindSerial;
2076 } else if (queue_kind_str == "concurrent") {
2077 queue_vars_valid = true;
2078 queue_kind = eQueueKindConcurrent;
2079 }
2080 } else if (key == g_key_queue_serial_number) {
2081 queue_serial_number = object->GetIntegerValue(0);
2082 if (queue_serial_number != 0)
2083 queue_vars_valid = true;
2084 } else if (key == g_key_dispatch_queue_t) {
2085 dispatch_queue_t = object->GetIntegerValue(0);
2086 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2087 queue_vars_valid = true;
2088 } else if (key == g_key_associated_with_dispatch_queue) {
2089 queue_vars_valid = true;
2090 bool associated = object->GetBooleanValue();
2091 if (associated)
2092 associated_with_dispatch_queue = eLazyBoolYes;
2093 else
2094 associated_with_dispatch_queue = eLazyBoolNo;
2095 } else if (key == g_key_reason) {
2096 reason = object->GetStringValue();
2097 } else if (key == g_key_description) {
2098 description = object->GetStringValue();
2099 } else if (key == g_key_registers) {
2100 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2101
2102 if (registers_dict) {
2103 registers_dict->ForEach(
2104 [&expedited_register_map](ConstString key,
2105 StructuredData::Object *object) -> bool {
2106 const uint32_t reg =
2107 StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
2108 if (reg != UINT32_MAX)
2109 expedited_register_map[reg] = object->GetStringValue();
2110 return true; // Keep iterating through all array items
2111 });
2112 }
2113 } else if (key == g_key_memory) {
2114 StructuredData::Array *array = object->GetAsArray();
2115 if (array) {
2116 array->ForEach([this](StructuredData::Object *object) -> bool {
2117 StructuredData::Dictionary *mem_cache_dict =
2118 object->GetAsDictionary();
2119 if (mem_cache_dict) {
2120 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2121 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2122 "address", mem_cache_addr)) {
2123 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
Zachary Turner28333212017-05-12 05:49:54 +00002124 llvm::StringRef str;
2125 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2126 StringExtractor bytes(str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002127 bytes.SetFilePos(0);
2128
2129 const size_t byte_size = bytes.GetStringRef().size() / 2;
2130 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2131 const size_t bytes_copied =
2132 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2133 if (bytes_copied == byte_size)
2134 m_memory_cache.AddL1CacheData(mem_cache_addr,
2135 data_buffer_sp);
2136 }
2137 }
2138 }
2139 }
2140 return true; // Keep iterating through all array items
2141 });
2142 }
2143
2144 } else if (key == g_key_signal)
2145 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2146 return true; // Keep iterating through all dictionary key/value pairs
2147 });
2148
2149 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2150 reason, description, exc_type, exc_data,
2151 thread_dispatch_qaddr, queue_vars_valid,
2152 associated_with_dispatch_queue, dispatch_queue_t,
2153 queue_name, queue_kind, queue_serial_number);
2154}
2155
2156StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2157 stop_packet.SetFilePos(0);
2158 const char stop_type = stop_packet.GetChar();
2159 switch (stop_type) {
2160 case 'T':
2161 case 'S': {
Adrian Prantl05097242018-04-30 16:49:04 +00002162 // This is a bit of a hack, but is is required. If we did exec, we need to
2163 // clear our thread lists and also know to rebuild our dynamic register
2164 // info before we lookup and threads and populate the expedited register
2165 // values so we need to know this right away so we can cleanup and update
2166 // our registers.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167 const uint32_t stop_id = GetStopID();
2168 if (stop_id == 0) {
Adrian Prantl05097242018-04-30 16:49:04 +00002169 // Our first stop, make sure we have a process ID, and also make sure we
2170 // know about our registers
Kate Stoneb9c1b512016-09-06 20:57:50 +00002171 if (GetID() == LLDB_INVALID_PROCESS_ID) {
2172 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2173 if (pid != LLDB_INVALID_PROCESS_ID)
2174 SetID(pid);
2175 }
2176 BuildDynamicRegisterInfo(true);
2177 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002178 // Stop with signal and thread info
2179 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002180 const uint8_t signo = stop_packet.GetHexU8();
2181 llvm::StringRef key;
2182 llvm::StringRef value;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002183 std::string thread_name;
2184 std::string reason;
2185 std::string description;
2186 uint32_t exc_type = 0;
2187 std::vector<addr_t> exc_data;
2188 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189 bool queue_vars_valid =
2190 false; // says if locals below that start with "queue_" are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002191 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2192 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002193 std::string queue_name;
2194 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002195 uint64_t queue_serial_number = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002196 ExpeditedRegisterMap expedited_register_map;
2197 while (stop_packet.GetNameColonValue(key, value)) {
2198 if (key.compare("metype") == 0) {
2199 // exception type in big endian hex
2200 value.getAsInteger(16, exc_type);
2201 } else if (key.compare("medata") == 0) {
2202 // exception data in big endian hex
2203 uint64_t x;
2204 value.getAsInteger(16, x);
2205 exc_data.push_back(x);
2206 } else if (key.compare("thread") == 0) {
2207 // thread in big endian hex
2208 if (value.getAsInteger(16, tid))
2209 tid = LLDB_INVALID_THREAD_ID;
2210 } else if (key.compare("threads") == 0) {
2211 std::lock_guard<std::recursive_mutex> guard(
2212 m_thread_list_real.GetMutex());
Greg Clayton358cf1e2015-06-25 21:46:34 +00002213
Kate Stoneb9c1b512016-09-06 20:57:50 +00002214 m_thread_ids.clear();
2215 // A comma separated list of all threads in the current
Adrian Prantl05097242018-04-30 16:49:04 +00002216 // process that includes the thread for this stop reply packet
Kate Stoneb9c1b512016-09-06 20:57:50 +00002217 lldb::tid_t tid;
2218 while (!value.empty()) {
2219 llvm::StringRef tid_str;
2220 std::tie(tid_str, value) = value.split(',');
2221 if (tid_str.getAsInteger(16, tid))
2222 tid = LLDB_INVALID_THREAD_ID;
2223 m_thread_ids.push_back(tid);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002224 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002225 } else if (key.compare("thread-pcs") == 0) {
2226 m_thread_pcs.clear();
2227 // A comma separated list of all threads in the current
Adrian Prantl05097242018-04-30 16:49:04 +00002228 // process that includes the thread for this stop reply packet
Kate Stoneb9c1b512016-09-06 20:57:50 +00002229 lldb::addr_t pc;
2230 while (!value.empty()) {
2231 llvm::StringRef pc_str;
2232 std::tie(pc_str, value) = value.split(',');
2233 if (pc_str.getAsInteger(16, pc))
2234 pc = LLDB_INVALID_ADDRESS;
2235 m_thread_pcs.push_back(pc);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002236 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002237 } else if (key.compare("jstopinfo") == 0) {
2238 StringExtractor json_extractor(value);
2239 std::string json;
2240 // Now convert the HEX bytes into a string value
2241 json_extractor.GetHexByteString(json);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002242
Kate Stoneb9c1b512016-09-06 20:57:50 +00002243 // This JSON contains thread IDs and thread stop info for all threads.
2244 // It doesn't contain expedited registers, memory or queue info.
2245 m_jstopinfo_sp = StructuredData::ParseJSON(json);
2246 } else if (key.compare("hexname") == 0) {
2247 StringExtractor name_extractor(value);
2248 std::string name;
2249 // Now convert the HEX bytes into a string value
2250 name_extractor.GetHexByteString(thread_name);
2251 } else if (key.compare("name") == 0) {
2252 thread_name = value;
2253 } else if (key.compare("qaddr") == 0) {
2254 value.getAsInteger(16, thread_dispatch_qaddr);
2255 } else if (key.compare("dispatch_queue_t") == 0) {
2256 queue_vars_valid = true;
2257 value.getAsInteger(16, dispatch_queue_t);
2258 } else if (key.compare("qname") == 0) {
2259 queue_vars_valid = true;
2260 StringExtractor name_extractor(value);
2261 // Now convert the HEX bytes into a string value
2262 name_extractor.GetHexByteString(queue_name);
2263 } else if (key.compare("qkind") == 0) {
2264 queue_kind = llvm::StringSwitch<QueueKind>(value)
2265 .Case("serial", eQueueKindSerial)
2266 .Case("concurrent", eQueueKindConcurrent)
2267 .Default(eQueueKindUnknown);
2268 queue_vars_valid = queue_kind != eQueueKindUnknown;
2269 } else if (key.compare("qserialnum") == 0) {
2270 if (!value.getAsInteger(0, queue_serial_number))
2271 queue_vars_valid = true;
2272 } else if (key.compare("reason") == 0) {
2273 reason = value;
2274 } else if (key.compare("description") == 0) {
2275 StringExtractor desc_extractor(value);
2276 // Now convert the HEX bytes into a string value
2277 desc_extractor.GetHexByteString(description);
2278 } else if (key.compare("memory") == 0) {
2279 // Expedited memory. GDB servers can choose to send back expedited
Adrian Prantl05097242018-04-30 16:49:04 +00002280 // memory that can populate the L1 memory cache in the process so that
2281 // things like the frame pointer backchain can be expedited. This will
2282 // help stack backtracing be more efficient by not having to send as
2283 // many memory read requests down the remote GDB server.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002284
2285 // Key/value pair format: memory:<addr>=<bytes>;
2286 // <addr> is a number whose base will be interpreted by the prefix:
2287 // "0x[0-9a-fA-F]+" for hex
2288 // "0[0-7]+" for octal
2289 // "[1-9]+" for decimal
2290 // <bytes> is native endian ASCII hex bytes just like the register
2291 // values
2292 llvm::StringRef addr_str, bytes_str;
2293 std::tie(addr_str, bytes_str) = value.split('=');
2294 if (!addr_str.empty() && !bytes_str.empty()) {
2295 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2296 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2297 StringExtractor bytes(bytes_str);
2298 const size_t byte_size = bytes.GetBytesLeft() / 2;
2299 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2300 const size_t bytes_copied =
2301 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2302 if (bytes_copied == byte_size)
2303 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2304 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002305 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002306 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2307 key.compare("awatch") == 0) {
2308 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2309 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2310 value.getAsInteger(16, wp_addr);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002311
Kate Stoneb9c1b512016-09-06 20:57:50 +00002312 WatchpointSP wp_sp =
2313 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2314 uint32_t wp_index = LLDB_INVALID_INDEX32;
Eugene Zelenko0722f082015-10-24 01:28:05 +00002315
Kate Stoneb9c1b512016-09-06 20:57:50 +00002316 if (wp_sp)
2317 wp_index = wp_sp->GetHardwareIndex();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002318
Kate Stoneb9c1b512016-09-06 20:57:50 +00002319 reason = "watchpoint";
2320 StreamString ostr;
2321 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002322 description = ostr.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002323 } else if (key.compare("library") == 0) {
2324 LoadModules();
2325 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2326 uint32_t reg = UINT32_MAX;
2327 if (!key.getAsInteger(16, reg))
2328 expedited_register_map[reg] = std::move(value);
2329 }
2330 }
2331
2332 if (tid == LLDB_INVALID_THREAD_ID) {
2333 // A thread id may be invalid if the response is old style 'S' packet
2334 // which does not provide the
Adrian Prantl05097242018-04-30 16:49:04 +00002335 // thread information. So update the thread list and choose the first
2336 // one.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002337 UpdateThreadIDList();
2338
2339 if (!m_thread_ids.empty()) {
2340 tid = m_thread_ids.front();
2341 }
2342 }
2343
2344 ThreadSP thread_sp = SetThreadStopInfo(
2345 tid, expedited_register_map, signo, thread_name, reason, description,
2346 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2347 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2348 queue_kind, queue_serial_number);
2349
2350 return eStateStopped;
2351 } break;
2352
2353 case 'W':
2354 case 'X':
2355 // process exited
2356 return eStateExited;
2357
2358 default:
2359 break;
2360 }
2361 return eStateInvalid;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002362}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002363
Kate Stoneb9c1b512016-09-06 20:57:50 +00002364void ProcessGDBRemote::RefreshStateAfterStop() {
2365 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002366
Kate Stoneb9c1b512016-09-06 20:57:50 +00002367 m_thread_ids.clear();
2368 m_thread_pcs.clear();
Adrian Prantl05097242018-04-30 16:49:04 +00002369 // Set the thread stop info. It might have a "threads" key whose value is a
2370 // list of all thread IDs in the current process, so m_thread_ids might get
2371 // set.
Greg Claytona5801ad2015-07-15 22:59:03 +00002372
Kate Stoneb9c1b512016-09-06 20:57:50 +00002373 // Scope for the lock
2374 {
2375 // Lock the thread stack while we access it
2376 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2377 // Get the number of stop packets on the stack
2378 int nItems = m_stop_packet_stack.size();
2379 // Iterate over them
2380 for (int i = 0; i < nItems; i++) {
2381 // Get the thread stop info
2382 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2383 // Process thread stop info
2384 SetThreadStopInfo(stop_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002385 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002386 // Clear the thread stop stack
2387 m_stop_packet_stack.clear();
2388 }
2389
2390 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2391 if (m_thread_ids.empty()) {
2392 // No, we need to fetch the thread list manually
2393 UpdateThreadIDList();
2394 }
2395
2396 // If we have queried for a default thread id
2397 if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2398 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2399 m_initial_tid = LLDB_INVALID_THREAD_ID;
2400 }
2401
Adrian Prantl05097242018-04-30 16:49:04 +00002402 // Let all threads recover from stopping and do any clean up based on the
2403 // previous thread state (if any).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002404 m_thread_list_real.RefreshStateAfterStop();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002405}
2406
Zachary Turner97206d52017-05-12 04:51:55 +00002407Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2408 Status error;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002409
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00002411 // We are being asked to halt during an attach. We need to just close our
2412 // file handle and debugserver will go away, and we can be done...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002413 m_gdb_comm.Disconnect();
2414 } else
2415 caused_stop = m_gdb_comm.Interrupt();
2416 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002417}
2418
Zachary Turner97206d52017-05-12 04:51:55 +00002419Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2420 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002421 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2422 if (log)
2423 log->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002424
Kate Stoneb9c1b512016-09-06 20:57:50 +00002425 error = m_gdb_comm.Detach(keep_stopped);
2426 if (log) {
2427 if (error.Success())
2428 log->PutCString(
2429 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
Greg Clayton513c26c2011-01-29 07:10:55 +00002430 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002431 log->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2432 error.AsCString() ? error.AsCString() : "<unknown error>");
2433 }
2434
2435 if (!error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002436 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002437
2438 // Sleep for one second to let the process get all detached...
2439 StopAsyncThread();
2440
2441 SetPrivateState(eStateDetached);
2442 ResumePrivateStateThread();
2443
2444 // KillDebugserverProcess ();
2445 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002446}
2447
Zachary Turner97206d52017-05-12 04:51:55 +00002448Status ProcessGDBRemote::DoDestroy() {
2449 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002450 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2451 if (log)
2452 log->Printf("ProcessGDBRemote::DoDestroy()");
Ed Maste81b4c5f2016-01-04 01:43:47 +00002453
Kate Stoneb9c1b512016-09-06 20:57:50 +00002454 // There is a bug in older iOS debugservers where they don't shut down the
Adrian Prantl05097242018-04-30 16:49:04 +00002455 // process they are debugging properly. If the process is sitting at a
2456 // breakpoint or an exception, this can cause problems with restarting. So
2457 // we check to see if any of our threads are stopped at a breakpoint, and if
2458 // so we remove all the breakpoints, resume the process, and THEN destroy it
2459 // again.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002460 //
2461 // Note, we don't have a good way to test the version of debugserver, but I
Adrian Prantl05097242018-04-30 16:49:04 +00002462 // happen to know that the set of all the iOS debugservers which don't
2463 // support GetThreadSuffixSupported() and that of the debugservers with this
2464 // bug are equal. There really should be a better way to test this!
Kate Stoneb9c1b512016-09-06 20:57:50 +00002465 //
2466 // We also use m_destroy_tried_resuming to make sure we only do this once, if
Adrian Prantl05097242018-04-30 16:49:04 +00002467 // we resume and then halt and get called here to destroy again and we're
2468 // still at a breakpoint or exception, then we should just do the straight-
2469 // forward kill.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002470 //
2471 // And of course, if we weren't able to stop the process by the time we get
Adrian Prantl05097242018-04-30 16:49:04 +00002472 // here, it isn't necessary (or helpful) to do any of this.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002473
Kate Stoneb9c1b512016-09-06 20:57:50 +00002474 if (!m_gdb_comm.GetThreadSuffixSupported() &&
2475 m_public_state.GetValue() != eStateRunning) {
2476 PlatformSP platform_sp = GetTarget().GetPlatform();
Jim Inghamacff8952013-05-02 00:27:30 +00002477
Kate Stoneb9c1b512016-09-06 20:57:50 +00002478 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2479 if (platform_sp && platform_sp->GetName() &&
2480 platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2481 if (m_destroy_tried_resuming) {
Greg Clayton8cda7f02013-05-21 21:55:59 +00002482 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002483 log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2484 "destroy once already, not doing it again.");
2485 } else {
2486 // At present, the plans are discarded and the breakpoints disabled
Adrian Prantl05097242018-04-30 16:49:04 +00002487 // Process::Destroy, but we really need it to happen here and it
2488 // doesn't matter if we do it twice.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002489 m_thread_list.DiscardThreadPlans();
2490 DisableAllBreakpointSites();
Greg Clayton8cda7f02013-05-21 21:55:59 +00002491
Kate Stoneb9c1b512016-09-06 20:57:50 +00002492 bool stop_looks_like_crash = false;
2493 ThreadList &threads = GetThreadList();
2494
2495 {
2496 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2497
2498 size_t num_threads = threads.GetSize();
2499 for (size_t i = 0; i < num_threads; i++) {
2500 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2501 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2502 StopReason reason = eStopReasonInvalid;
2503 if (stop_info_sp)
2504 reason = stop_info_sp->GetStopReason();
2505 if (reason == eStopReasonBreakpoint ||
2506 reason == eStopReasonException) {
2507 if (log)
2508 log->Printf(
2509 "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2510 " stopped with reason: %s.",
2511 thread_sp->GetProtocolID(), stop_info_sp->GetDescription());
2512 stop_looks_like_crash = true;
2513 break;
2514 }
2515 }
2516 }
2517
2518 if (stop_looks_like_crash) {
2519 if (log)
2520 log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2521 "breakpoint, continue and then kill.");
2522 m_destroy_tried_resuming = true;
2523
2524 // If we are going to run again before killing, it would be good to
Adrian Prantl05097242018-04-30 16:49:04 +00002525 // suspend all the threads before resuming so they won't get into
2526 // more trouble. Sadly, for the threads stopped with the breakpoint
2527 // or exception, the exception doesn't get cleared if it is
2528 // suspended, so we do have to run the risk of letting those threads
2529 // proceed a bit.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002530
2531 {
2532 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2533
2534 size_t num_threads = threads.GetSize();
2535 for (size_t i = 0; i < num_threads; i++) {
2536 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2537 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2538 StopReason reason = eStopReasonInvalid;
2539 if (stop_info_sp)
2540 reason = stop_info_sp->GetStopReason();
2541 if (reason != eStopReasonBreakpoint &&
2542 reason != eStopReasonException) {
2543 if (log)
2544 log->Printf("ProcessGDBRemote::DoDestroy() - Suspending "
2545 "thread: 0x%4.4" PRIx64 " before running.",
2546 thread_sp->GetProtocolID());
2547 thread_sp->SetResumeState(eStateSuspended);
2548 }
2549 }
2550 }
2551 Resume();
2552 return Destroy(false);
2553 }
2554 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002555 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002556 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002557
Kate Stoneb9c1b512016-09-06 20:57:50 +00002558 // Interrupt if our inferior is running...
2559 int exit_status = SIGABRT;
2560 std::string exit_string;
Greg Clayton2e309072015-07-17 23:42:28 +00002561
Kate Stoneb9c1b512016-09-06 20:57:50 +00002562 if (m_gdb_comm.IsConnected()) {
2563 if (m_public_state.GetValue() != eStateAttaching) {
2564 StringExtractorGDBRemote response;
2565 bool send_async = true;
Pavel Labath3aa04912016-10-31 17:19:42 +00002566 GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2567 std::chrono::seconds(3));
Greg Clayton2e309072015-07-17 23:42:28 +00002568
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002569 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002570 GDBRemoteCommunication::PacketResult::Success) {
2571 char packet_cmd = response.GetChar(0);
2572
2573 if (packet_cmd == 'W' || packet_cmd == 'X') {
2574#if defined(__APPLE__)
2575 // For Native processes on Mac OS X, we launch through the Host
Adrian Prantl05097242018-04-30 16:49:04 +00002576 // Platform, then hand the process off to debugserver, which becomes
2577 // the parent process through "PT_ATTACH". Then when we go to kill
2578 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2579 // we call waitpid which returns with no error and the correct
2580 // status. But amusingly enough that doesn't seem to actually reap
Kate Stoneb9c1b512016-09-06 20:57:50 +00002581 // the process, but instead it is left around as a Zombie. Probably
Adrian Prantl05097242018-04-30 16:49:04 +00002582 // the kernel is in the process of switching ownership back to lldb
2583 // which was the original parent, and gets confused in the handoff.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002584 // Anyway, so call waitpid here to finally reap it.
2585 PlatformSP platform_sp(GetTarget().GetPlatform());
2586 if (platform_sp && platform_sp->IsHost()) {
2587 int status;
2588 ::pid_t reap_pid;
2589 reap_pid = waitpid(GetID(), &status, WNOHANG);
2590 if (log)
2591 log->Printf("Reaped pid: %d, status: %d.\n", reap_pid, status);
2592 }
2593#endif
2594 SetLastStopPacket(response);
2595 ClearThreadIDList();
2596 exit_status = response.GetHexU8();
2597 } else {
2598 if (log)
2599 log->Printf("ProcessGDBRemote::DoDestroy - got unexpected response "
2600 "to k packet: %s",
2601 response.GetStringRef().c_str());
2602 exit_string.assign("got unexpected response to k packet: ");
2603 exit_string.append(response.GetStringRef());
2604 }
2605 } else {
2606 if (log)
2607 log->Printf("ProcessGDBRemote::DoDestroy - failed to send k packet");
2608 exit_string.assign("failed to send the k packet");
2609 }
2610 } else {
2611 if (log)
2612 log->Printf("ProcessGDBRemote::DoDestroy - killed or interrupted while "
2613 "attaching");
2614 exit_string.assign("killed or interrupted while attaching.");
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002615 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002616 } else {
2617 // If we missed setting the exit status on the way out, do it here.
2618 // NB set exit status can be called multiple times, the first one sets the
2619 // status.
2620 exit_string.assign("destroying when not connected to debugserver");
2621 }
2622
2623 SetExitStatus(exit_status, exit_string.c_str());
2624
2625 StopAsyncThread();
2626 KillDebugserverProcess();
2627 return error;
Greg Clayton8cda7f02013-05-21 21:55:59 +00002628}
2629
Kate Stoneb9c1b512016-09-06 20:57:50 +00002630void ProcessGDBRemote::SetLastStopPacket(
2631 const StringExtractorGDBRemote &response) {
2632 const bool did_exec =
2633 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2634 if (did_exec) {
2635 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2636 if (log)
2637 log->Printf("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2638
2639 m_thread_list_real.Clear();
2640 m_thread_list.Clear();
2641 BuildDynamicRegisterInfo(true);
2642 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2643 }
2644
2645 // Scope the lock
2646 {
2647 // Lock the thread stack while we access it
2648 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2649
2650 // We are are not using non-stop mode, there can only be one last stop
2651 // reply packet, so clear the list.
2652 if (GetTarget().GetNonStopModeEnabled() == false)
2653 m_stop_packet_stack.clear();
2654
Adrian Prantl05097242018-04-30 16:49:04 +00002655 // Add this stop packet to the stop packet stack This stack will get popped
2656 // and examined when we switch to the Stopped state
Kate Stoneb9c1b512016-09-06 20:57:50 +00002657 m_stop_packet_stack.push_back(response);
2658 }
2659}
2660
2661void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2662 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
Chaoren Linc963a222015-09-01 16:58:45 +00002663}
2664
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002665//------------------------------------------------------------------
2666// Process Queries
2667//------------------------------------------------------------------
2668
Kate Stoneb9c1b512016-09-06 20:57:50 +00002669bool ProcessGDBRemote::IsAlive() {
2670 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002671}
2672
Kate Stoneb9c1b512016-09-06 20:57:50 +00002673addr_t ProcessGDBRemote::GetImageInfoAddress() {
2674 // request the link map address via the $qShlibInfoAddr packet
2675 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
Aidan Doddsc0c83852015-05-08 09:36:31 +00002676
Kate Stoneb9c1b512016-09-06 20:57:50 +00002677 // the loaded module list can also provides a link map address
2678 if (addr == LLDB_INVALID_ADDRESS) {
2679 LoadedModuleInfoList list;
2680 if (GetLoadedModuleList(list).Success())
2681 addr = list.m_link_map;
2682 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00002683
Kate Stoneb9c1b512016-09-06 20:57:50 +00002684 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002685}
2686
Kate Stoneb9c1b512016-09-06 20:57:50 +00002687void ProcessGDBRemote::WillPublicStop() {
Adrian Prantl05097242018-04-30 16:49:04 +00002688 // See if the GDB remote client supports the JSON threads info. If so, we
2689 // gather stop info for all threads, expedited registers, expedited memory,
2690 // runtime queue information (iOS and MacOSX only), and more. Expediting
2691 // memory will help stack backtracing be much faster. Expediting registers
2692 // will make sure we don't have to read the thread registers for GPRs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002693 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
Greg Clayton2e309072015-07-17 23:42:28 +00002694
Kate Stoneb9c1b512016-09-06 20:57:50 +00002695 if (m_jthreadsinfo_sp) {
2696 // Now set the stop info for each thread and also expedite any registers
2697 // and memory that was in the jThreadsInfo response.
2698 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2699 if (thread_infos) {
2700 const size_t n = thread_infos->GetSize();
2701 for (size_t i = 0; i < n; ++i) {
2702 StructuredData::Dictionary *thread_dict =
2703 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2704 if (thread_dict)
2705 SetThreadStopInfo(thread_dict);
2706 }
Greg Clayton2e309072015-07-17 23:42:28 +00002707 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708 }
Greg Clayton2e309072015-07-17 23:42:28 +00002709}
2710
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002711//------------------------------------------------------------------
2712// Process Memory
2713//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002714size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002715 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002716 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002717 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2718 // M and m packets take 2 bytes for 1 byte of memory
2719 size_t max_memory_size =
2720 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2721 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002722 // Keep memory read sizes down to a sane limit. This function will be
2723 // called multiple times in order to complete the task by
2724 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002725 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002726 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002727
Kate Stoneb9c1b512016-09-06 20:57:50 +00002728 char packet[64];
2729 int packet_len;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002730 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2731 binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2732 (uint64_t)size);
2733 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002734 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002735 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002736 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002737 GDBRemoteCommunication::PacketResult::Success) {
2738 if (response.IsNormalResponse()) {
2739 error.Clear();
2740 if (binary_memory_read) {
2741 // The lower level GDBRemoteCommunication packet receive layer has
Adrian Prantl05097242018-04-30 16:49:04 +00002742 // already de-quoted any 0x7d character escaping that was present in
2743 // the packet
Jason Molenda6076bf42014-05-06 04:34:52 +00002744
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745 size_t data_received_size = response.GetBytesLeft();
2746 if (data_received_size > size) {
2747 // Don't write past the end of BUF if the remote debug server gave us
Adrian Prantl05097242018-04-30 16:49:04 +00002748 // too much data for some reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749 data_received_size = size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002750 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002751 memcpy(buf, response.GetStringRef().data(), data_received_size);
2752 return data_received_size;
2753 } else {
2754 return response.GetHexBytes(
2755 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2756 }
2757 } else if (response.IsErrorResponse())
2758 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2759 else if (response.IsUnsupportedResponse())
2760 error.SetErrorStringWithFormat(
2761 "GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002762 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002763 error.SetErrorStringWithFormat(
2764 "unexpected response to GDB server memory read packet '%s': '%s'",
2765 packet, response.GetStringRef().c_str());
2766 } else {
2767 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2768 }
2769 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002770}
2771
Pavel Labath16064d32018-03-20 11:56:24 +00002772Status ProcessGDBRemote::WriteObjectFile(
2773 std::vector<ObjectFile::LoadableData> entries) {
2774 Status error;
2775 // Sort the entries by address because some writes, like those to flash
2776 // memory, must happen in order of increasing address.
2777 std::stable_sort(
2778 std::begin(entries), std::end(entries),
2779 [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2780 return a.Dest < b.Dest;
2781 });
2782 m_allow_flash_writes = true;
2783 error = Process::WriteObjectFile(entries);
2784 if (error.Success())
2785 error = FlashDone();
2786 else
Adrian Prantl05097242018-04-30 16:49:04 +00002787 // Even though some of the writing failed, try to send a flash done if some
2788 // of the writing succeeded so the flash state is reset to normal, but
2789 // don't stomp on the error status that was set in the write failure since
2790 // that's the one we want to report back.
Pavel Labath16064d32018-03-20 11:56:24 +00002791 FlashDone();
2792 m_allow_flash_writes = false;
2793 return error;
2794}
2795
2796bool ProcessGDBRemote::HasErased(FlashRange range) {
2797 auto size = m_erased_flash_ranges.GetSize();
2798 for (size_t i = 0; i < size; ++i)
2799 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2800 return true;
2801 return false;
2802}
2803
2804Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2805 Status status;
2806
2807 MemoryRegionInfo region;
2808 status = GetMemoryRegionInfo(addr, region);
2809 if (!status.Success())
2810 return status;
2811
2812 // The gdb spec doesn't say if erasures are allowed across multiple regions,
2813 // but we'll disallow it to be safe and to keep the logic simple by worring
2814 // about only one region's block size. DoMemoryWrite is this function's
2815 // primary user, and it can easily keep writes within a single memory region
2816 if (addr + size > region.GetRange().GetRangeEnd()) {
2817 status.SetErrorString("Unable to erase flash in multiple regions");
2818 return status;
2819 }
2820
2821 uint64_t blocksize = region.GetBlocksize();
2822 if (blocksize == 0) {
2823 status.SetErrorString("Unable to erase flash because blocksize is 0");
2824 return status;
2825 }
2826
2827 // Erasures can only be done on block boundary adresses, so round down addr
2828 // and round up size
2829 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2830 size += (addr - block_start_addr);
2831 if ((size % blocksize) != 0)
2832 size += (blocksize - size % blocksize);
2833
2834 FlashRange range(block_start_addr, size);
2835
2836 if (HasErased(range))
2837 return status;
2838
2839 // We haven't erased the entire range, but we may have erased part of it.
Adrian Prantl05097242018-04-30 16:49:04 +00002840 // (e.g., block A is already erased and range starts in A and ends in B). So,
2841 // adjust range if necessary to exclude already erased blocks.
Pavel Labath16064d32018-03-20 11:56:24 +00002842 if (!m_erased_flash_ranges.IsEmpty()) {
2843 // Assuming that writes and erasures are done in increasing addr order,
Adrian Prantl05097242018-04-30 16:49:04 +00002844 // because that is a requirement of the vFlashWrite command. Therefore, we
2845 // only need to look at the last range in the list for overlap.
Pavel Labath16064d32018-03-20 11:56:24 +00002846 const auto &last_range = *m_erased_flash_ranges.Back();
2847 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2848 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
Adrian Prantl05097242018-04-30 16:49:04 +00002849 // overlap will be less than range.GetByteSize() or else HasErased()
2850 // would have been true
Pavel Labath16064d32018-03-20 11:56:24 +00002851 range.SetByteSize(range.GetByteSize() - overlap);
2852 range.SetRangeBase(range.GetRangeBase() + overlap);
2853 }
2854 }
2855
2856 StreamString packet;
2857 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2858 (uint64_t)range.GetByteSize());
2859
2860 StringExtractorGDBRemote response;
2861 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2862 true) ==
2863 GDBRemoteCommunication::PacketResult::Success) {
2864 if (response.IsOKResponse()) {
2865 m_erased_flash_ranges.Insert(range, true);
2866 } else {
2867 if (response.IsErrorResponse())
2868 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2869 addr);
2870 else if (response.IsUnsupportedResponse())
2871 status.SetErrorStringWithFormat("GDB server does not support flashing");
2872 else
2873 status.SetErrorStringWithFormat(
2874 "unexpected response to GDB server flash erase packet '%s': '%s'",
2875 packet.GetData(), response.GetStringRef().c_str());
2876 }
2877 } else {
2878 status.SetErrorStringWithFormat("failed to send packet: '%s'",
2879 packet.GetData());
2880 }
2881 return status;
2882}
2883
2884Status ProcessGDBRemote::FlashDone() {
2885 Status status;
2886 // If we haven't erased any blocks, then we must not have written anything
2887 // either, so there is no need to actually send a vFlashDone command
2888 if (m_erased_flash_ranges.IsEmpty())
2889 return status;
2890 StringExtractorGDBRemote response;
2891 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, true) ==
2892 GDBRemoteCommunication::PacketResult::Success) {
2893 if (response.IsOKResponse()) {
2894 m_erased_flash_ranges.Clear();
2895 } else {
2896 if (response.IsErrorResponse())
2897 status.SetErrorStringWithFormat("flash done failed");
2898 else if (response.IsUnsupportedResponse())
2899 status.SetErrorStringWithFormat("GDB server does not support flashing");
2900 else
2901 status.SetErrorStringWithFormat(
2902 "unexpected response to GDB server flash done packet: '%s'",
2903 response.GetStringRef().c_str());
2904 }
2905 } else {
2906 status.SetErrorStringWithFormat("failed to send flash done packet");
2907 }
2908 return status;
2909}
2910
Kate Stoneb9c1b512016-09-06 20:57:50 +00002911size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
Zachary Turner97206d52017-05-12 04:51:55 +00002912 size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002914 // M and m packets take 2 bytes for 1 byte of memory
2915 size_t max_memory_size = m_max_memory_size / 2;
2916 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002917 // Keep memory read sizes down to a sane limit. This function will be
2918 // called multiple times in order to complete the task by
2919 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002920 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921 }
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002922
Pavel Labath16064d32018-03-20 11:56:24 +00002923 StreamGDBRemote packet;
2924
2925 MemoryRegionInfo region;
2926 Status region_status = GetMemoryRegionInfo(addr, region);
2927
2928 bool is_flash =
2929 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2930
2931 if (is_flash) {
2932 if (!m_allow_flash_writes) {
2933 error.SetErrorString("Writing to flash memory is not allowed");
2934 return 0;
2935 }
2936 // Keep the write within a flash memory region
2937 if (addr + size > region.GetRange().GetRangeEnd())
2938 size = region.GetRange().GetRangeEnd() - addr;
2939 // Flash memory must be erased before it can be written
2940 error = FlashErase(addr, size);
2941 if (!error.Success())
2942 return 0;
2943 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2944 packet.PutEscapedBytes(buf, size);
2945 } else {
2946 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2947 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2948 endian::InlHostByteOrder());
2949 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002950 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002951 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2952 true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002953 GDBRemoteCommunication::PacketResult::Success) {
2954 if (response.IsOKResponse()) {
2955 error.Clear();
2956 return size;
2957 } else if (response.IsErrorResponse())
2958 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2959 addr);
2960 else if (response.IsUnsupportedResponse())
2961 error.SetErrorStringWithFormat(
2962 "GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002963 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 error.SetErrorStringWithFormat(
2965 "unexpected response to GDB server memory write packet '%s': '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00002966 packet.GetData(), response.GetStringRef().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002967 } else {
2968 error.SetErrorStringWithFormat("failed to send packet: '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00002969 packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970 }
2971 return 0;
2972}
2973
2974lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2975 uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002976 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002977 Log *log(
2978 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
2979 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2980
2981 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2982 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2983 if (allocated_addr != LLDB_INVALID_ADDRESS ||
2984 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2985 return allocated_addr;
2986 }
2987
2988 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2989 // Call mmap() to create memory in the inferior..
2990 unsigned prot = 0;
2991 if (permissions & lldb::ePermissionsReadable)
2992 prot |= eMmapProtRead;
2993 if (permissions & lldb::ePermissionsWritable)
2994 prot |= eMmapProtWrite;
2995 if (permissions & lldb::ePermissionsExecutable)
2996 prot |= eMmapProtExec;
2997
2998 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2999 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3000 m_addr_to_mmap_size[allocated_addr] = size;
3001 else {
3002 allocated_addr = LLDB_INVALID_ADDRESS;
3003 if (log)
3004 log->Printf("ProcessGDBRemote::%s no direct stub support for memory "
3005 "allocation, and InferiorCallMmap also failed - is stub "
3006 "missing register context save/restore capability?",
3007 __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003008 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009 }
3010
3011 if (allocated_addr == LLDB_INVALID_ADDRESS)
3012 error.SetErrorStringWithFormat(
3013 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
3014 (uint64_t)size, GetPermissionsAsCString(permissions));
3015 else
3016 error.Clear();
3017 return allocated_addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003018}
3019
Zachary Turner97206d52017-05-12 04:51:55 +00003020Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
3021 MemoryRegionInfo &region_info) {
Ed Maste81b4c5f2016-01-04 01:43:47 +00003022
Zachary Turner97206d52017-05-12 04:51:55 +00003023 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003024 return error;
3025}
3026
Zachary Turner97206d52017-05-12 04:51:55 +00003027Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003028
Zachary Turner97206d52017-05-12 04:51:55 +00003029 Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003030 return error;
3031}
3032
Zachary Turner97206d52017-05-12 04:51:55 +00003033Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
3034 Status error(m_gdb_comm.GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003035 num, after, GetTarget().GetArchitecture()));
3036 return error;
3037}
3038
Zachary Turner97206d52017-05-12 04:51:55 +00003039Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
3040 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003041 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3042
3043 switch (supported) {
3044 case eLazyBoolCalculate:
Adrian Prantl05097242018-04-30 16:49:04 +00003045 // We should never be deallocating memory without allocating memory first
3046 // so we should never get eLazyBoolCalculate
Kate Stoneb9c1b512016-09-06 20:57:50 +00003047 error.SetErrorString(
3048 "tried to deallocate memory without ever allocating memory");
3049 break;
3050
3051 case eLazyBoolYes:
3052 if (!m_gdb_comm.DeallocateMemory(addr))
3053 error.SetErrorStringWithFormat(
3054 "unable to deallocate memory at 0x%" PRIx64, addr);
3055 break;
3056
3057 case eLazyBoolNo:
3058 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2a48f522011-05-14 01:50:35 +00003059 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003060 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3061 if (pos != m_addr_to_mmap_size.end() &&
3062 InferiorCallMunmap(this, addr, pos->second))
3063 m_addr_to_mmap_size.erase(pos);
3064 else
3065 error.SetErrorStringWithFormat(
3066 "unable to deallocate memory at 0x%" PRIx64, addr);
Greg Claytoncec91ef2016-02-26 01:20:20 +00003067 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003068 break;
3069 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003070
Kate Stoneb9c1b512016-09-06 20:57:50 +00003071 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003072}
3073
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003074//------------------------------------------------------------------
3075// Process STDIO
3076//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003077size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00003078 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003079 if (m_stdio_communication.IsConnected()) {
3080 ConnectionStatus status;
3081 m_stdio_communication.Write(src, src_len, status, NULL);
3082 } else if (m_stdin_forward) {
3083 m_gdb_comm.SendStdinNotification(src, src_len);
3084 }
3085 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003086}
3087
Zachary Turner97206d52017-05-12 04:51:55 +00003088Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
3089 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003090 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091
Kate Stoneb9c1b512016-09-06 20:57:50 +00003092 // Get logging info
3093 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3094 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003095
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096 // Get the breakpoint address
3097 const addr_t addr = bp_site->GetLoadAddress();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003098
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 // Log that a breakpoint was requested
3100 if (log)
3101 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3102 ") address = 0x%" PRIx64,
3103 site_id, (uint64_t)addr);
3104
3105 // Breakpoint already exists and is enabled
3106 if (bp_site->IsEnabled()) {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003107 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003108 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3109 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3110 site_id, (uint64_t)addr);
3111 return error;
3112 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003113
Kate Stoneb9c1b512016-09-06 20:57:50 +00003114 // Get the software breakpoint trap opcode size
3115 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3116
3117 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
Adrian Prantl05097242018-04-30 16:49:04 +00003118 // breakpoint type is supported by the remote stub. These are set to true by
3119 // default, and later set to false only after we receive an unimplemented
3120 // response when sending a breakpoint packet. This means initially that
3121 // unless we were specifically instructed to use a hardware breakpoint, LLDB
3122 // will attempt to set a software breakpoint. HardwareRequired() also queries
3123 // a boolean variable which indicates if the user specifically asked for
3124 // hardware breakpoints. If true then we will skip over software
3125 // breakpoints.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003126 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3127 (!bp_site->HardwareRequired())) {
3128 // Try to send off a software breakpoint packet ($Z0)
3129 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3130 eBreakpointSoftware, true, addr, bp_op_size);
3131 if (error_no == 0) {
3132 // The breakpoint was placed successfully
3133 bp_site->SetEnabled(true);
3134 bp_site->SetType(BreakpointSite::eExternal);
3135 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003136 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003137
Adrian Prantl05097242018-04-30 16:49:04 +00003138 // SendGDBStoppointTypePacket() will return an error if it was unable to
3139 // set this breakpoint. We need to differentiate between a error specific
3140 // to placing this breakpoint or if we have learned that this breakpoint
3141 // type is unsupported. To do this, we must test the support boolean for
3142 // this breakpoint type to see if it now indicates that this breakpoint
3143 // type is unsupported. If they are still supported then we should return
Kate Stoneb9c1b512016-09-06 20:57:50 +00003144 // with the error code. If they are now unsupported, then we would like to
Adrian Prantl05097242018-04-30 16:49:04 +00003145 // fall through and try another form of breakpoint.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003146 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3147 if (error_no != UINT8_MAX)
3148 error.SetErrorStringWithFormat(
3149 "error: %d sending the breakpoint request", errno);
3150 else
3151 error.SetErrorString("error sending the breakpoint request");
3152 return error;
3153 }
3154
3155 // We reach here when software breakpoints have been found to be
Adrian Prantl05097242018-04-30 16:49:04 +00003156 // unsupported. For future calls to set a breakpoint, we will not attempt
3157 // to set a breakpoint with a type that is known not to be supported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003158 if (log)
3159 log->Printf("Software breakpoints are unsupported");
3160
3161 // So we will fall through and try a hardware breakpoint
3162 }
3163
Adrian Prantl05097242018-04-30 16:49:04 +00003164 // The process of setting a hardware breakpoint is much the same as above.
3165 // We check the supported boolean for this breakpoint type, and if it is
3166 // thought to be supported then we will try to set this breakpoint with a
3167 // hardware breakpoint.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003168 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3169 // Try to send off a hardware breakpoint packet ($Z1)
3170 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3171 eBreakpointHardware, true, addr, bp_op_size);
3172 if (error_no == 0) {
3173 // The breakpoint was placed successfully
3174 bp_site->SetEnabled(true);
3175 bp_site->SetType(BreakpointSite::eHardware);
3176 return error;
3177 }
3178
3179 // Check if the error was something other then an unsupported breakpoint
3180 // type
3181 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3182 // Unable to set this hardware breakpoint
3183 if (error_no != UINT8_MAX)
3184 error.SetErrorStringWithFormat(
3185 "error: %d sending the hardware breakpoint request "
3186 "(hardware breakpoint resources might be exhausted or unavailable)",
3187 error_no);
3188 else
3189 error.SetErrorString("error sending the hardware breakpoint request "
3190 "(hardware breakpoint resources "
3191 "might be exhausted or unavailable)");
3192 return error;
3193 }
3194
3195 // We will reach here when the stub gives an unsupported response to a
3196 // hardware breakpoint
3197 if (log)
3198 log->Printf("Hardware breakpoints are unsupported");
3199
3200 // Finally we will falling through to a #trap style breakpoint
3201 }
3202
3203 // Don't fall through when hardware breakpoints were specifically requested
3204 if (bp_site->HardwareRequired()) {
3205 error.SetErrorString("hardware breakpoints are not supported");
3206 return error;
3207 }
3208
Adrian Prantl05097242018-04-30 16:49:04 +00003209 // As a last resort we want to place a manual breakpoint. An instruction is
3210 // placed into the process memory using memory write packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003211 return EnableSoftwareBreakpoint(bp_site);
3212}
3213
Zachary Turner97206d52017-05-12 04:51:55 +00003214Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3215 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003216 assert(bp_site != NULL);
3217 addr_t addr = bp_site->GetLoadAddress();
3218 user_id_t site_id = bp_site->GetID();
3219 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3220 if (log)
3221 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3222 ") addr = 0x%8.8" PRIx64,
3223 site_id, (uint64_t)addr);
3224
3225 if (bp_site->IsEnabled()) {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003226 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3227
Kate Stoneb9c1b512016-09-06 20:57:50 +00003228 BreakpointSite::Type bp_type = bp_site->GetType();
3229 switch (bp_type) {
3230 case BreakpointSite::eSoftware:
3231 error = DisableSoftwareBreakpoint(bp_site);
3232 break;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003233
Kate Stoneb9c1b512016-09-06 20:57:50 +00003234 case BreakpointSite::eHardware:
3235 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3236 addr, bp_op_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003237 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003238 break;
3239
3240 case BreakpointSite::eExternal: {
3241 GDBStoppointType stoppoint_type;
3242 if (bp_site->IsHardware())
3243 stoppoint_type = eBreakpointHardware;
3244 else
3245 stoppoint_type = eBreakpointSoftware;
3246
3247 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr,
3248 bp_op_size))
3249 error.SetErrorToGenericError();
3250 } break;
3251 }
3252 if (error.Success())
3253 bp_site->SetEnabled(false);
3254 } else {
3255 if (log)
3256 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3257 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3258 site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003259 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003260 }
3261
3262 if (error.Success())
3263 error.SetErrorToGenericError();
3264 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003265}
3266
Johnny Chen11309a32011-09-06 22:38:36 +00003267// Pre-requisite: wp != NULL.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003268static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3269 assert(wp);
3270 bool watch_read = wp->WatchpointRead();
3271 bool watch_write = wp->WatchpointWrite();
Johnny Chen11309a32011-09-06 22:38:36 +00003272
Kate Stoneb9c1b512016-09-06 20:57:50 +00003273 // watch_read and watch_write cannot both be false.
3274 assert(watch_read || watch_write);
3275 if (watch_read && watch_write)
3276 return eWatchpointReadWrite;
3277 else if (watch_read)
3278 return eWatchpointRead;
3279 else // Must be watch_write, then.
3280 return eWatchpointWrite;
Johnny Chen11309a32011-09-06 22:38:36 +00003281}
3282
Zachary Turner97206d52017-05-12 04:51:55 +00003283Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3284 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003285 if (wp) {
3286 user_id_t watchID = wp->GetID();
3287 addr_t addr = wp->GetLoadAddress();
3288 Log *log(
3289 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003290 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003291 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3292 watchID);
3293 if (wp->IsEnabled()) {
3294 if (log)
3295 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3296 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3297 watchID, (uint64_t)addr);
3298 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003299 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003300
3301 GDBStoppointType type = GetGDBStoppointType(wp);
3302 // Pass down an appropriate z/Z packet...
3303 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3304 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3305 wp->GetByteSize()) == 0) {
3306 wp->SetEnabled(true, notify);
3307 return error;
3308 } else
3309 error.SetErrorString("sending gdb watchpoint packet failed");
3310 } else
3311 error.SetErrorString("watchpoints not supported");
3312 } else {
3313 error.SetErrorString("Watchpoint argument was NULL.");
3314 }
3315 if (error.Success())
3316 error.SetErrorToGenericError();
3317 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003318}
Kate Stoneb9c1b512016-09-06 20:57:50 +00003319
Zachary Turner97206d52017-05-12 04:51:55 +00003320Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3321 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003322 if (wp) {
3323 user_id_t watchID = wp->GetID();
3324
3325 Log *log(
3326 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3327
3328 addr_t addr = wp->GetLoadAddress();
3329
3330 if (log)
3331 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3332 ") addr = 0x%8.8" PRIx64,
3333 watchID, (uint64_t)addr);
3334
3335 if (!wp->IsEnabled()) {
3336 if (log)
3337 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3338 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3339 watchID, (uint64_t)addr);
Adrian Prantl05097242018-04-30 16:49:04 +00003340 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3341 // attempt might come from the user-supplied actions, we'll route it in
3342 // order for the watchpoint object to intelligently process this action.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003343 wp->SetEnabled(false, notify);
3344 return error;
3345 }
3346
3347 if (wp->IsHardware()) {
3348 GDBStoppointType type = GetGDBStoppointType(wp);
3349 // Pass down an appropriate z/Z packet...
3350 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3351 wp->GetByteSize()) == 0) {
3352 wp->SetEnabled(false, notify);
3353 return error;
3354 } else
3355 error.SetErrorString("sending gdb watchpoint packet failed");
3356 }
3357 // TODO: clear software watchpoints if we implement them
3358 } else {
3359 error.SetErrorString("Watchpoint argument was NULL.");
3360 }
3361 if (error.Success())
3362 error.SetErrorToGenericError();
3363 return error;
3364}
3365
3366void ProcessGDBRemote::Clear() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003367 m_thread_list_real.Clear();
3368 m_thread_list.Clear();
3369}
3370
Zachary Turner97206d52017-05-12 04:51:55 +00003371Status ProcessGDBRemote::DoSignal(int signo) {
3372 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003373 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3374 if (log)
3375 log->Printf("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3376
3377 if (!m_gdb_comm.SendAsyncSignal(signo))
3378 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3379 return error;
3380}
3381
Zachary Turner97206d52017-05-12 04:51:55 +00003382Status
3383ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003384 // Make sure we aren't already connected?
3385 if (m_gdb_comm.IsConnected())
Zachary Turner97206d52017-05-12 04:51:55 +00003386 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003387
3388 PlatformSP platform_sp(GetTarget().GetPlatform());
3389 if (platform_sp && !platform_sp->IsHost())
Zachary Turner97206d52017-05-12 04:51:55 +00003390 return Status("Lost debug server connection");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003391
3392 auto error = LaunchAndConnectToDebugserver(process_info);
3393 if (error.Fail()) {
3394 const char *error_string = error.AsCString();
3395 if (error_string == nullptr)
3396 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3397 }
3398 return error;
3399}
Eugene Zemtsov30153412017-09-25 17:41:16 +00003400#if !defined(_WIN32)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003401#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3402#endif
3403
3404#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Kate Stoneb9c1b512016-09-06 20:57:50 +00003405static bool SetCloexecFlag(int fd) {
3406#if defined(FD_CLOEXEC)
3407 int flags = ::fcntl(fd, F_GETFD);
3408 if (flags == -1)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003409 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003410 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3411#else
3412 return false;
Greg Claytonc6c420f2016-08-12 16:46:18 +00003413#endif
3414}
3415#endif
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003416
Zachary Turner97206d52017-05-12 04:51:55 +00003417Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003418 const ProcessInfo &process_info) {
3419 using namespace std::placeholders; // For _1, _2, etc.
Pavel Labath998bdc52016-05-11 16:59:04 +00003420
Zachary Turner97206d52017-05-12 04:51:55 +00003421 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003422 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3423 // If we locate debugserver, keep that located version around
3424 static FileSpec g_debugserver_file_spec;
3425
3426 ProcessLaunchInfo debugserver_launch_info;
Adrian Prantl05097242018-04-30 16:49:04 +00003427 // Make debugserver run in its own session so signals generated by special
3428 // terminal key sequences (^C) don't affect debugserver.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003429 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3430
3431 const std::weak_ptr<ProcessGDBRemote> this_wp =
3432 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3433 debugserver_launch_info.SetMonitorProcessCallback(
3434 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3435 debugserver_launch_info.SetUserID(process_info.GetUserID());
3436
3437 int communication_fd = -1;
3438#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Eugene Zemtsov30153412017-09-25 17:41:16 +00003439 // Use a socketpair on non-Windows systems for security and performance
3440 // reasons.
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003441 int sockets[2]; /* the pair of socket descriptors */
3442 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3443 error.SetErrorToErrno();
3444 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003445 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003446
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003447 int our_socket = sockets[0];
3448 int gdb_socket = sockets[1];
3449 CleanUp cleanup_our(close, our_socket);
3450 CleanUp cleanup_gdb(close, gdb_socket);
3451
Kate Stoneb9c1b512016-09-06 20:57:50 +00003452 // Don't let any child processes inherit our communication socket
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003453 SetCloexecFlag(our_socket);
3454 communication_fd = gdb_socket;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003455#endif
3456
3457 error = m_gdb_comm.StartDebugserverProcess(
3458 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3459 nullptr, nullptr, communication_fd);
3460
3461 if (error.Success())
3462 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3463 else
3464 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3465
3466 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3467#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Adrian Prantl05097242018-04-30 16:49:04 +00003468 // Our process spawned correctly, we can now set our connection to use
3469 // our end of the socket pair
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003470 cleanup_our.disable();
3471 m_gdb_comm.SetConnection(new ConnectionFileDescriptor(our_socket, true));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003472#endif
3473 StartAsyncThread();
3474 }
3475
3476 if (error.Fail()) {
3477 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3478
3479 if (log)
3480 log->Printf("failed to start debugserver process: %s",
3481 error.AsCString());
3482 return error;
3483 }
3484
3485 if (m_gdb_comm.IsConnected()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003486 // Finish the connection process by doing the handshake without
3487 // connecting (send NULL URL)
Zachary Turner31659452016-11-17 21:15:14 +00003488 ConnectToDebugserver("");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003489 } else {
3490 error.SetErrorString("connection failed");
3491 }
3492 }
3493 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003494}
3495
Kate Stoneb9c1b512016-09-06 20:57:50 +00003496bool ProcessGDBRemote::MonitorDebugserverProcess(
3497 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3498 bool exited, // True if the process did exit
3499 int signo, // Zero for no signal
3500 int exit_status // Exit value of process if signal is zero
3501 ) {
Adrian Prantl05097242018-04-30 16:49:04 +00003502 // "debugserver_pid" argument passed in is the process ID for debugserver
3503 // that we are tracking...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003504 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3505 const bool handled = true;
Greg Claytone4e45922011-11-16 05:37:56 +00003506
Kate Stoneb9c1b512016-09-06 20:57:50 +00003507 if (log)
3508 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3509 ", signo=%i (0x%x), exit_status=%i)",
3510 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00003511
Kate Stoneb9c1b512016-09-06 20:57:50 +00003512 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3513 if (log)
3514 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3515 static_cast<void *>(process_sp.get()));
3516 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
Pavel Labath194357c2016-05-12 11:10:01 +00003517 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003518
Adrian Prantl05097242018-04-30 16:49:04 +00003519 // Sleep for a half a second to make sure our inferior process has time to
3520 // set its exit status before we set it incorrectly when both the debugserver
3521 // and the inferior process shut down.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003522 usleep(500000);
Adrian Prantl05097242018-04-30 16:49:04 +00003523 // If our process hasn't yet exited, debugserver might have died. If the
3524 // process did exit, then we are reaping it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003525 const StateType state = process_sp->GetState();
3526
3527 if (state != eStateInvalid && state != eStateUnloaded &&
3528 state != eStateExited && state != eStateDetached) {
3529 char error_str[1024];
3530 if (signo) {
3531 const char *signal_cstr =
3532 process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3533 if (signal_cstr)
3534 ::snprintf(error_str, sizeof(error_str),
3535 DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3536 else
3537 ::snprintf(error_str, sizeof(error_str),
3538 DEBUGSERVER_BASENAME " died with signal %i", signo);
3539 } else {
3540 ::snprintf(error_str, sizeof(error_str),
3541 DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3542 exit_status);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003543 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003544
3545 process_sp->SetExitStatus(-1, error_str);
3546 }
Adrian Prantl05097242018-04-30 16:49:04 +00003547 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3548 // longer has a debugserver instance
Kate Stoneb9c1b512016-09-06 20:57:50 +00003549 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3550 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003551}
3552
Kate Stoneb9c1b512016-09-06 20:57:50 +00003553void ProcessGDBRemote::KillDebugserverProcess() {
3554 m_gdb_comm.Disconnect();
3555 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3556 Host::Kill(m_debugserver_pid, SIGINT);
3557 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3558 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003559}
3560
Kate Stoneb9c1b512016-09-06 20:57:50 +00003561void ProcessGDBRemote::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003562 static llvm::once_flag g_once_flag;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003563
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003564 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003565 PluginManager::RegisterPlugin(GetPluginNameStatic(),
3566 GetPluginDescriptionStatic(), CreateInstance,
3567 DebuggerInitialize);
3568 });
Greg Clayton7f982402013-07-15 22:54:20 +00003569}
3570
Kate Stoneb9c1b512016-09-06 20:57:50 +00003571void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3572 if (!PluginManager::GetSettingForProcessPlugin(
3573 debugger, PluginProperties::GetSettingName())) {
3574 const bool is_global_setting = true;
3575 PluginManager::CreateSettingForProcessPlugin(
3576 debugger, GetGlobalPluginProperties()->GetValueProperties(),
3577 ConstString("Properties for the gdb-remote process plug-in."),
3578 is_global_setting);
3579 }
3580}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003581
Kate Stoneb9c1b512016-09-06 20:57:50 +00003582bool ProcessGDBRemote::StartAsyncThread() {
3583 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3584
3585 if (log)
3586 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3587
3588 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3589 if (!m_async_thread.IsJoinable()) {
3590 // Create a thread that watches our internal state and controls which
3591 // events make it to clients (into the DCProcess event queue).
3592
3593 m_async_thread =
3594 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>",
3595 ProcessGDBRemote::AsyncThread, this, NULL);
3596 } else if (log)
3597 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
3598 "already running.",
3599 __FUNCTION__);
3600
3601 return m_async_thread.IsJoinable();
3602}
3603
3604void ProcessGDBRemote::StopAsyncThread() {
3605 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3606
3607 if (log)
3608 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3609
3610 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3611 if (m_async_thread.IsJoinable()) {
3612 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3613
3614 // This will shut down the async thread.
3615 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3616
3617 // Stop the stdio thread
3618 m_async_thread.Join(nullptr);
3619 m_async_thread.Reset();
3620 } else if (log)
3621 log->Printf(
3622 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3623 __FUNCTION__);
3624}
3625
3626bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3627 // get the packet at a string
3628 const std::string &pkt = packet.GetStringRef();
3629 // skip %stop:
3630 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3631
3632 // pass as a thread stop info packet
3633 SetLastStopPacket(stop_info);
3634
3635 // check for more stop reasons
3636 HandleStopReplySequence();
3637
Adrian Prantl05097242018-04-30 16:49:04 +00003638 // if the process is stopped then we need to fake a resume so that we can
3639 // stop properly with the new break. This is possible due to
3640 // SetPrivateState() broadcasting the state change as a side effect.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003641 if (GetPrivateState() == lldb::StateType::eStateStopped) {
3642 SetPrivateState(lldb::StateType::eStateRunning);
3643 }
3644
3645 // since we have some stopped packets we can halt the process
3646 SetPrivateState(lldb::StateType::eStateStopped);
3647
3648 return true;
3649}
3650
3651thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3652 ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3653
3654 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3655 if (log)
3656 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3657 ") thread starting...",
3658 __FUNCTION__, arg, process->GetID());
3659
3660 EventSP event_sp;
3661 bool done = false;
3662 while (!done) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003663 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003664 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3665 ") listener.WaitForEvent (NULL, event_sp)...",
3666 __FUNCTION__, arg, process->GetID());
Pavel Labathd35031e12016-11-30 10:41:42 +00003667 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003668 const uint32_t event_type = event_sp->GetType();
3669 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
Pavel Labath50556852015-09-03 09:36:22 +00003670 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003671 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3672 ") Got an event of type: %d...",
3673 __FUNCTION__, arg, process->GetID(), event_type);
Pavel Labath50556852015-09-03 09:36:22 +00003674
Kate Stoneb9c1b512016-09-06 20:57:50 +00003675 switch (event_type) {
3676 case eBroadcastBitAsyncContinue: {
3677 const EventDataBytes *continue_packet =
3678 EventDataBytes::GetEventDataFromEvent(event_sp.get());
Pavel Labath50556852015-09-03 09:36:22 +00003679
Kate Stoneb9c1b512016-09-06 20:57:50 +00003680 if (continue_packet) {
3681 const char *continue_cstr =
3682 (const char *)continue_packet->GetBytes();
3683 const size_t continue_cstr_len = continue_packet->GetByteSize();
Pavel Labath50556852015-09-03 09:36:22 +00003684 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003685 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3686 ") got eBroadcastBitAsyncContinue: %s",
3687 __FUNCTION__, arg, process->GetID(), continue_cstr);
3688
3689 if (::strstr(continue_cstr, "vAttach") == NULL)
3690 process->SetPrivateState(eStateRunning);
3691 StringExtractorGDBRemote response;
3692
3693 // If in Non-Stop-Mode
3694 if (process->GetTarget().GetNonStopModeEnabled()) {
3695 // send the vCont packet
3696 if (!process->GetGDBRemote().SendvContPacket(
3697 llvm::StringRef(continue_cstr, continue_cstr_len),
3698 response)) {
3699 // Something went wrong
3700 done = true;
3701 break;
3702 }
3703 }
3704 // If in All-Stop-Mode
3705 else {
3706 StateType stop_state =
3707 process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3708 *process, *process->GetUnixSignals(),
3709 llvm::StringRef(continue_cstr, continue_cstr_len),
3710 response);
3711
3712 // We need to immediately clear the thread ID list so we are sure
Adrian Prantl05097242018-04-30 16:49:04 +00003713 // to get a valid list of threads. The thread ID list might be
3714 // contained within the "response", or the stop reply packet that
Kate Stoneb9c1b512016-09-06 20:57:50 +00003715 // caused the stop. So clear it now before we give the stop reply
Adrian Prantl05097242018-04-30 16:49:04 +00003716 // packet to the process using the
3717 // process->SetLastStopPacket()...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003718 process->ClearThreadIDList();
3719
3720 switch (stop_state) {
3721 case eStateStopped:
3722 case eStateCrashed:
3723 case eStateSuspended:
3724 process->SetLastStopPacket(response);
3725 process->SetPrivateState(stop_state);
3726 break;
3727
3728 case eStateExited: {
3729 process->SetLastStopPacket(response);
3730 process->ClearThreadIDList();
3731 response.SetFilePos(1);
3732
3733 int exit_status = response.GetHexU8();
3734 std::string desc_string;
3735 if (response.GetBytesLeft() > 0 &&
3736 response.GetChar('-') == ';') {
3737 llvm::StringRef desc_str;
3738 llvm::StringRef desc_token;
3739 while (response.GetNameColonValue(desc_token, desc_str)) {
3740 if (desc_token != "description")
3741 continue;
3742 StringExtractor extractor(desc_str);
3743 extractor.GetHexByteString(desc_string);
3744 }
3745 }
3746 process->SetExitStatus(exit_status, desc_string.c_str());
3747 done = true;
3748 break;
3749 }
3750 case eStateInvalid: {
3751 // Check to see if we were trying to attach and if we got back
3752 // the "E87" error code from debugserver -- this indicates that
3753 // the process is not debuggable. Return a slightly more
Adrian Prantl05097242018-04-30 16:49:04 +00003754 // helpful error message about why the attach failed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003755 if (::strstr(continue_cstr, "vAttach") != NULL &&
3756 response.GetError() == 0x87) {
3757 process->SetExitStatus(-1, "cannot attach to process due to "
3758 "System Integrity Protection");
Pavel Labathacebc432018-04-18 11:56:21 +00003759 } else if (::strstr(continue_cstr, "vAttach") != NULL &&
3760 response.GetStatus().Fail()) {
3761 process->SetExitStatus(-1, response.GetStatus().AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003762 } else {
3763 process->SetExitStatus(-1, "lost connection");
3764 }
3765 break;
3766 }
3767
3768 default:
3769 process->SetPrivateState(stop_state);
3770 break;
3771 } // switch(stop_state)
3772 } // else // if in All-stop-mode
3773 } // if (continue_packet)
3774 } // case eBroadcastBitAysncContinue
3775 break;
3776
3777 case eBroadcastBitAsyncThreadShouldExit:
3778 if (log)
3779 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3780 ") got eBroadcastBitAsyncThreadShouldExit...",
3781 __FUNCTION__, arg, process->GetID());
3782 done = true;
3783 break;
3784
3785 default:
3786 if (log)
3787 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3788 ") got unknown event 0x%8.8x",
3789 __FUNCTION__, arg, process->GetID(), event_type);
3790 done = true;
3791 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003792 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003793 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3794 switch (event_type) {
3795 case Communication::eBroadcastBitReadThreadDidExit:
3796 process->SetExitStatus(-1, "lost connection");
3797 done = true;
3798 break;
3799
3800 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3801 lldb_private::Event *event = event_sp.get();
3802 const EventDataBytes *continue_packet =
3803 EventDataBytes::GetEventDataFromEvent(event);
3804 StringExtractorGDBRemote notify(
3805 (const char *)continue_packet->GetBytes());
3806 // Hand this over to the process to handle
3807 process->HandleNotifyPacket(notify);
3808 break;
3809 }
3810
3811 default:
3812 if (log)
3813 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3814 ") got unknown event 0x%8.8x",
3815 __FUNCTION__, arg, process->GetID(), event_type);
3816 done = true;
3817 break;
3818 }
3819 }
3820 } else {
3821 if (log)
3822 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3823 ") listener.WaitForEvent (NULL, event_sp) => false",
3824 __FUNCTION__, arg, process->GetID());
3825 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003826 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003827 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003828
Kate Stoneb9c1b512016-09-06 20:57:50 +00003829 if (log)
3830 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3831 ") thread exiting...",
3832 __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003833
Kate Stoneb9c1b512016-09-06 20:57:50 +00003834 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003835}
3836
Kate Stoneb9c1b512016-09-06 20:57:50 +00003837// uint32_t
3838// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3839// &matches, std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00003840//{
Kate Stoneb9c1b512016-09-06 20:57:50 +00003841// // If we are planning to launch the debugserver remotely, then we need to
3842// fire up a debugserver
3843// // process and ask it for the list of processes. But if we are local, we
3844// can let the Host do it.
Greg Claytone996fd32011-03-08 22:40:15 +00003845// if (m_local_debugserver)
3846// {
3847// return Host::ListProcessesMatchingName (name, matches, pids);
3848// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003849// else
Greg Claytone996fd32011-03-08 22:40:15 +00003850// {
3851// // FIXME: Implement talking to the remote debugserver.
3852// return 0;
3853// }
3854//
3855//}
3856//
Kate Stoneb9c1b512016-09-06 20:57:50 +00003857bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3858 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3859 lldb::user_id_t break_loc_id) {
3860 // I don't think I have to do anything here, just make sure I notice the new
3861 // thread when it starts to
3862 // run so I can stop it if that's what I want to do.
3863 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3864 if (log)
3865 log->Printf("Hit New Thread Notification breakpoint.");
3866 return false;
Jim Ingham1c823b42011-01-22 01:33:44 +00003867}
3868
Zachary Turner97206d52017-05-12 04:51:55 +00003869Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003870 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3871 LLDB_LOG(log, "Check if need to update ignored signals");
3872
Adrian Prantl05097242018-04-30 16:49:04 +00003873 // QPassSignals package is not supported by the server, there is no way we
3874 // can ignore any signals on server side.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003875 if (!m_gdb_comm.GetQPassSignalsSupported())
Zachary Turner97206d52017-05-12 04:51:55 +00003876 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003877
3878 // No signals, nothing to send.
3879 if (m_unix_signals_sp == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00003880 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003881
3882 // Signals' version hasn't changed, no need to send anything.
3883 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3884 if (new_signals_version == m_last_signals_version) {
3885 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3886 m_last_signals_version);
Zachary Turner97206d52017-05-12 04:51:55 +00003887 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003888 }
3889
3890 auto signals_to_ignore =
3891 m_unix_signals_sp->GetFilteredSignals(false, false, false);
Zachary Turner97206d52017-05-12 04:51:55 +00003892 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003893
3894 LLDB_LOG(log,
3895 "Signals' version changed. old version={0}, new version={1}, "
3896 "signals ignored={2}, update result={3}",
3897 m_last_signals_version, new_signals_version,
3898 signals_to_ignore.size(), error);
3899
3900 if (error.Success())
3901 m_last_signals_version = new_signals_version;
3902
3903 return error;
3904}
3905
Kate Stoneb9c1b512016-09-06 20:57:50 +00003906bool ProcessGDBRemote::StartNoticingNewThreads() {
3907 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3908 if (m_thread_create_bp_sp) {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003909 if (log && log->GetVerbose())
Kate Stoneb9c1b512016-09-06 20:57:50 +00003910 log->Printf("Enabled noticing new thread breakpoint.");
3911 m_thread_create_bp_sp->SetEnabled(true);
3912 } else {
3913 PlatformSP platform_sp(GetTarget().GetPlatform());
3914 if (platform_sp) {
3915 m_thread_create_bp_sp =
3916 platform_sp->SetThreadCreationBreakpoint(GetTarget());
3917 if (m_thread_create_bp_sp) {
3918 if (log && log->GetVerbose())
3919 log->Printf(
3920 "Successfully created new thread notification breakpoint %i",
3921 m_thread_create_bp_sp->GetID());
3922 m_thread_create_bp_sp->SetCallback(
3923 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3924 } else {
3925 if (log)
3926 log->Printf("Failed to create new thread notification breakpoint.");
3927 }
Jason Molendaa3329782014-03-29 18:54:20 +00003928 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003929 }
3930 return m_thread_create_bp_sp.get() != NULL;
Jason Molendaa3329782014-03-29 18:54:20 +00003931}
3932
Kate Stoneb9c1b512016-09-06 20:57:50 +00003933bool ProcessGDBRemote::StopNoticingNewThreads() {
3934 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3935 if (log && log->GetVerbose())
3936 log->Printf("Disabling new thread notification breakpoint.");
3937
3938 if (m_thread_create_bp_sp)
3939 m_thread_create_bp_sp->SetEnabled(false);
3940
3941 return true;
3942}
3943
3944DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3945 if (m_dyld_ap.get() == NULL)
3946 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, NULL));
3947 return m_dyld_ap.get();
3948}
3949
Zachary Turner97206d52017-05-12 04:51:55 +00003950Status ProcessGDBRemote::SendEventData(const char *data) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003951 int return_value;
3952 bool was_supported;
3953
Zachary Turner97206d52017-05-12 04:51:55 +00003954 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003955
3956 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3957 if (return_value != 0) {
3958 if (!was_supported)
3959 error.SetErrorString("Sending events is not supported for this process.");
3960 else
3961 error.SetErrorStringWithFormat("Error sending event data: %d.",
3962 return_value);
3963 }
3964 return error;
3965}
3966
3967const DataBufferSP ProcessGDBRemote::GetAuxvData() {
3968 DataBufferSP buf;
3969 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3970 std::string response_string;
3971 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
3972 response_string) ==
3973 GDBRemoteCommunication::PacketResult::Success)
3974 buf.reset(new DataBufferHeap(response_string.c_str(),
3975 response_string.length()));
3976 }
3977 return buf;
Steve Pucci03904ac2014-03-04 23:18:46 +00003978}
3979
Jason Molenda705b1802014-06-13 02:37:02 +00003980StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00003981ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3982 StructuredData::ObjectSP object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00003983
Kate Stoneb9c1b512016-09-06 20:57:50 +00003984 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003985 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003986 SystemRuntime *runtime = GetSystemRuntime();
3987 if (runtime) {
3988 runtime->AddThreadExtendedInfoPacketHints(args_dict);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003989 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003990 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003991
Kate Stoneb9c1b512016-09-06 20:57:50 +00003992 StreamString packet;
3993 packet << "jThreadExtendedInfo:";
3994 args_dict->Dump(packet, false);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00003995
Kate Stoneb9c1b512016-09-06 20:57:50 +00003996 // FIXME the final character of a JSON dictionary, '}', is the escape
3997 // character in gdb-remote binary mode. lldb currently doesn't escape
Adrian Prantl05097242018-04-30 16:49:04 +00003998 // these characters in its packet output -- so we add the quoted version of
3999 // the } character here manually in case we talk to a debugserver which un-
4000 // escapes the characters at packet read time.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004001 packet << (char)(0x7d ^ 0x20);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004002
Kate Stoneb9c1b512016-09-06 20:57:50 +00004003 StringExtractorGDBRemote response;
4004 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004005 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4006 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004007 GDBRemoteCommunication::PacketResult::Success) {
4008 StringExtractorGDBRemote::ResponseType response_type =
4009 response.GetResponseType();
4010 if (response_type == StringExtractorGDBRemote::eResponse) {
4011 if (!response.Empty()) {
4012 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda705b1802014-06-13 02:37:02 +00004013 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004014 }
Jason Molenda705b1802014-06-13 02:37:02 +00004015 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004016 }
4017 return object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00004018}
4019
Kate Stoneb9c1b512016-09-06 20:57:50 +00004020StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4021 lldb::addr_t image_list_address, lldb::addr_t image_count) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004022
Kate Stoneb9c1b512016-09-06 20:57:50 +00004023 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4024 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4025 image_list_address);
4026 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004027
Kate Stoneb9c1b512016-09-06 20:57:50 +00004028 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4029}
4030
4031StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
4032 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4033
4034 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4035
4036 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4037}
4038
4039StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4040 const std::vector<lldb::addr_t> &load_addresses) {
4041 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4042 StructuredData::ArraySP addresses(new StructuredData::Array);
4043
4044 for (auto addr : load_addresses) {
4045 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
4046 addresses->AddItem(addr_sp);
4047 }
4048
4049 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4050
4051 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4052}
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004053
Jason Molenda37397352016-07-22 00:17:55 +00004054StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004055ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
4056 StructuredData::ObjectSP args_dict) {
4057 StructuredData::ObjectSP object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00004058
Kate Stoneb9c1b512016-09-06 20:57:50 +00004059 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4060 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +00004061 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
4062 std::chrono::seconds(10));
Jason Molenda37397352016-07-22 00:17:55 +00004063
Kate Stoneb9c1b512016-09-06 20:57:50 +00004064 StreamString packet;
4065 packet << "jGetLoadedDynamicLibrariesInfos:";
4066 args_dict->Dump(packet, false);
Jason Molenda37397352016-07-22 00:17:55 +00004067
Kate Stoneb9c1b512016-09-06 20:57:50 +00004068 // FIXME the final character of a JSON dictionary, '}', is the escape
4069 // character in gdb-remote binary mode. lldb currently doesn't escape
Adrian Prantl05097242018-04-30 16:49:04 +00004070 // these characters in its packet output -- so we add the quoted version of
4071 // the } character here manually in case we talk to a debugserver which un-
4072 // escapes the characters at packet read time.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004073 packet << (char)(0x7d ^ 0x20);
4074
4075 StringExtractorGDBRemote response;
4076 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004077 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4078 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004079 GDBRemoteCommunication::PacketResult::Success) {
4080 StringExtractorGDBRemote::ResponseType response_type =
4081 response.GetResponseType();
4082 if (response_type == StringExtractorGDBRemote::eResponse) {
4083 if (!response.Empty()) {
4084 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda37397352016-07-22 00:17:55 +00004085 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004086 }
Jason Molenda37397352016-07-22 00:17:55 +00004087 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004088 }
4089 return object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00004090}
4091
Kate Stoneb9c1b512016-09-06 20:57:50 +00004092StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
4093 StructuredData::ObjectSP object_sp;
4094 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4095
4096 if (m_gdb_comm.GetSharedCacheInfoSupported()) {
4097 StreamString packet;
4098 packet << "jGetSharedCacheInfo:";
4099 args_dict->Dump(packet, false);
4100
4101 // FIXME the final character of a JSON dictionary, '}', is the escape
4102 // character in gdb-remote binary mode. lldb currently doesn't escape
Adrian Prantl05097242018-04-30 16:49:04 +00004103 // these characters in its packet output -- so we add the quoted version of
4104 // the } character here manually in case we talk to a debugserver which un-
4105 // escapes the characters at packet read time.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004106 packet << (char)(0x7d ^ 0x20);
4107
4108 StringExtractorGDBRemote response;
4109 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004110 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4111 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004112 GDBRemoteCommunication::PacketResult::Success) {
4113 StringExtractorGDBRemote::ResponseType response_type =
4114 response.GetResponseType();
4115 if (response_type == StringExtractorGDBRemote::eResponse) {
4116 if (!response.Empty()) {
4117 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4118 }
4119 }
4120 }
4121 }
4122 return object_sp;
4123}
4124
Zachary Turner97206d52017-05-12 04:51:55 +00004125Status ProcessGDBRemote::ConfigureStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004126 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
4127 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
Todd Fiala75930012016-08-19 04:21:48 +00004128}
Jason Molenda37397352016-07-22 00:17:55 +00004129
Adrian Prantl05097242018-04-30 16:49:04 +00004130// Establish the largest memory read/write payloads we should use. If the
4131// remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004132//
Adrian Prantl05097242018-04-30 16:49:04 +00004133// If the remote stub's max packet size is crazy large, use a reasonable
4134// largeish default.
Jason Molenda6076bf42014-05-06 04:34:52 +00004135//
Adrian Prantl05097242018-04-30 16:49:04 +00004136// If the remote stub doesn't advertise a max packet size, use a conservative
4137// default.
Jason Molenda6076bf42014-05-06 04:34:52 +00004138
Kate Stoneb9c1b512016-09-06 20:57:50 +00004139void ProcessGDBRemote::GetMaxMemorySize() {
4140 const uint64_t reasonable_largeish_default = 128 * 1024;
4141 const uint64_t conservative_default = 512;
Jason Molenda6076bf42014-05-06 04:34:52 +00004142
Kate Stoneb9c1b512016-09-06 20:57:50 +00004143 if (m_max_memory_size == 0) {
4144 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4145 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4146 // Save the stub's claimed maximum packet size
4147 m_remote_stub_max_memory_size = stub_max_size;
Jason Molenda6076bf42014-05-06 04:34:52 +00004148
Adrian Prantl05097242018-04-30 16:49:04 +00004149 // Even if the stub says it can support ginormous packets, don't exceed
4150 // our reasonable largeish default packet size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004151 if (stub_max_size > reasonable_largeish_default) {
4152 stub_max_size = reasonable_largeish_default;
4153 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004154
Adrian Prantl05097242018-04-30 16:49:04 +00004155 // Memory packet have other overheads too like Maddr,size:#NN Instead of
4156 // calculating the bytes taken by size and addr every time, we take a
4157 // maximum guess here.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00004158 if (stub_max_size > 70)
4159 stub_max_size -= 32 + 32 + 6;
4160 else {
4161 // In unlikely scenario that max packet size is less then 70, we will
4162 // hope that data being written is small enough to fit.
4163 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4164 GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4165 if (log)
4166 log->Warning("Packet size is too small. "
4167 "LLDB may face problems while writing memory");
4168 }
4169
Kate Stoneb9c1b512016-09-06 20:57:50 +00004170 m_max_memory_size = stub_max_size;
4171 } else {
4172 m_max_memory_size = conservative_default;
Jason Molenda6076bf42014-05-06 04:34:52 +00004173 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004174 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004175}
4176
Kate Stoneb9c1b512016-09-06 20:57:50 +00004177void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4178 uint64_t user_specified_max) {
4179 if (user_specified_max != 0) {
4180 GetMaxMemorySize();
Jason Molenda6076bf42014-05-06 04:34:52 +00004181
Kate Stoneb9c1b512016-09-06 20:57:50 +00004182 if (m_remote_stub_max_memory_size != 0) {
4183 if (m_remote_stub_max_memory_size < user_specified_max) {
4184 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4185 // packet size too
4186 // big, go as big
4187 // as the remote stub says we can go.
4188 } else {
4189 m_max_memory_size = user_specified_max; // user's packet size is good
4190 }
4191 } else {
4192 m_max_memory_size =
4193 user_specified_max; // user's packet size is probably fine
Jason Molenda6076bf42014-05-06 04:34:52 +00004194 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004195 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004196}
4197
Kate Stoneb9c1b512016-09-06 20:57:50 +00004198bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4199 const ArchSpec &arch,
4200 ModuleSpec &module_spec) {
4201 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004202
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004203 const ModuleCacheKey key(module_file_spec.GetPath(),
4204 arch.GetTriple().getTriple());
4205 auto cached = m_cached_module_specs.find(key);
4206 if (cached != m_cached_module_specs.end()) {
4207 module_spec = cached->second;
4208 return bool(module_spec);
4209 }
4210
Kate Stoneb9c1b512016-09-06 20:57:50 +00004211 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004212 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004213 log->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4214 __FUNCTION__, module_file_spec.GetPath().c_str(),
4215 arch.GetTriple().getTriple().c_str());
4216 return false;
4217 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004218
Kate Stoneb9c1b512016-09-06 20:57:50 +00004219 if (log) {
4220 StreamString stream;
4221 module_spec.Dump(stream);
4222 log->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4223 __FUNCTION__, module_file_spec.GetPath().c_str(),
Zachary Turnerc1564272016-11-16 21:15:24 +00004224 arch.GetTriple().getTriple().c_str(), stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004225 }
4226
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004227 m_cached_module_specs[key] = module_spec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004228 return true;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004229}
4230
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004231void ProcessGDBRemote::PrefetchModuleSpecs(
4232 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4233 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4234 if (module_specs) {
4235 for (const FileSpec &spec : module_file_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004236 m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4237 triple.getTriple())] = ModuleSpec();
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004238 for (const ModuleSpec &spec : *module_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004239 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4240 triple.getTriple())] = spec;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004241 }
4242}
4243
Kate Stoneb9c1b512016-09-06 20:57:50 +00004244bool ProcessGDBRemote::GetHostOSVersion(uint32_t &major, uint32_t &minor,
4245 uint32_t &update) {
4246 if (m_gdb_comm.GetOSVersion(major, minor, update))
4247 return true;
Adrian Prantl05097242018-04-30 16:49:04 +00004248 // We failed to get the host OS version, defer to the base implementation to
4249 // correctly invalidate the arguments.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004250 return Process::GetHostOSVersion(major, minor, update);
Jim Ingham13c30d22015-11-05 22:33:17 +00004251}
4252
Colin Rileyc3c95b22015-04-16 15:51:33 +00004253namespace {
4254
4255typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004256
4257typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004258struct RegisterSetInfo {
4259 ConstString name;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004260};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004261
Greg Claytond04f0ed2015-05-26 18:00:51 +00004262typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004263
Kate Stoneb9c1b512016-09-06 20:57:50 +00004264struct GdbServerTargetInfo {
4265 std::string arch;
4266 std::string osabi;
4267 stringVec includes;
4268 RegisterSetMap reg_set_map;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004269};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004270
Kate Stoneb9c1b512016-09-06 20:57:50 +00004271bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4272 GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4273 uint32_t &cur_reg_num, uint32_t &reg_offset) {
4274 if (!feature_node)
4275 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004276
Kate Stoneb9c1b512016-09-06 20:57:50 +00004277 feature_node.ForEachChildElementWithName(
4278 "reg", [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset,
4279 &abi_sp](const XMLNode &reg_node) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004280 std::string gdb_group;
4281 std::string gdb_type;
4282 ConstString reg_name;
4283 ConstString alt_name;
4284 ConstString set_name;
4285 std::vector<uint32_t> value_regs;
4286 std::vector<uint32_t> invalidate_regs;
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004287 std::vector<uint8_t> dwarf_opcode_bytes;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004288 bool encoding_set = false;
4289 bool format_set = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004290 RegisterInfo reg_info = {
4291 NULL, // Name
4292 NULL, // Alt name
4293 0, // byte size
4294 reg_offset, // offset
4295 eEncodingUint, // encoding
4296 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004297 {
Jason Molendabf67a302015-09-01 05:17:01 +00004298 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004299 LLDB_INVALID_REGNUM, // DWARF reg num
4300 LLDB_INVALID_REGNUM, // generic reg num
Kate Stoneb9c1b512016-09-06 20:57:50 +00004301 cur_reg_num, // process plugin reg num
4302 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004303 },
4304 NULL,
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004305 NULL,
Kate Stoneb9c1b512016-09-06 20:57:50 +00004306 NULL, // Dwarf Expression opcode bytes pointer
4307 0 // Dwarf Expression opcode bytes length
Greg Claytond04f0ed2015-05-26 18:00:51 +00004308 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004309
Kate Stoneb9c1b512016-09-06 20:57:50 +00004310 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4311 &reg_name, &alt_name, &set_name, &value_regs,
4312 &invalidate_regs, &encoding_set, &format_set,
Zachary Turner3bc714b2017-03-02 00:05:25 +00004313 &reg_info, &reg_offset, &dwarf_opcode_bytes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004314 const llvm::StringRef &name,
4315 const llvm::StringRef &value) -> bool {
4316 if (name == "name") {
4317 reg_name.SetString(value);
4318 } else if (name == "bitsize") {
4319 reg_info.byte_size =
4320 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4321 } else if (name == "type") {
4322 gdb_type = value.str();
4323 } else if (name == "group") {
4324 gdb_group = value.str();
4325 } else if (name == "regnum") {
4326 const uint32_t regnum =
4327 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4328 if (regnum != LLDB_INVALID_REGNUM) {
4329 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004330 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004331 } else if (name == "offset") {
4332 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4333 } else if (name == "altname") {
4334 alt_name.SetString(value);
4335 } else if (name == "encoding") {
4336 encoding_set = true;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004337 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004338 } else if (name == "format") {
4339 format_set = true;
4340 Format format = eFormatInvalid;
Pavel Labath47cbf4a2018-04-10 09:03:59 +00004341 if (OptionArgParser::ToFormat(value.data(), format, NULL).Success())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004342 reg_info.format = format;
4343 else if (value == "vector-sint8")
4344 reg_info.format = eFormatVectorOfSInt8;
4345 else if (value == "vector-uint8")
4346 reg_info.format = eFormatVectorOfUInt8;
4347 else if (value == "vector-sint16")
4348 reg_info.format = eFormatVectorOfSInt16;
4349 else if (value == "vector-uint16")
4350 reg_info.format = eFormatVectorOfUInt16;
4351 else if (value == "vector-sint32")
4352 reg_info.format = eFormatVectorOfSInt32;
4353 else if (value == "vector-uint32")
4354 reg_info.format = eFormatVectorOfUInt32;
4355 else if (value == "vector-float32")
4356 reg_info.format = eFormatVectorOfFloat32;
Valentina Giusticda0ae42016-09-08 14:16:45 +00004357 else if (value == "vector-uint64")
4358 reg_info.format = eFormatVectorOfUInt64;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004359 else if (value == "vector-uint128")
4360 reg_info.format = eFormatVectorOfUInt128;
4361 } else if (name == "group_id") {
4362 const uint32_t set_id =
4363 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4364 RegisterSetMap::const_iterator pos =
4365 target_info.reg_set_map.find(set_id);
4366 if (pos != target_info.reg_set_map.end())
4367 set_name = pos->second.name;
4368 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4369 reg_info.kinds[eRegisterKindEHFrame] =
4370 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4371 } else if (name == "dwarf_regnum") {
4372 reg_info.kinds[eRegisterKindDWARF] =
4373 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4374 } else if (name == "generic") {
4375 reg_info.kinds[eRegisterKindGeneric] =
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004376 Args::StringToGenericRegister(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004377 } else if (name == "value_regnums") {
4378 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4379 } else if (name == "invalidate_regnums") {
4380 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4381 } else if (name == "dynamic_size_dwarf_expr_bytes") {
4382 StringExtractor opcode_extractor;
4383 std::string opcode_string = value.str();
4384 size_t dwarf_opcode_len = opcode_string.length() / 2;
4385 assert(dwarf_opcode_len > 0);
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004386
Kate Stoneb9c1b512016-09-06 20:57:50 +00004387 dwarf_opcode_bytes.resize(dwarf_opcode_len);
4388 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4389 opcode_extractor.GetStringRef().swap(opcode_string);
4390 uint32_t ret_val =
4391 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4392 assert(dwarf_opcode_len == ret_val);
Hafiz Abid Qadeer05008ca2017-01-19 15:11:01 +00004393 UNUSED_IF_ASSERT_DISABLED(ret_val);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004394 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4395 } else {
4396 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4397 }
4398 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004399 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004400
Kate Stoneb9c1b512016-09-06 20:57:50 +00004401 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4402 if (gdb_type.find("int") == 0) {
4403 reg_info.format = eFormatHex;
4404 reg_info.encoding = eEncodingUint;
4405 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4406 reg_info.format = eFormatAddressInfo;
4407 reg_info.encoding = eEncodingUint;
4408 } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4409 reg_info.format = eFormatFloat;
4410 reg_info.encoding = eEncodingIEEE754;
4411 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004412 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004413
Kate Stoneb9c1b512016-09-06 20:57:50 +00004414 // Only update the register set name if we didn't get a "reg_set"
Adrian Prantl05097242018-04-30 16:49:04 +00004415 // attribute. "set_name" will be empty if we didn't have a "reg_set"
Kate Stoneb9c1b512016-09-06 20:57:50 +00004416 // attribute.
Greg Claytond04f0ed2015-05-26 18:00:51 +00004417 if (!set_name && !gdb_group.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004418 set_name.SetCString(gdb_group.c_str());
Ed Maste81b4c5f2016-01-04 01:43:47 +00004419
Greg Claytond04f0ed2015-05-26 18:00:51 +00004420 reg_info.byte_offset = reg_offset;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004421 assert(reg_info.byte_size != 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004422 reg_offset += reg_info.byte_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004423 if (!value_regs.empty()) {
4424 value_regs.push_back(LLDB_INVALID_REGNUM);
4425 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004426 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004427 if (!invalidate_regs.empty()) {
4428 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4429 reg_info.invalidate_regs = invalidate_regs.data();
Greg Claytond04f0ed2015-05-26 18:00:51 +00004430 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004431
Jason Molenda63bd0db2015-09-15 23:20:34 +00004432 ++cur_reg_num;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004433 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004434 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004435
Greg Claytond04f0ed2015-05-26 18:00:51 +00004436 return true; // Keep iterating through all "reg" elements
Kate Stoneb9c1b512016-09-06 20:57:50 +00004437 });
4438 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004439}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004440
Eugene Zelenko0722f082015-10-24 01:28:05 +00004441} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004442
Adrian Prantl05097242018-04-30 16:49:04 +00004443// query the target of gdb-remote for extended target information return:
4444// 'true' on success
Colin Rileyc3c95b22015-04-16 15:51:33 +00004445// 'false' on failure
Kate Stoneb9c1b512016-09-06 20:57:50 +00004446bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4447 // Make sure LLDB has an XML parser it can use first
4448 if (!XMLDocument::XMLEnabled())
4449 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004450
Kate Stoneb9c1b512016-09-06 20:57:50 +00004451 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004452
Kate Stoneb9c1b512016-09-06 20:57:50 +00004453 GDBRemoteCommunicationClient &comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004454
Kate Stoneb9c1b512016-09-06 20:57:50 +00004455 // check that we have extended feature read support
4456 if (!comm.GetQXferFeaturesReadSupported())
4457 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004458
Kate Stoneb9c1b512016-09-06 20:57:50 +00004459 // request the target xml file
4460 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004461 lldb_private::Status lldberr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004462 if (!comm.ReadExtFeature(ConstString("features"), ConstString("target.xml"),
4463 raw, lldberr)) {
4464 return false;
4465 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004466
Kate Stoneb9c1b512016-09-06 20:57:50 +00004467 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004468
Kate Stoneb9c1b512016-09-06 20:57:50 +00004469 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) {
4470 GdbServerTargetInfo target_info;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004471
Kate Stoneb9c1b512016-09-06 20:57:50 +00004472 XMLNode target_node = xml_document.GetRootElement("target");
4473 if (target_node) {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004474 std::vector<XMLNode> feature_nodes;
4475 target_node.ForEachChildElement([&target_info, &feature_nodes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004476 const XMLNode &node) -> bool {
4477 llvm::StringRef name = node.GetName();
4478 if (name == "architecture") {
4479 node.GetElementText(target_info.arch);
4480 } else if (name == "osabi") {
4481 node.GetElementText(target_info.osabi);
4482 } else if (name == "xi:include" || name == "include") {
4483 llvm::StringRef href = node.GetAttributeValue("href");
4484 if (!href.empty())
4485 target_info.includes.push_back(href.str());
4486 } else if (name == "feature") {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004487 feature_nodes.push_back(node);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004488 } else if (name == "groups") {
4489 node.ForEachChildElementWithName(
4490 "group", [&target_info](const XMLNode &node) -> bool {
4491 uint32_t set_id = UINT32_MAX;
4492 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004493
Kate Stoneb9c1b512016-09-06 20:57:50 +00004494 node.ForEachAttribute(
4495 [&set_id, &set_info](const llvm::StringRef &name,
4496 const llvm::StringRef &value) -> bool {
4497 if (name == "id")
4498 set_id = StringConvert::ToUInt32(value.data(),
4499 UINT32_MAX, 0);
4500 if (name == "name")
4501 set_info.name = ConstString(value);
4502 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004503 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004504
Kate Stoneb9c1b512016-09-06 20:57:50 +00004505 if (set_id != UINT32_MAX)
4506 target_info.reg_set_map[set_id] = set_info;
4507 return true; // Keep iterating through all "group" elements
4508 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004509 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004510 return true; // Keep iterating through all children of the target_node
4511 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004512
Jason Molendac4dd04c2018-01-12 01:16:13 +00004513 // If the target.xml includes an architecture entry like
4514 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4515 // <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board)
4516 // use that if we don't have anything better.
4517 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4518 if (target_info.arch == "i386:x86-64")
4519 {
4520 // We don't have any information about vendor or OS.
4521 arch_to_use.SetTriple("x86_64--");
4522 GetTarget().MergeArchitecture(arch_to_use);
4523 }
4524 }
4525
Kate Stoneb9c1b512016-09-06 20:57:50 +00004526 // Initialize these outside of ParseRegisters, since they should not be
4527 // reset inside each include feature
4528 uint32_t cur_reg_num = 0;
4529 uint32_t reg_offset = 0;
4530
Adrian Prantl05097242018-04-30 16:49:04 +00004531 // Don't use Process::GetABI, this code gets called from DidAttach, and
4532 // in that context we haven't set the Target's architecture yet, so the
4533 // ABI is also potentially incorrect.
Jason Molenda43294c92017-06-29 02:57:03 +00004534 ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004535 for (auto &feature_node : feature_nodes) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004536 ParseRegisters(feature_node, target_info, this->m_register_info,
4537 abi_to_use_sp, cur_reg_num, reg_offset);
4538 }
4539
4540 for (const auto &include : target_info.includes) {
4541 // request register file
4542 std::string xml_data;
4543 if (!comm.ReadExtFeature(ConstString("features"), ConstString(include),
4544 xml_data, lldberr))
4545 continue;
4546
4547 XMLDocument include_xml_document;
4548 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(),
4549 include.c_str());
4550 XMLNode include_feature_node =
4551 include_xml_document.GetRootElement("feature");
4552 if (include_feature_node) {
4553 ParseRegisters(include_feature_node, target_info,
4554 this->m_register_info, abi_to_use_sp, cur_reg_num,
4555 reg_offset);
4556 }
4557 }
4558 this->m_register_info.Finalize(arch_to_use);
4559 }
4560 }
4561
4562 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004563}
4564
Zachary Turner97206d52017-05-12 04:51:55 +00004565Status ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004566 // Make sure LLDB has an XML parser it can use first
4567 if (!XMLDocument::XMLEnabled())
Zachary Turner97206d52017-05-12 04:51:55 +00004568 return Status(0, ErrorType::eErrorTypeGeneric);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004569
Kate Stoneb9c1b512016-09-06 20:57:50 +00004570 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
4571 if (log)
4572 log->Printf("ProcessGDBRemote::%s", __FUNCTION__);
4573
4574 GDBRemoteCommunicationClient &comm = m_gdb_comm;
4575
4576 // check that we have extended feature read support
4577 if (comm.GetQXferLibrariesSVR4ReadSupported()) {
4578 list.clear();
4579
4580 // request the loaded library list
4581 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004582 lldb_private::Status lldberr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004583
4584 if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4585 raw, lldberr))
Zachary Turner97206d52017-05-12 04:51:55 +00004586 return Status(0, ErrorType::eErrorTypeGeneric);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004587
4588 // parse the xml file in memory
Aidan Doddsc0c83852015-05-08 09:36:31 +00004589 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004590 log->Printf("parsing: %s", raw.c_str());
4591 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004592
Kate Stoneb9c1b512016-09-06 20:57:50 +00004593 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Zachary Turner97206d52017-05-12 04:51:55 +00004594 return Status(0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004595
Kate Stoneb9c1b512016-09-06 20:57:50 +00004596 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4597 if (!root_element)
Zachary Turner97206d52017-05-12 04:51:55 +00004598 return Status();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004599
Kate Stoneb9c1b512016-09-06 20:57:50 +00004600 // main link map structure
4601 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4602 if (!main_lm.empty()) {
4603 list.m_link_map =
4604 StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4605 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004606
Kate Stoneb9c1b512016-09-06 20:57:50 +00004607 root_element.ForEachChildElementWithName(
4608 "library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004609
Kate Stoneb9c1b512016-09-06 20:57:50 +00004610 LoadedModuleInfoList::LoadedModuleInfo module;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004611
Kate Stoneb9c1b512016-09-06 20:57:50 +00004612 library.ForEachAttribute(
Zachary Turner3bc714b2017-03-02 00:05:25 +00004613 [&module](const llvm::StringRef &name,
4614 const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004615
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004616 if (name == "name")
Kate Stoneb9c1b512016-09-06 20:57:50 +00004617 module.set_name(value.str());
4618 else if (name == "lm") {
4619 // the address of the link_map struct.
4620 module.set_link_map(StringConvert::ToUInt64(
4621 value.data(), LLDB_INVALID_ADDRESS, 0));
4622 } else if (name == "l_addr") {
4623 // the displacement as read from the field 'l_addr' of the
4624 // link_map struct.
4625 module.set_base(StringConvert::ToUInt64(
4626 value.data(), LLDB_INVALID_ADDRESS, 0));
4627 // base address is always a displacement, not an absolute
4628 // value.
4629 module.set_base_is_offset(true);
4630 } else if (name == "l_ld") {
4631 // the memory address of the libraries PT_DYAMIC section.
4632 module.set_dynamic(StringConvert::ToUInt64(
4633 value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004634 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004635
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004636 return true; // Keep iterating over all properties of "library"
Kate Stoneb9c1b512016-09-06 20:57:50 +00004637 });
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004638
Kate Stoneb9c1b512016-09-06 20:57:50 +00004639 if (log) {
4640 std::string name;
4641 lldb::addr_t lm = 0, base = 0, ld = 0;
4642 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004643
Kate Stoneb9c1b512016-09-06 20:57:50 +00004644 module.get_name(name);
4645 module.get_link_map(lm);
4646 module.get_base(base);
4647 module.get_base_is_offset(base_is_offset);
4648 module.get_dynamic(ld);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004649
Kate Stoneb9c1b512016-09-06 20:57:50 +00004650 log->Printf("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4651 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4652 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4653 name.c_str());
4654 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004655
Kate Stoneb9c1b512016-09-06 20:57:50 +00004656 list.add(module);
4657 return true; // Keep iterating over all "library" elements in the root
4658 // node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004659 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004660
Kate Stoneb9c1b512016-09-06 20:57:50 +00004661 if (log)
4662 log->Printf("found %" PRId32 " modules in total",
4663 (int)list.m_list.size());
4664 } else if (comm.GetQXferLibrariesReadSupported()) {
4665 list.clear();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004666
Kate Stoneb9c1b512016-09-06 20:57:50 +00004667 // request the loaded library list
4668 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004669 lldb_private::Status lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004670
Kate Stoneb9c1b512016-09-06 20:57:50 +00004671 if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4672 lldberr))
Zachary Turner97206d52017-05-12 04:51:55 +00004673 return Status(0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004674
Kate Stoneb9c1b512016-09-06 20:57:50 +00004675 if (log)
4676 log->Printf("parsing: %s", raw.c_str());
4677 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004678
Kate Stoneb9c1b512016-09-06 20:57:50 +00004679 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Zachary Turner97206d52017-05-12 04:51:55 +00004680 return Status(0, ErrorType::eErrorTypeGeneric);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004681
Kate Stoneb9c1b512016-09-06 20:57:50 +00004682 XMLNode root_element = doc.GetRootElement("library-list");
4683 if (!root_element)
Zachary Turner97206d52017-05-12 04:51:55 +00004684 return Status();
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004685
Kate Stoneb9c1b512016-09-06 20:57:50 +00004686 root_element.ForEachChildElementWithName(
4687 "library", [log, &list](const XMLNode &library) -> bool {
4688 LoadedModuleInfoList::LoadedModuleInfo module;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004689
Kate Stoneb9c1b512016-09-06 20:57:50 +00004690 llvm::StringRef name = library.GetAttributeValue("name");
4691 module.set_name(name.str());
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004692
Kate Stoneb9c1b512016-09-06 20:57:50 +00004693 // The base address of a given library will be the address of its
4694 // first section. Most remotes send only one section for Windows
4695 // targets for example.
4696 const XMLNode &section =
4697 library.FindFirstChildElementWithName("section");
4698 llvm::StringRef address = section.GetAttributeValue("address");
4699 module.set_base(
4700 StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4701 // These addresses are absolute values.
4702 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004703
Kate Stoneb9c1b512016-09-06 20:57:50 +00004704 if (log) {
4705 std::string name;
4706 lldb::addr_t base = 0;
4707 bool base_is_offset;
4708 module.get_name(name);
4709 module.get_base(base);
4710 module.get_base_is_offset(base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004711
Kate Stoneb9c1b512016-09-06 20:57:50 +00004712 log->Printf("found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4713 (base_is_offset ? "offset" : "absolute"), name.c_str());
4714 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004715
Kate Stoneb9c1b512016-09-06 20:57:50 +00004716 list.add(module);
4717 return true; // Keep iterating over all "library" elements in the root
4718 // node
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004719 });
4720
Kate Stoneb9c1b512016-09-06 20:57:50 +00004721 if (log)
4722 log->Printf("found %" PRId32 " modules in total",
4723 (int)list.m_list.size());
4724 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00004725 return Status(0, ErrorType::eErrorTypeGeneric);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004726 }
4727
Zachary Turner97206d52017-05-12 04:51:55 +00004728 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004729}
4730
4731lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4732 lldb::addr_t link_map,
4733 lldb::addr_t base_addr,
4734 bool value_is_offset) {
4735 DynamicLoader *loader = GetDynamicLoader();
4736 if (!loader)
4737 return nullptr;
4738
4739 return loader->LoadModuleAtAddress(file, link_map, base_addr,
4740 value_is_offset);
4741}
4742
4743size_t ProcessGDBRemote::LoadModules(LoadedModuleInfoList &module_list) {
4744 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4745
4746 // request a list of loaded libraries from GDBServer
4747 if (GetLoadedModuleList(module_list).Fail())
4748 return 0;
4749
4750 // get a list of all the modules
4751 ModuleList new_modules;
4752
4753 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list.m_list) {
4754 std::string mod_name;
4755 lldb::addr_t mod_base;
4756 lldb::addr_t link_map;
4757 bool mod_base_is_offset;
4758
4759 bool valid = true;
4760 valid &= modInfo.get_name(mod_name);
4761 valid &= modInfo.get_base(mod_base);
4762 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4763 if (!valid)
4764 continue;
4765
4766 if (!modInfo.get_link_map(link_map))
4767 link_map = LLDB_INVALID_ADDRESS;
4768
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00004769 FileSpec file(mod_name, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004770 lldb::ModuleSP module_sp =
4771 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4772
4773 if (module_sp.get())
4774 new_modules.Append(module_sp);
4775 }
4776
4777 if (new_modules.GetSize() > 0) {
4778 ModuleList removed_modules;
4779 Target &target = GetTarget();
4780 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4781
4782 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4783 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4784
4785 bool found = false;
4786 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4787 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4788 found = true;
4789 }
4790
4791 // The main executable will never be included in libraries-svr4, don't
4792 // remove it
4793 if (!found &&
4794 loaded_module.get() != target.GetExecutableModulePointer()) {
4795 removed_modules.Append(loaded_module);
4796 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004797 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004798
Kate Stoneb9c1b512016-09-06 20:57:50 +00004799 loaded_modules.Remove(removed_modules);
4800 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4801
4802 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4803 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4804 if (!obj)
4805 return true;
4806
4807 if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4808 return true;
4809
4810 lldb::ModuleSP module_copy_sp = module_sp;
4811 target.SetExecutableModule(module_copy_sp, false);
4812 return false;
4813 });
4814
4815 loaded_modules.AppendIfNeeded(new_modules);
4816 m_process->GetTarget().ModulesDidLoad(new_modules);
4817 }
4818
4819 return new_modules.GetSize();
4820}
4821
4822size_t ProcessGDBRemote::LoadModules() {
4823 LoadedModuleInfoList module_list;
4824 return LoadModules(module_list);
4825}
4826
Zachary Turner97206d52017-05-12 04:51:55 +00004827Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4828 bool &is_loaded,
4829 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004830 is_loaded = false;
4831 load_addr = LLDB_INVALID_ADDRESS;
4832
4833 std::string file_path = file.GetPath(false);
4834 if (file_path.empty())
Zachary Turner97206d52017-05-12 04:51:55 +00004835 return Status("Empty file name specified");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004836
4837 StreamString packet;
4838 packet.PutCString("qFileLoadAddress:");
4839 packet.PutCStringAsRawHex8(file_path.c_str());
4840
4841 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004842 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4843 false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00004844 GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00004845 return Status("Sending qFileLoadAddress packet failed");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004846
4847 if (response.IsErrorResponse()) {
4848 if (response.GetError() == 1) {
4849 // The file is not loaded into the inferior
4850 is_loaded = false;
4851 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00004852 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004853 }
4854
Zachary Turner97206d52017-05-12 04:51:55 +00004855 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004856 "Fetching file load address from remote server returned an error");
4857 }
4858
4859 if (response.IsNormalResponse()) {
4860 is_loaded = true;
4861 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
Zachary Turner97206d52017-05-12 04:51:55 +00004862 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004863 }
4864
Zachary Turner97206d52017-05-12 04:51:55 +00004865 return Status(
4866 "Unknown error happened during sending the load address packet");
Aidan Doddsc0c83852015-05-08 09:36:31 +00004867}
4868
Kate Stoneb9c1b512016-09-06 20:57:50 +00004869void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4870 // We must call the lldb_private::Process::ModulesDidLoad () first before we
4871 // do anything
4872 Process::ModulesDidLoad(module_list);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004873
Adrian Prantl05097242018-04-30 16:49:04 +00004874 // After loading shared libraries, we can ask our remote GDB server if it
4875 // needs any symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004876 m_gdb_comm.ServeSymbolLookups(this);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004877}
4878
Kate Stoneb9c1b512016-09-06 20:57:50 +00004879void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4880 AppendSTDOUT(out.data(), out.size());
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004881}
4882
4883static const char *end_delimiter = "--end--;";
4884static const int end_delimiter_len = 8;
4885
Kate Stoneb9c1b512016-09-06 20:57:50 +00004886void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4887 std::string input = data.str(); // '1' to move beyond 'A'
4888 if (m_partial_profile_data.length() > 0) {
4889 m_partial_profile_data.append(input);
4890 input = m_partial_profile_data;
4891 m_partial_profile_data.clear();
4892 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004893
Kate Stoneb9c1b512016-09-06 20:57:50 +00004894 size_t found, pos = 0, len = input.length();
4895 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4896 StringExtractorGDBRemote profileDataExtractor(
4897 input.substr(pos, found).c_str());
4898 std::string profile_data =
4899 HarmonizeThreadIdsForProfileData(profileDataExtractor);
4900 BroadcastAsyncProfileData(profile_data);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004901
Kate Stoneb9c1b512016-09-06 20:57:50 +00004902 pos = found + end_delimiter_len;
4903 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004904
Kate Stoneb9c1b512016-09-06 20:57:50 +00004905 if (pos < len) {
4906 // Last incomplete chunk.
4907 m_partial_profile_data = input.substr(pos);
4908 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004909}
4910
Kate Stoneb9c1b512016-09-06 20:57:50 +00004911std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4912 StringExtractorGDBRemote &profileDataExtractor) {
4913 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4914 std::string output;
4915 llvm::raw_string_ostream output_stream(output);
4916 llvm::StringRef name, value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004917
Kate Stoneb9c1b512016-09-06 20:57:50 +00004918 // Going to assuming thread_used_usec comes first, else bail out.
4919 while (profileDataExtractor.GetNameColonValue(name, value)) {
4920 if (name.compare("thread_used_id") == 0) {
4921 StringExtractor threadIDHexExtractor(value);
4922 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004923
Kate Stoneb9c1b512016-09-06 20:57:50 +00004924 bool has_used_usec = false;
4925 uint32_t curr_used_usec = 0;
4926 llvm::StringRef usec_name, usec_value;
4927 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4928 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4929 if (usec_name.equals("thread_used_usec")) {
4930 has_used_usec = true;
4931 usec_value.getAsInteger(0, curr_used_usec);
4932 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004933 // We didn't find what we want, it is probably an older version. Bail
4934 // out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004935 profileDataExtractor.SetFilePos(input_file_pos);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004936 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004937 }
4938
4939 if (has_used_usec) {
4940 uint32_t prev_used_usec = 0;
4941 std::map<uint64_t, uint32_t>::iterator iterator =
4942 m_thread_id_to_used_usec_map.find(thread_id);
4943 if (iterator != m_thread_id_to_used_usec_map.end()) {
4944 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004945 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004946
4947 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4948 // A good first time record is one that runs for at least 0.25 sec
4949 bool good_first_time =
4950 (prev_used_usec == 0) && (real_used_usec > 250000);
4951 bool good_subsequent_time =
4952 (prev_used_usec > 0) &&
4953 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4954
4955 if (good_first_time || good_subsequent_time) {
Adrian Prantl05097242018-04-30 16:49:04 +00004956 // We try to avoid doing too many index id reservation, resulting in
4957 // fast increase of index ids.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004958
4959 output_stream << name << ":";
4960 int32_t index_id = AssignIndexIDToThread(thread_id);
4961 output_stream << index_id << ";";
4962
4963 output_stream << usec_name << ":" << usec_value << ";";
4964 } else {
4965 // Skip past 'thread_used_name'.
4966 llvm::StringRef local_name, local_value;
4967 profileDataExtractor.GetNameColonValue(local_name, local_value);
4968 }
4969
4970 // Store current time as previous time so that they can be compared
4971 // later.
4972 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4973 } else {
4974 // Bail out and use old string.
4975 output_stream << name << ":" << value << ";";
4976 }
4977 } else {
4978 output_stream << name << ":" << value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004979 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004980 }
4981 output_stream << end_delimiter;
4982 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004983
Kate Stoneb9c1b512016-09-06 20:57:50 +00004984 return output_stream.str();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004985}
4986
Kate Stoneb9c1b512016-09-06 20:57:50 +00004987void ProcessGDBRemote::HandleStopReply() {
4988 if (GetStopID() != 0)
4989 return;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004990
Kate Stoneb9c1b512016-09-06 20:57:50 +00004991 if (GetID() == LLDB_INVALID_PROCESS_ID) {
4992 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
4993 if (pid != LLDB_INVALID_PROCESS_ID)
4994 SetID(pid);
4995 }
4996 BuildDynamicRegisterInfo(true);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004997}
Eugene Zelenko0722f082015-10-24 01:28:05 +00004998
Todd Fialafcdb1af2016-09-10 00:06:29 +00004999static const char *const s_async_json_packet_prefix = "JSON-async:";
5000
5001static StructuredData::ObjectSP
5002ParseStructuredDataPacket(llvm::StringRef packet) {
5003 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
5004
5005 if (!packet.consume_front(s_async_json_packet_prefix)) {
5006 if (log) {
5007 log->Printf(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +00005008 "GDBRemoteCommunicationClientBase::%s() received $J packet "
Todd Fialafcdb1af2016-09-10 00:06:29 +00005009 "but was not a StructuredData packet: packet starts with "
5010 "%s",
5011 __FUNCTION__,
5012 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
5013 }
5014 return StructuredData::ObjectSP();
5015 }
5016
Adrian Prantl05097242018-04-30 16:49:04 +00005017 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
Todd Fialafcdb1af2016-09-10 00:06:29 +00005018 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
5019 if (log) {
5020 if (json_sp) {
5021 StreamString json_str;
5022 json_sp->Dump(json_str);
5023 json_str.Flush();
5024 log->Printf("ProcessGDBRemote::%s() "
5025 "received Async StructuredData packet: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00005026 __FUNCTION__, json_str.GetData());
Todd Fialafcdb1af2016-09-10 00:06:29 +00005027 } else {
5028 log->Printf("ProcessGDBRemote::%s"
5029 "() received StructuredData packet:"
5030 " parse failure",
5031 __FUNCTION__);
5032 }
5033 }
5034 return json_sp;
5035}
5036
5037void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
5038 auto structured_data_sp = ParseStructuredDataPacket(data);
5039 if (structured_data_sp)
5040 RouteAsyncStructuredData(structured_data_sp);
Todd Fiala75930012016-08-19 04:21:48 +00005041}
5042
Kate Stoneb9c1b512016-09-06 20:57:50 +00005043class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
Greg Claytone034a042015-05-21 20:52:06 +00005044public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005045 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
5046 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5047 "Tests packet speeds of various sizes to determine "
5048 "the performance characteristics of the GDB remote "
5049 "connection. ",
5050 NULL),
5051 m_option_group(),
5052 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5053 "The number of packets to send of each varying size "
5054 "(default is 1000).",
5055 1000),
5056 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5057 "The maximum number of bytes to send in a packet. Sizes "
5058 "increase in powers of 2 while the size is less than or "
5059 "equal to this option value. (default 1024).",
5060 1024),
5061 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5062 "The maximum number of bytes to receive in a packet. Sizes "
5063 "increase in powers of 2 while the size is less than or "
5064 "equal to this option value. (default 1024).",
5065 1024),
5066 m_json(LLDB_OPT_SET_1, false, "json", 'j',
5067 "Print the output as JSON data for easy parsing.", false, true) {
5068 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5069 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5070 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5071 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5072 m_option_group.Finalize();
5073 }
Greg Claytone034a042015-05-21 20:52:06 +00005074
Kate Stoneb9c1b512016-09-06 20:57:50 +00005075 ~CommandObjectProcessGDBRemoteSpeedTest() {}
Eugene Zelenko0722f082015-10-24 01:28:05 +00005076
Kate Stoneb9c1b512016-09-06 20:57:50 +00005077 Options *GetOptions() override { return &m_option_group; }
Greg Claytone034a042015-05-21 20:52:06 +00005078
Kate Stoneb9c1b512016-09-06 20:57:50 +00005079 bool DoExecute(Args &command, CommandReturnObject &result) override {
5080 const size_t argc = command.GetArgumentCount();
5081 if (argc == 0) {
5082 ProcessGDBRemote *process =
5083 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5084 .GetProcessPtr();
5085 if (process) {
5086 StreamSP output_stream_sp(
5087 m_interpreter.GetDebugger().GetAsyncOutputStream());
5088 result.SetImmediateOutputStream(output_stream_sp);
Greg Claytone034a042015-05-21 20:52:06 +00005089
Kate Stoneb9c1b512016-09-06 20:57:50 +00005090 const uint32_t num_packets =
5091 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5092 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5093 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5094 const bool json = m_json.GetOptionValue().GetCurrentValue();
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00005095 const uint64_t k_recv_amount =
5096 4 * 1024 * 1024; // Receive amount in bytes
5097 process->GetGDBRemote().TestPacketSpeed(
5098 num_packets, max_send, max_recv, k_recv_amount, json,
5099 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005100 result.SetStatus(eReturnStatusSuccessFinishResult);
5101 return true;
5102 }
5103 } else {
5104 result.AppendErrorWithFormat("'%s' takes no arguments",
5105 m_cmd_name.c_str());
Greg Claytone034a042015-05-21 20:52:06 +00005106 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005107 result.SetStatus(eReturnStatusFailed);
5108 return false;
5109 }
5110
Greg Claytone034a042015-05-21 20:52:06 +00005111protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005112 OptionGroupOptions m_option_group;
5113 OptionGroupUInt64 m_num_packets;
5114 OptionGroupUInt64 m_max_send;
5115 OptionGroupUInt64 m_max_recv;
5116 OptionGroupBoolean m_json;
Greg Claytone034a042015-05-21 20:52:06 +00005117};
5118
Kate Stoneb9c1b512016-09-06 20:57:50 +00005119class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005120private:
Greg Clayton998255b2012-10-13 02:07:45 +00005121public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005122 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5123 : CommandObjectParsed(interpreter, "process plugin packet history",
5124 "Dumps the packet history buffer. ", NULL) {}
5125
5126 ~CommandObjectProcessGDBRemotePacketHistory() {}
5127
5128 bool DoExecute(Args &command, CommandReturnObject &result) override {
5129 const size_t argc = command.GetArgumentCount();
5130 if (argc == 0) {
5131 ProcessGDBRemote *process =
5132 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5133 .GetProcessPtr();
5134 if (process) {
5135 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5136 result.SetStatus(eReturnStatusSuccessFinishResult);
5137 return true;
5138 }
5139 } else {
5140 result.AppendErrorWithFormat("'%s' takes no arguments",
5141 m_cmd_name.c_str());
5142 }
5143 result.SetStatus(eReturnStatusFailed);
5144 return false;
5145 }
5146};
5147
5148class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5149private:
5150public:
5151 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5152 : CommandObjectParsed(
5153 interpreter, "process plugin packet xfer-size",
5154 "Maximum size that lldb will try to read/write one one chunk.",
5155 NULL) {}
5156
5157 ~CommandObjectProcessGDBRemotePacketXferSize() {}
5158
5159 bool DoExecute(Args &command, CommandReturnObject &result) override {
5160 const size_t argc = command.GetArgumentCount();
5161 if (argc == 0) {
5162 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5163 "amount to be transferred when "
5164 "reading/writing",
5165 m_cmd_name.c_str());
5166 result.SetStatus(eReturnStatusFailed);
5167 return false;
Greg Clayton998255b2012-10-13 02:07:45 +00005168 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005169
Kate Stoneb9c1b512016-09-06 20:57:50 +00005170 ProcessGDBRemote *process =
5171 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5172 if (process) {
5173 const char *packet_size = command.GetArgumentAtIndex(0);
5174 errno = 0;
5175 uint64_t user_specified_max = strtoul(packet_size, NULL, 10);
5176 if (errno == 0 && user_specified_max != 0) {
5177 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5178 result.SetStatus(eReturnStatusSuccessFinishResult);
5179 return true;
5180 }
5181 }
5182 result.SetStatus(eReturnStatusFailed);
5183 return false;
5184 }
5185};
5186
5187class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5188private:
5189public:
5190 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5191 : CommandObjectParsed(interpreter, "process plugin packet send",
5192 "Send a custom packet through the GDB remote "
5193 "protocol and print the answer. "
5194 "The packet header and footer will automatically "
5195 "be added to the packet prior to sending and "
5196 "stripped from the result.",
5197 NULL) {}
5198
5199 ~CommandObjectProcessGDBRemotePacketSend() {}
5200
5201 bool DoExecute(Args &command, CommandReturnObject &result) override {
5202 const size_t argc = command.GetArgumentCount();
5203 if (argc == 0) {
5204 result.AppendErrorWithFormat(
5205 "'%s' takes a one or more packet content arguments",
5206 m_cmd_name.c_str());
5207 result.SetStatus(eReturnStatusFailed);
5208 return false;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005209 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005210
Kate Stoneb9c1b512016-09-06 20:57:50 +00005211 ProcessGDBRemote *process =
5212 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5213 if (process) {
5214 for (size_t i = 0; i < argc; ++i) {
5215 const char *packet_cstr = command.GetArgumentAtIndex(0);
5216 bool send_async = true;
5217 StringExtractorGDBRemote response;
5218 process->GetGDBRemote().SendPacketAndWaitForResponse(
5219 packet_cstr, response, send_async);
5220 result.SetStatus(eReturnStatusSuccessFinishResult);
5221 Stream &output_strm = result.GetOutputStream();
5222 output_strm.Printf(" packet: %s\n", packet_cstr);
5223 std::string &response_str = response.GetStringRef();
5224
5225 if (strstr(packet_cstr, "qGetProfileData") != NULL) {
5226 response_str = process->HarmonizeThreadIdsForProfileData(response);
Greg Clayton02686b82012-10-15 22:42:16 +00005227 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005228
5229 if (response_str.empty())
5230 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
Greg Clayton02686b82012-10-15 22:42:16 +00005231 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005232 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5233 }
Greg Clayton02686b82012-10-15 22:42:16 +00005234 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005235 return true;
5236 }
Greg Clayton02686b82012-10-15 22:42:16 +00005237};
5238
Kate Stoneb9c1b512016-09-06 20:57:50 +00005239class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005240private:
Jason Molenda6076bf42014-05-06 04:34:52 +00005241public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005242 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5243 : CommandObjectRaw(interpreter, "process plugin packet monitor",
5244 "Send a qRcmd packet through the GDB remote protocol "
5245 "and print the response."
5246 "The argument passed to this command will be hex "
5247 "encoded into a valid 'qRcmd' packet, sent and the "
Zachary Turnera4496982016-10-05 21:14:38 +00005248 "response will be printed.") {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005249
5250 ~CommandObjectProcessGDBRemotePacketMonitor() {}
5251
5252 bool DoExecute(const char *command, CommandReturnObject &result) override {
5253 if (command == NULL || command[0] == '\0') {
5254 result.AppendErrorWithFormat("'%s' takes a command string argument",
5255 m_cmd_name.c_str());
5256 result.SetStatus(eReturnStatusFailed);
5257 return false;
Jason Molenda6076bf42014-05-06 04:34:52 +00005258 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005259
Kate Stoneb9c1b512016-09-06 20:57:50 +00005260 ProcessGDBRemote *process =
5261 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5262 if (process) {
5263 StreamString packet;
5264 packet.PutCString("qRcmd,");
5265 packet.PutBytesAsRawHex8(command, strlen(command));
Ed Maste81b4c5f2016-01-04 01:43:47 +00005266
Kate Stoneb9c1b512016-09-06 20:57:50 +00005267 bool send_async = true;
5268 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005269 Stream &output_strm = result.GetOutputStream();
Pavel Labath7da84752018-01-10 14:39:08 +00005270 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5271 packet.GetString(), response, send_async,
5272 [&output_strm](llvm::StringRef output) { output_strm << output; });
5273 result.SetStatus(eReturnStatusSuccessFinishResult);
Zachary Turnerc1564272016-11-16 21:15:24 +00005274 output_strm.Printf(" packet: %s\n", packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005275 const std::string &response_str = response.GetStringRef();
Jason Molenda6076bf42014-05-06 04:34:52 +00005276
Kate Stoneb9c1b512016-09-06 20:57:50 +00005277 if (response_str.empty())
5278 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5279 else
5280 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
Jason Molenda6076bf42014-05-06 04:34:52 +00005281 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005282 return true;
5283 }
Jason Molenda6076bf42014-05-06 04:34:52 +00005284};
5285
Kate Stoneb9c1b512016-09-06 20:57:50 +00005286class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005287private:
Greg Clayton02686b82012-10-15 22:42:16 +00005288public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005289 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5290 : CommandObjectMultiword(interpreter, "process plugin packet",
5291 "Commands that deal with GDB remote packets.",
5292 NULL) {
5293 LoadSubCommand(
5294 "history",
5295 CommandObjectSP(
5296 new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5297 LoadSubCommand(
5298 "send", CommandObjectSP(
5299 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5300 LoadSubCommand(
5301 "monitor",
5302 CommandObjectSP(
5303 new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5304 LoadSubCommand(
5305 "xfer-size",
5306 CommandObjectSP(
5307 new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5308 LoadSubCommand("speed-test",
5309 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5310 interpreter)));
5311 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005312
Kate Stoneb9c1b512016-09-06 20:57:50 +00005313 ~CommandObjectProcessGDBRemotePacket() {}
Greg Clayton998255b2012-10-13 02:07:45 +00005314};
5315
Kate Stoneb9c1b512016-09-06 20:57:50 +00005316class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
Greg Claytonba4a0a52013-02-01 23:03:47 +00005317public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005318 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5319 : CommandObjectMultiword(
5320 interpreter, "process plugin",
5321 "Commands for operating on a ProcessGDBRemote process.",
5322 "process plugin <subcommand> [<subcommand-options>]") {
5323 LoadSubCommand(
5324 "packet",
5325 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5326 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005327
Kate Stoneb9c1b512016-09-06 20:57:50 +00005328 ~CommandObjectMultiwordProcessGDBRemote() {}
Greg Claytonba4a0a52013-02-01 23:03:47 +00005329};
5330
Kate Stoneb9c1b512016-09-06 20:57:50 +00005331CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5332 if (!m_command_sp)
5333 m_command_sp.reset(new CommandObjectMultiwordProcessGDBRemote(
5334 GetTarget().GetDebugger().GetCommandInterpreter()));
5335 return m_command_sp.get();
Greg Clayton998255b2012-10-13 02:07:45 +00005336}