blob: 5cb5f147367f93393234055c2445970bfc93780e [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Eugene Zelenko0722f082015-10-24 01:28:05 +00009#include "lldb/Host/Config.h"
10
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011#include <errno.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000012#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000013#ifndef LLDB_DISABLE_POSIX
Sean Callanan224f6f52012-07-19 18:07:36 +000014#include <netinet/in.h>
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000015#include <sys/mman.h>
Greg Claytonc6c420f2016-08-12 16:46:18 +000016#include <sys/socket.h>
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000017#include <unistd.h>
Zachary Turnerbd22bf22016-08-12 16:52:31 +000018#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000020#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000021#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include <algorithm>
Pavel Labath6b3c8bb2018-04-05 16:23:54 +000024#include <csignal>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include <map>
Jonas Devlieghere796ac802019-02-11 23:13:08 +000026#include <memory>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000027#include <mutex>
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000028#include <sstream>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029
Johnny Chen01a67862011-10-14 00:42:25 +000030#include "lldb/Breakpoint/Watchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000033#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Core/PluginManager.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000035#include "lldb/Core/StreamFile.h"
Greg Clayton70b57652011-05-15 01:25:55 +000036#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000037#include "lldb/DataFormatters/FormatManager.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000038#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000039#include "lldb/Host/FileSystem.h"
Zachary Turner39de3112014-09-09 20:54:56 +000040#include "lldb/Host/HostThread.h"
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000041#include "lldb/Host/PosixApi.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000042#include "lldb/Host/PseudoTerminal.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000043#include "lldb/Host/StringConvert.h"
Zachary Turner39de3112014-09-09 20:54:56 +000044#include "lldb/Host/ThreadLauncher.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000045#include "lldb/Host/XML.h"
Greg Clayton02686b82012-10-15 22:42:16 +000046#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000047#include "lldb/Interpreter/CommandObject.h"
48#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000049#include "lldb/Interpreter/CommandReturnObject.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000050#include "lldb/Interpreter/OptionArgParser.h"
Greg Claytone034a042015-05-21 20:52:06 +000051#include "lldb/Interpreter/OptionGroupBoolean.h"
52#include "lldb/Interpreter/OptionGroupUInt64.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000053#include "lldb/Interpreter/OptionValueProperties.h"
54#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000055#include "lldb/Interpreter/Property.h"
Zachary Turner80552912019-02-27 21:42:10 +000056#include "lldb/Symbol/LocateSymbolFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057#include "lldb/Symbol/ObjectFile.h"
Jason Molenda21586c82015-09-09 03:36:24 +000058#include "lldb/Target/ABI.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000059#include "lldb/Target/DynamicLoader.h"
Pavel Labath16064d32018-03-20 11:56:24 +000060#include "lldb/Target/MemoryRegionInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000061#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000062#include "lldb/Target/Target.h"
63#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000064#include "lldb/Target/ThreadPlanCallFunction.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000065#include "lldb/Utility/Args.h"
Greg Claytonc6c420f2016-08-12 16:46:18 +000066#include "lldb/Utility/CleanUp.h"
Zachary Turner5713a052017-03-22 18:40:07 +000067#include "lldb/Utility/FileSpec.h"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000068#include "lldb/Utility/Reproducer.h"
Pavel Labathd821c992018-08-07 11:07:21 +000069#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000070#include "lldb/Utility/StreamString.h"
Pavel Labath38d06322017-06-29 14:32:17 +000071#include "lldb/Utility/Timer.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000072
Kate Stoneb9c1b512016-09-06 20:57:50 +000073#include "GDBRemoteRegisterContext.h"
74#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000075#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000076#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000077#include "Plugins/Process/Utility/StopInfoMachException.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000078#include "ProcessGDBRemote.h"
79#include "ProcessGDBRemoteLog.h"
80#include "ThreadGDBRemote.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000081#include "lldb/Host/Host.h"
Pavel Labath9af71b32018-03-20 16:14:00 +000082#include "lldb/Utility/StringExtractorGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000083
Zachary Turner54695a32016-08-29 19:58:14 +000084#include "llvm/ADT/StringSwitch.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000085#include "llvm/Support/Threading.h"
Eugene Zemtsov7993cc52017-03-07 21:34:40 +000086#include "llvm/Support/raw_ostream.h"
Zachary Turner54695a32016-08-29 19:58:14 +000087
Kate Stoneb9c1b512016-09-06 20:57:50 +000088#define DEBUGSERVER_BASENAME "debugserver"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000089using namespace llvm;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000090using namespace lldb;
91using namespace lldb_private;
92using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000093
Kate Stoneb9c1b512016-09-06 20:57:50 +000094namespace lldb {
95// Provide a function that can easily dump the packet history if we know a
Adrian Prantl05097242018-04-30 16:49:04 +000096// ProcessGDBRemote * value (which we can get from logs or from debugging). We
97// need the function in the lldb namespace so it makes it into the final
Kate Stoneb9c1b512016-09-06 20:57:50 +000098// executable since the LLDB shared library only exports stuff in the lldb
Adrian Prantl05097242018-04-30 16:49:04 +000099// namespace. This allows you to attach with a debugger and call this function
100// and get the packet history dumped to a file.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
102 StreamFile strm;
Jonas Devlieghere50bc1ed2018-11-02 22:34:51 +0000103 Status error = FileSystem::Instance().Open(strm.GetFile(), FileSpec(path),
104 File::eOpenOptionWrite |
105 File::eOpenOptionCanCreate);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 if (error.Success())
107 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(strm);
108}
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000109} // namespace lldb
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000110
Greg Clayton7f982402013-07-15 22:54:20 +0000111namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000112
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000113static constexpr PropertyDefinition g_properties[] = {
Antonio Afonsof8251f12019-07-03 17:30:07 +0000114 {"packet-timeout",
115 OptionValue::eTypeUInt64,
116 true,
117 5
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000118#if defined(__has_feature)
119#if __has_feature(address_sanitizer)
Konrad Kleine248a1302019-05-23 11:14:47 +0000120 * 2
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000121#endif
122#endif
Antonio Afonsof8251f12019-07-03 17:30:07 +0000123 ,
124 nullptr,
125 {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 "Specify the default packet timeout in seconds."},
Antonio Afonsof8251f12019-07-03 17:30:07 +0000127 {"target-definition-file",
128 OptionValue::eTypeFileSpec,
129 true,
130 0,
131 nullptr,
132 {},
133 "The file that provides the description for remote target registers."},
134 {"use-libraries-svr4",
135 OptionValue::eTypeBoolean,
136 true,
137 false,
138 nullptr,
139 {},
140 "If true, the libraries-svr4 feature will be used to get a hold of the "
141 "process's loaded modules."}};
Ed Maste81b4c5f2016-01-04 01:43:47 +0000142
Antonio Afonsof8251f12019-07-03 17:30:07 +0000143enum {
144 ePropertyPacketTimeout,
145 ePropertyTargetDefinitionFile,
146 ePropertyUseSVR4
147};
Ed Maste81b4c5f2016-01-04 01:43:47 +0000148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149class PluginProperties : public Properties {
150public:
151 static ConstString GetSettingName() {
152 return ProcessGDBRemote::GetPluginNameStatic();
153 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000154
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 PluginProperties() : Properties() {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000156 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157 m_collection_sp->Initialize(g_properties);
158 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000159
Raphael Isemann17566302019-05-03 10:03:28 +0000160 ~PluginProperties() override {}
Ed Maste81b4c5f2016-01-04 01:43:47 +0000161
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 uint64_t GetPacketTimeout() {
163 const uint32_t idx = ePropertyPacketTimeout;
164 return m_collection_sp->GetPropertyAtIndexAsUInt64(
Konrad Kleine248a1302019-05-23 11:14:47 +0000165 nullptr, idx, g_properties[idx].default_uint_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000167
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168 bool SetPacketTimeout(uint64_t timeout) {
169 const uint32_t idx = ePropertyPacketTimeout;
Konrad Kleine248a1302019-05-23 11:14:47 +0000170 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000172
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173 FileSpec GetTargetDefinitionFile() const {
174 const uint32_t idx = ePropertyTargetDefinitionFile;
Konrad Kleine248a1302019-05-23 11:14:47 +0000175 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000176 }
Antonio Afonsof8251f12019-07-03 17:30:07 +0000177
178 bool GetUseSVR4() const {
179 const uint32_t idx = ePropertyUseSVR4;
180 return m_collection_sp->GetPropertyAtIndexAsBoolean(
181 nullptr, idx, g_properties[idx].default_uint_value != 0);
182 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183};
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000184
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000186
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
188 static ProcessKDPPropertiesSP g_settings_sp;
189 if (!g_settings_sp)
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000190 g_settings_sp = std::make_shared<PluginProperties>();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000191 return g_settings_sp;
192}
Ed Maste81b4c5f2016-01-04 01:43:47 +0000193
Jonas Devlieghere68ed93d2018-11-27 22:11:02 +0000194class ProcessGDBRemoteProvider
195 : public repro::Provider<ProcessGDBRemoteProvider> {
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000196public:
Jonas Devlieghereef96e982019-06-12 22:17:38 +0000197 struct Info {
198 static const char *name;
199 static const char *file;
200 };
Jonas Devliegheree912cc52019-01-18 01:04:59 +0000201
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000202 ProcessGDBRemoteProvider(const FileSpec &directory) : Provider(directory) {
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000203 }
204
205 raw_ostream *GetHistoryStream() {
Jonas Devlieghereef96e982019-06-12 22:17:38 +0000206 FileSpec history_file = GetRoot().CopyByAppendingPathComponent(Info::file);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000207
208 std::error_code EC;
Haojian Wu01b09882018-11-14 09:42:28 +0000209 m_stream_up = llvm::make_unique<raw_fd_ostream>(history_file.GetPath(), EC,
Jonas Devlieghere209e3a12019-03-12 17:31:04 +0000210 sys::fs::OpenFlags::F_Text);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000211 return m_stream_up.get();
212 }
213
214 void SetCallback(std::function<void()> callback) {
215 m_callback = std::move(callback);
216 }
217
218 void Keep() override { m_callback(); }
219
220 void Discard() override { m_callback(); }
221
Jonas Devlieghere68ed93d2018-11-27 22:11:02 +0000222 static char ID;
223
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000224private:
225 std::function<void()> m_callback;
226 std::unique_ptr<raw_fd_ostream> m_stream_up;
227};
228
Jonas Devlieghere68ed93d2018-11-27 22:11:02 +0000229char ProcessGDBRemoteProvider::ID = 0;
Jonas Devlieghereef96e982019-06-12 22:17:38 +0000230const char *ProcessGDBRemoteProvider::Info::name = "gdb-remote";
231const char *ProcessGDBRemoteProvider::Info::file = "gdb-remote.yaml";
Jonas Devlieghere68ed93d2018-11-27 22:11:02 +0000232
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000233} // namespace
Greg Clayton7f982402013-07-15 22:54:20 +0000234
Greg Claytonfda4fab2014-01-10 22:24:11 +0000235// TODO Randomly assigning a port is unsafe. We should get an unused
Adrian Prantl05097242018-04-30 16:49:04 +0000236// ephemeral port from the kernel and make sure we reserve it before passing it
237// to debugserver.
Greg Claytonfda4fab2014-01-10 22:24:11 +0000238
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239#if defined(__APPLE__)
240#define LOW_PORT (IPPORT_RESERVED)
241#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
Greg Claytonfda4fab2014-01-10 22:24:11 +0000242#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243#define LOW_PORT (1024u)
244#define HIGH_PORT (49151u)
Greg Claytonfda4fab2014-01-10 22:24:11 +0000245#endif
246
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247#if defined(__APPLE__) && \
248 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000249static bool rand_initialized = false;
250
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251static inline uint16_t get_random_port() {
252 if (!rand_initialized) {
253 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000254
Kate Stoneb9c1b512016-09-06 20:57:50 +0000255 rand_initialized = true;
256 srand(seed);
257 }
258 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Greg Claytonfda4fab2014-01-10 22:24:11 +0000259}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000260#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000261
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262ConstString ProcessGDBRemote::GetPluginNameStatic() {
263 static ConstString g_name("gdb-remote");
264 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000265}
266
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267const char *ProcessGDBRemote::GetPluginDescriptionStatic() {
268 return "GDB Remote protocol based debugging plug-in.";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000269}
270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271void ProcessGDBRemote::Terminate() {
272 PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000273}
274
Greg Claytonc3776bf2012-02-09 06:16:32 +0000275lldb::ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
277 ListenerSP listener_sp,
278 const FileSpec *crash_file_path) {
279 lldb::ProcessSP process_sp;
Konrad Kleine248a1302019-05-23 11:14:47 +0000280 if (crash_file_path == nullptr)
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000281 process_sp = std::make_shared<ProcessGDBRemote>(target_sp, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000283}
284
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
286 bool plugin_specified_by_name) {
287 if (plugin_specified_by_name)
Jim Ingham5aee1622010-08-09 23:31:02 +0000288 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000289
290 // For now we are just making sure the file exists for a given module
291 Module *exe_module = target_sp->GetExecutableModulePointer();
292 if (exe_module) {
293 ObjectFile *exe_objfile = exe_module->GetObjectFile();
294 // We can't debug core files...
295 switch (exe_objfile->GetType()) {
296 case ObjectFile::eTypeInvalid:
297 case ObjectFile::eTypeCoreFile:
298 case ObjectFile::eTypeDebugInfo:
299 case ObjectFile::eTypeObjectFile:
300 case ObjectFile::eTypeSharedLibrary:
301 case ObjectFile::eTypeStubLibrary:
302 case ObjectFile::eTypeJIT:
303 return false;
304 case ObjectFile::eTypeExecutable:
305 case ObjectFile::eTypeDynamicLinker:
306 case ObjectFile::eTypeUnknown:
307 break;
308 }
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000309 return FileSystem::Instance().Exists(exe_module->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000310 }
Adrian Prantl05097242018-04-30 16:49:04 +0000311 // However, if there is no executable module, we return true since we might
312 // be preparing to attach.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000313 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000314}
315
Eugene Zelenko0722f082015-10-24 01:28:05 +0000316// ProcessGDBRemote constructor
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
318 ListenerSP listener_sp)
Pavel Labatha9640122017-11-03 22:12:50 +0000319 : Process(target_sp, listener_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_last_stop_packet_mutex(),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000321 m_register_info(),
Konrad Kleine248a1302019-05-23 11:14:47 +0000322 m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 m_async_listener_sp(
324 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
325 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
326 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
327 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
328 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
329 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
330 m_waiting_for_attach(false), m_destroy_tried_resuming(false),
331 m_command_sp(), m_breakpoint_pc_offset(0),
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000332 m_initial_tid(LLDB_INVALID_THREAD_ID), m_replay_mode(false),
333 m_allow_flash_writes(false), m_erased_flash_ranges() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000334 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
335 "async thread should exit");
336 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
337 "async thread continue");
338 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
339 "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000340
Jonas Devlieghere68ed93d2018-11-27 22:11:02 +0000341 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000342 ProcessGDBRemoteProvider &provider =
Jonas Devlieghere68ed93d2018-11-27 22:11:02 +0000343 g->GetOrCreate<ProcessGDBRemoteProvider>();
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000344 // Set the history stream to the stream owned by the provider.
345 m_gdb_comm.SetHistoryStream(provider.GetHistoryStream());
346 // Make sure to clear the stream again when we're finished.
347 provider.SetCallback([&]() { m_gdb_comm.SetHistoryStream(nullptr); });
348 }
349
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
Pavel Labath50556852015-09-03 09:36:22 +0000351
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 const uint32_t async_event_mask =
353 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
Pavel Labath50556852015-09-03 09:36:22 +0000354
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 if (m_async_listener_sp->StartListeningForEvents(
356 &m_async_broadcaster, async_event_mask) != async_event_mask) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000357 LLDB_LOGF(log,
358 "ProcessGDBRemote::%s failed to listen for "
359 "m_async_broadcaster events",
360 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 }
Pavel Labath50556852015-09-03 09:36:22 +0000362
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 const uint32_t gdb_event_mask =
364 Communication::eBroadcastBitReadThreadDidExit |
365 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
366 if (m_async_listener_sp->StartListeningForEvents(
367 &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000368 LLDB_LOGF(log,
369 "ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
370 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 }
Pavel Labath50556852015-09-03 09:36:22 +0000372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 const uint64_t timeout_seconds =
374 GetGlobalPluginProperties()->GetPacketTimeout();
375 if (timeout_seconds > 0)
Pavel Labath3aa04912016-10-31 17:19:42 +0000376 m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377}
378
Eugene Zelenko0722f082015-10-24 01:28:05 +0000379// Destructor
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380ProcessGDBRemote::~ProcessGDBRemote() {
381 // m_mach_process.UnregisterNotificationCallbacks (this);
382 Clear();
Adrian Prantl05097242018-04-30 16:49:04 +0000383 // We need to call finalize on the process before destroying ourselves to
384 // make sure all of the broadcaster cleanup goes as planned. If we destruct
385 // this class, then Process::~Process() might have problems trying to fully
386 // destroy the broadcaster.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 Finalize();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000388
Adrian Prantl05097242018-04-30 16:49:04 +0000389 // The general Finalize is going to try to destroy the process and that
390 // SHOULD shut down the async thread. However, if we don't kill it it will
391 // get stranded and its connection will go away so when it wakes up it will
392 // crash. So kill it for sure here.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 StopAsyncThread();
394 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395}
396
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000397// PluginInterface
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402bool ProcessGDBRemote::ParsePythonTargetDefinition(
403 const FileSpec &target_definition_fspec) {
404 ScriptInterpreter *interpreter =
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000405 GetTarget().GetDebugger().GetScriptInterpreter();
Zachary Turner97206d52017-05-12 04:51:55 +0000406 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 StructuredData::ObjectSP module_object_sp(
408 interpreter->LoadPluginModule(target_definition_fspec, error));
409 if (module_object_sp) {
410 StructuredData::DictionarySP target_definition_sp(
411 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
412 "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 if (target_definition_sp) {
415 StructuredData::ObjectSP target_object(
416 target_definition_sp->GetValueForKey("host-info"));
417 if (target_object) {
418 if (auto host_info_dict = target_object->GetAsDictionary()) {
419 StructuredData::ObjectSP triple_value =
420 host_info_dict->GetValueForKey("triple");
421 if (auto triple_string_value = triple_value->GetAsString()) {
422 std::string triple_string = triple_string_value->GetValue();
423 ArchSpec host_arch(triple_string.c_str());
424 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
425 GetTarget().SetArchitecture(host_arch);
Greg Clayton312bcbe2013-10-17 01:10:23 +0000426 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 }
Greg Claytonef8180a2013-10-15 00:14:28 +0000428 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429 }
430 m_breakpoint_pc_offset = 0;
431 StructuredData::ObjectSP breakpoint_pc_offset_value =
432 target_definition_sp->GetValueForKey("breakpoint-pc-offset");
433 if (breakpoint_pc_offset_value) {
434 if (auto breakpoint_pc_int_value =
435 breakpoint_pc_offset_value->GetAsInteger())
436 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
437 }
438
439 if (m_register_info.SetRegisterInfo(*target_definition_sp,
440 GetTarget().GetArchitecture()) > 0) {
441 return true;
442 }
Greg Claytonef8180a2013-10-15 00:14:28 +0000443 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000444 }
445 return false;
Greg Claytonef8180a2013-10-15 00:14:28 +0000446}
447
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448// If the remote stub didn't give us eh_frame or DWARF register numbers for a
Adrian Prantl05097242018-04-30 16:49:04 +0000449// register, see if the ABI can provide them.
Jason Molenda21586c82015-09-09 03:36:24 +0000450// DWARF and eh_frame register numbers are defined as a part of the ABI.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451static void AugmentRegisterInfoViaABI(RegisterInfo &reg_info,
452 ConstString reg_name, ABISP abi_sp) {
453 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM ||
454 reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM) {
455 if (abi_sp) {
456 RegisterInfo abi_reg_info;
457 if (abi_sp->GetRegisterInfoByName(reg_name, abi_reg_info)) {
458 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM &&
459 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM) {
460 reg_info.kinds[eRegisterKindEHFrame] =
461 abi_reg_info.kinds[eRegisterKindEHFrame];
462 }
463 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM &&
464 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM) {
465 reg_info.kinds[eRegisterKindDWARF] =
466 abi_reg_info.kinds[eRegisterKindDWARF];
467 }
468 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM &&
469 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM) {
470 reg_info.kinds[eRegisterKindGeneric] =
471 abi_reg_info.kinds[eRegisterKindGeneric];
472 }
473 }
474 }
475 }
476}
477
478static size_t SplitCommaSeparatedRegisterNumberString(
479 const llvm::StringRef &comma_separated_regiter_numbers,
480 std::vector<uint32_t> &regnums, int base) {
481 regnums.clear();
482 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
483 value_pair.second = comma_separated_regiter_numbers;
484 do {
485 value_pair = value_pair.second.split(',');
486 if (!value_pair.first.empty()) {
487 uint32_t reg = StringConvert::ToUInt32(value_pair.first.str().c_str(),
488 LLDB_INVALID_REGNUM, base);
489 if (reg != LLDB_INVALID_REGNUM)
490 regnums.push_back(reg);
491 }
492 } while (!value_pair.second.empty());
493 return regnums.size();
494}
495
496void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
497 if (!force && m_register_info.GetNumRegisters() > 0)
498 return;
499
500 m_register_info.Clear();
501
Adrian Prantl05097242018-04-30 16:49:04 +0000502 // Check if qHostInfo specified a specific packet timeout for this
503 // connection. If so then lets update our setting so the user knows what the
504 // timeout is and can see it.
Pavel Labath3aa04912016-10-31 17:19:42 +0000505 const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
506 if (host_packet_timeout > std::chrono::seconds(0)) {
507 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout.count());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 }
509
510 // Register info search order:
511 // 1 - Use the target definition python file if one is specified.
512 // 2 - If the target definition doesn't have any of the info from the
513 // target.xml (registers) then proceed to read the target.xml.
514 // 3 - Fall back on the qRegisterInfo packets.
515
516 FileSpec target_definition_fspec =
517 GetGlobalPluginProperties()->GetTargetDefinitionFile();
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000518 if (!FileSystem::Instance().Exists(target_definition_fspec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 // If the filename doesn't exist, it may be a ~ not having been expanded -
520 // try to resolve it.
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000521 FileSystem::Instance().Resolve(target_definition_fspec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 }
523 if (target_definition_fspec) {
524 // See if we can get register definitions from a python file
525 if (ParsePythonTargetDefinition(target_definition_fspec)) {
526 return;
527 } else {
528 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
529 stream_sp->Printf("ERROR: target description file %s failed to parse.\n",
530 target_definition_fspec.GetPath().c_str());
531 }
532 }
533
534 const ArchSpec &target_arch = GetTarget().GetArchitecture();
535 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
536 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
537
538 // Use the process' architecture instead of the host arch, if available
539 ArchSpec arch_to_use;
540 if (remote_process_arch.IsValid())
541 arch_to_use = remote_process_arch;
542 else
543 arch_to_use = remote_host_arch;
544
545 if (!arch_to_use.IsValid())
546 arch_to_use = target_arch;
547
548 if (GetGDBServerRegisterInfo(arch_to_use))
549 return;
550
551 char packet[128];
552 uint32_t reg_offset = 0;
553 uint32_t reg_num = 0;
554 for (StringExtractorGDBRemote::ResponseType response_type =
555 StringExtractorGDBRemote::eResponse;
556 response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
557 const int packet_len =
558 ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
559 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000560 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000562 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 GDBRemoteCommunication::PacketResult::Success) {
564 response_type = response.GetResponseType();
565 if (response_type == StringExtractorGDBRemote::eResponse) {
566 llvm::StringRef name;
567 llvm::StringRef value;
568 ConstString reg_name;
569 ConstString alt_name;
570 ConstString set_name;
571 std::vector<uint32_t> value_regs;
572 std::vector<uint32_t> invalidate_regs;
573 std::vector<uint8_t> dwarf_opcode_bytes;
574 RegisterInfo reg_info = {
Konrad Kleine248a1302019-05-23 11:14:47 +0000575 nullptr, // Name
576 nullptr, // Alt name
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 0, // byte size
578 reg_offset, // offset
579 eEncodingUint, // encoding
580 eFormatHex, // format
Jason Molenda21586c82015-09-09 03:36:24 +0000581 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 LLDB_INVALID_REGNUM, // eh_frame reg num
583 LLDB_INVALID_REGNUM, // DWARF reg num
584 LLDB_INVALID_REGNUM, // generic reg num
585 reg_num, // process plugin reg num
586 reg_num // native register number
587 },
Konrad Kleine248a1302019-05-23 11:14:47 +0000588 nullptr,
589 nullptr,
590 nullptr, // Dwarf expression opcode bytes pointer
591 0 // Dwarf expression opcode bytes length
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592 };
593
594 while (response.GetNameColonValue(name, value)) {
595 if (name.equals("name")) {
596 reg_name.SetString(value);
597 } else if (name.equals("alt-name")) {
598 alt_name.SetString(value);
599 } else if (name.equals("bitsize")) {
600 value.getAsInteger(0, reg_info.byte_size);
601 reg_info.byte_size /= CHAR_BIT;
602 } else if (name.equals("offset")) {
603 if (value.getAsInteger(0, reg_offset))
604 reg_offset = UINT32_MAX;
605 } else if (name.equals("encoding")) {
606 const Encoding encoding = Args::StringToEncoding(value);
607 if (encoding != eEncodingInvalid)
608 reg_info.encoding = encoding;
609 } else if (name.equals("format")) {
610 Format format = eFormatInvalid;
Konrad Kleine248a1302019-05-23 11:14:47 +0000611 if (OptionArgParser::ToFormat(value.str().c_str(), format, nullptr)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612 .Success())
613 reg_info.format = format;
614 else {
615 reg_info.format =
616 llvm::StringSwitch<Format>(value)
617 .Case("binary", eFormatBinary)
618 .Case("decimal", eFormatDecimal)
619 .Case("hex", eFormatHex)
620 .Case("float", eFormatFloat)
621 .Case("vector-sint8", eFormatVectorOfSInt8)
622 .Case("vector-uint8", eFormatVectorOfUInt8)
623 .Case("vector-sint16", eFormatVectorOfSInt16)
624 .Case("vector-uint16", eFormatVectorOfUInt16)
625 .Case("vector-sint32", eFormatVectorOfSInt32)
626 .Case("vector-uint32", eFormatVectorOfUInt32)
627 .Case("vector-float32", eFormatVectorOfFloat32)
Valentina Giusticda0ae42016-09-08 14:16:45 +0000628 .Case("vector-uint64", eFormatVectorOfUInt64)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 .Case("vector-uint128", eFormatVectorOfUInt128)
630 .Default(eFormatInvalid);
Jason Molenda21586c82015-09-09 03:36:24 +0000631 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632 } else if (name.equals("set")) {
633 set_name.SetString(value);
634 } else if (name.equals("gcc") || name.equals("ehframe")) {
635 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame]))
636 reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM;
637 } else if (name.equals("dwarf")) {
638 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF]))
639 reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM;
640 } else if (name.equals("generic")) {
641 reg_info.kinds[eRegisterKindGeneric] =
642 Args::StringToGenericRegister(value);
643 } else if (name.equals("container-regs")) {
644 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
645 } else if (name.equals("invalidate-regs")) {
646 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
647 } else if (name.equals("dynamic_size_dwarf_expr_bytes")) {
648 size_t dwarf_opcode_len = value.size() / 2;
649 assert(dwarf_opcode_len > 0);
650
651 dwarf_opcode_bytes.resize(dwarf_opcode_len);
652 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
653
654 StringExtractor opcode_extractor(value);
655 uint32_t ret_val =
656 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
657 assert(dwarf_opcode_len == ret_val);
Hafiz Abid Qadeer05008ca2017-01-19 15:11:01 +0000658 UNUSED_IF_ASSERT_DISABLED(ret_val);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
660 }
Jason Molenda21586c82015-09-09 03:36:24 +0000661 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000662
663 reg_info.byte_offset = reg_offset;
664 assert(reg_info.byte_size != 0);
665 reg_offset += reg_info.byte_size;
666 if (!value_regs.empty()) {
667 value_regs.push_back(LLDB_INVALID_REGNUM);
668 reg_info.value_regs = value_regs.data();
669 }
670 if (!invalidate_regs.empty()) {
671 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
672 reg_info.invalidate_regs = invalidate_regs.data();
673 }
674
675 // We have to make a temporary ABI here, and not use the GetABI because
Adrian Prantl05097242018-04-30 16:49:04 +0000676 // this code gets called in DidAttach, when the target architecture
677 // (and consequently the ABI we'll get from the process) may be wrong.
Jason Molenda43294c92017-06-29 02:57:03 +0000678 ABISP abi_to_use = ABI::FindPlugin(shared_from_this(), arch_to_use);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679
680 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_to_use);
681
682 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
683 } else {
684 break; // ensure exit before reg_num is incremented
685 }
686 } else {
687 break;
Jason Molenda21586c82015-09-09 03:36:24 +0000688 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 }
690
691 if (m_register_info.GetNumRegisters() > 0) {
692 m_register_info.Finalize(GetTarget().GetArchitecture());
693 return;
694 }
695
696 // We didn't get anything if the accumulated reg_num is zero. See if we are
697 // debugging ARM and fill with a hard coded register set until we can get an
Adrian Prantl05097242018-04-30 16:49:04 +0000698 // updated debugserver down on the devices. On the other hand, if the
699 // accumulated reg_num is positive, see if we can add composite registers to
700 // the existing primordial ones.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
702
703 if (!target_arch.IsValid()) {
704 if (arch_to_use.IsValid() &&
705 (arch_to_use.GetMachine() == llvm::Triple::arm ||
706 arch_to_use.GetMachine() == llvm::Triple::thumb) &&
707 arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
708 m_register_info.HardcodeARMRegisters(from_scratch);
709 } else if (target_arch.GetMachine() == llvm::Triple::arm ||
710 target_arch.GetMachine() == llvm::Triple::thumb) {
711 m_register_info.HardcodeARMRegisters(from_scratch);
712 }
713
714 // At this point, we can finalize our register info.
715 m_register_info.Finalize(GetTarget().GetArchitecture());
Jason Molenda21586c82015-09-09 03:36:24 +0000716}
717
Saleem Abdulrasool92e52732018-12-05 04:04:14 +0000718Status ProcessGDBRemote::WillLaunch(lldb_private::Module *module) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 return WillLaunchOrAttach();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000720}
721
Zachary Turner97206d52017-05-12 04:51:55 +0000722Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 return WillLaunchOrAttach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724}
725
Zachary Turner97206d52017-05-12 04:51:55 +0000726Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
727 bool wait_for_launch) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000728 return WillLaunchOrAttach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729}
730
Zachary Turner97206d52017-05-12 04:51:55 +0000731Status ProcessGDBRemote::DoConnectRemote(Stream *strm,
732 llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +0000734 Status error(WillLaunchOrAttach());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736 if (error.Fail())
Greg Claytonb766a732011-02-04 01:58:07 +0000737 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738
739 error = ConnectToDebugserver(remote_url);
740
741 if (error.Fail())
742 return error;
743 StartAsyncThread();
744
745 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
746 if (pid == LLDB_INVALID_PROCESS_ID) {
Adrian Prantl05097242018-04-30 16:49:04 +0000747 // We don't have a valid process ID, so note that we are connected and
748 // could now request to launch or attach, or get remote process listings...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749 SetPrivateState(eStateConnected);
750 } else {
751 // We have a valid process
752 SetID(pid);
753 GetThreadList();
754 StringExtractorGDBRemote response;
755 if (m_gdb_comm.GetStopReply(response)) {
756 SetLastStopPacket(response);
757
758 // '?' Packets must be handled differently in non-stop mode
759 if (GetTarget().GetNonStopModeEnabled())
760 HandleStopReplySequence();
761
762 Target &target = GetTarget();
763 if (!target.GetArchitecture().IsValid()) {
764 if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
765 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
766 } else {
Jason Molendadf9f7962018-10-23 23:45:56 +0000767 if (m_gdb_comm.GetHostArchitecture().IsValid()) {
768 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
769 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770 }
771 }
772
773 const StateType state = SetThreadStopInfo(response);
774 if (state != eStateInvalid) {
775 SetPrivateState(state);
776 } else
Zachary Turner31659452016-11-17 21:15:14 +0000777 error.SetErrorStringWithFormat(
778 "Process %" PRIu64 " was reported after connecting to "
779 "'%s', but state was not stopped: %s",
780 pid, remote_url.str().c_str(), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 } else
782 error.SetErrorStringWithFormat("Process %" PRIu64
783 " was reported after connecting to '%s', "
784 "but no stop reply packet was received",
Zachary Turner31659452016-11-17 21:15:14 +0000785 pid, remote_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 }
787
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000788 LLDB_LOGF(log,
789 "ProcessGDBRemote::%s pid %" PRIu64
790 ": normalizing target architecture initial triple: %s "
791 "(GetTarget().GetArchitecture().IsValid() %s, "
792 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
793 __FUNCTION__, GetID(),
794 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
795 GetTarget().GetArchitecture().IsValid() ? "true" : "false",
796 m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797
798 if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
799 m_gdb_comm.GetHostArchitecture().IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000800 // Prefer the *process'* architecture over that of the *host*, if
801 // available.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 if (m_gdb_comm.GetProcessArchitecture().IsValid())
803 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
804 else
805 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
806 }
807
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000808 LLDB_LOGF(log,
809 "ProcessGDBRemote::%s pid %" PRIu64
810 ": normalized target architecture triple: %s",
811 __FUNCTION__, GetID(),
812 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813
814 if (error.Success()) {
815 PlatformSP platform_sp = GetTarget().GetPlatform();
816 if (platform_sp && platform_sp->IsConnected())
817 SetUnixSignals(platform_sp->GetUnixSignals());
818 else
819 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
820 }
821
822 return error;
Greg Claytonb766a732011-02-04 01:58:07 +0000823}
824
Zachary Turner97206d52017-05-12 04:51:55 +0000825Status ProcessGDBRemote::WillLaunchOrAttach() {
826 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 m_stdio_communication.Clear();
828 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000829}
830
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000831// Process Control
Saleem Abdulrasool92e52732018-12-05 04:04:14 +0000832Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module,
Zachary Turner97206d52017-05-12 04:51:55 +0000833 ProcessLaunchInfo &launch_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +0000835 Status error;
Greg Clayton982c9762011-11-03 21:22:33 +0000836
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000837 LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);
Todd Fiala75f47c32014-10-11 21:42:09 +0000838
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 uint32_t launch_flags = launch_info.GetFlags().Get();
840 FileSpec stdin_file_spec{};
841 FileSpec stdout_file_spec{};
842 FileSpec stderr_file_spec{};
843 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000844
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845 const FileAction *file_action;
846 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
847 if (file_action) {
848 if (file_action->GetAction() == FileAction::eFileActionOpen)
849 stdin_file_spec = file_action->GetFileSpec();
850 }
851 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
852 if (file_action) {
853 if (file_action->GetAction() == FileAction::eFileActionOpen)
854 stdout_file_spec = file_action->GetFileSpec();
855 }
856 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
857 if (file_action) {
858 if (file_action->GetAction() == FileAction::eFileActionOpen)
859 stderr_file_spec = file_action->GetFileSpec();
860 }
Greg Clayton982c9762011-11-03 21:22:33 +0000861
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862 if (log) {
863 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000864 LLDB_LOGF(log,
865 "ProcessGDBRemote::%s provided with STDIO paths via "
866 "launch_info: stdin=%s, stdout=%s, stderr=%s",
867 __FUNCTION__,
868 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
869 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
870 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Vince Harrondf3f00f2015-02-10 21:09:04 +0000871 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000872 LLDB_LOGF(log,
873 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
874 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000875 }
Vince Harrondf3f00f2015-02-10 21:09:04 +0000876
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
878 if (stdin_file_spec || disable_stdio) {
Adrian Prantl05097242018-04-30 16:49:04 +0000879 // the inferior will be reading stdin from the specified file or stdio is
880 // completely disabled
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 m_stdin_forward = false;
882 } else {
883 m_stdin_forward = true;
884 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885
Kate Stoneb9c1b512016-09-06 20:57:50 +0000886 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
887 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
888 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
889 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
890 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000891
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 ObjectFile *object_file = exe_module->GetObjectFile();
893 if (object_file) {
894 error = EstablishConnectionIfNeeded(launch_info);
895 if (error.Success()) {
Pavel Labath07d6f882017-12-11 10:09:14 +0000896 PseudoTerminal pty;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000898
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899 PlatformSP platform_sp(GetTarget().GetPlatform());
900 if (disable_stdio) {
901 // set to /dev/null unless redirected to a file above
902 if (!stdin_file_spec)
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000903 stdin_file_spec.SetFile(FileSystem::DEV_NULL,
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000904 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905 if (!stdout_file_spec)
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000906 stdout_file_spec.SetFile(FileSystem::DEV_NULL,
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000907 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 if (!stderr_file_spec)
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000909 stderr_file_spec.SetFile(FileSystem::DEV_NULL,
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000910 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000911 } else if (platform_sp && platform_sp->IsHost()) {
912 // If the debugserver is local and we aren't disabling STDIO, lets use
913 // a pseudo terminal to instead of relying on the 'O' packets for stdio
914 // since 'O' packets can really slow down debugging if the inferior
915 // does a lot of output.
916 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
Konrad Kleine248a1302019-05-23 11:14:47 +0000917 pty.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, nullptr, 0)) {
918 FileSpec slave_name{pty.GetSlaveName(nullptr, 0)};
Chaoren Lind3173f32015-05-29 19:52:29 +0000919
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 if (!stdin_file_spec)
921 stdin_file_spec = slave_name;
Chaoren Lind3173f32015-05-29 19:52:29 +0000922
Kate Stoneb9c1b512016-09-06 20:57:50 +0000923 if (!stdout_file_spec)
924 stdout_file_spec = slave_name;
Greg Clayton71337622011-02-24 22:24:29 +0000925
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 if (!stderr_file_spec)
927 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000928 }
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000929 LLDB_LOGF(
930 log,
931 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
932 "(IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
933 __FUNCTION__,
934 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
935 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
936 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000937 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000938
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000939 LLDB_LOGF(log,
940 "ProcessGDBRemote::%s final STDIO paths after all "
941 "adjustments: stdin=%s, stdout=%s, stderr=%s",
942 __FUNCTION__,
943 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
944 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
945 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Ed Maste81b4c5f2016-01-04 01:43:47 +0000946
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947 if (stdin_file_spec)
948 m_gdb_comm.SetSTDIN(stdin_file_spec);
949 if (stdout_file_spec)
950 m_gdb_comm.SetSTDOUT(stdout_file_spec);
951 if (stderr_file_spec)
952 m_gdb_comm.SetSTDERR(stderr_file_spec);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000953
Kate Stoneb9c1b512016-09-06 20:57:50 +0000954 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
955 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000956
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957 m_gdb_comm.SendLaunchArchPacket(
958 GetTarget().GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000959
Kate Stoneb9c1b512016-09-06 20:57:50 +0000960 const char *launch_event_data = launch_info.GetLaunchEventData();
Konrad Kleine248a1302019-05-23 11:14:47 +0000961 if (launch_event_data != nullptr && *launch_event_data != '\0')
Kate Stoneb9c1b512016-09-06 20:57:50 +0000962 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
Eugene Zelenko0722f082015-10-24 01:28:05 +0000963
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 if (working_dir) {
965 m_gdb_comm.SetWorkingDir(working_dir);
966 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000967
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 // Send the environment and the program + arguments after we connect
Pavel Labath62930e52018-01-10 11:57:31 +0000969 m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
Ewan Crawford78baa192015-05-13 09:18:18 +0000970
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 {
972 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +0000973 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
974 std::chrono::seconds(10));
Ewan Crawford78baa192015-05-13 09:18:18 +0000975
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
977 if (arg_packet_err == 0) {
978 std::string error_str;
979 if (m_gdb_comm.GetLaunchSuccess(error_str)) {
980 SetID(m_gdb_comm.GetCurrentProcessID());
981 } else {
982 error.SetErrorString(error_str.c_str());
983 }
984 } else {
985 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
986 arg_packet_err);
987 }
988 }
989
990 if (GetID() == LLDB_INVALID_PROCESS_ID) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000991 LLDB_LOGF(log, "failed to connect to debugserver: %s",
992 error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 KillDebugserverProcess();
994 return error;
995 }
996
997 StringExtractorGDBRemote response;
998 if (m_gdb_comm.GetStopReply(response)) {
Ewan Crawford78baa192015-05-13 09:18:18 +0000999 SetLastStopPacket(response);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 // '?' Packets must be handled differently in non-stop mode
1001 if (GetTarget().GetNonStopModeEnabled())
1002 HandleStopReplySequence();
1003
1004 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1005
1006 if (process_arch.IsValid()) {
1007 GetTarget().MergeArchitecture(process_arch);
1008 } else {
1009 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1010 if (host_arch.IsValid())
1011 GetTarget().MergeArchitecture(host_arch);
1012 }
1013
1014 SetPrivateState(SetThreadStopInfo(response));
1015
1016 if (!disable_stdio) {
Pavel Labath07d6f882017-12-11 10:09:14 +00001017 if (pty.GetMasterFileDescriptor() != PseudoTerminal::invalid_fd)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 SetSTDIOFileDescriptor(pty.ReleaseMasterFileDescriptor());
1019 }
1020 }
1021 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001022 LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
Ewan Crawford78baa192015-05-13 09:18:18 +00001023 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024 } else {
1025 // Set our user ID to an invalid process ID.
1026 SetID(LLDB_INVALID_PROCESS_ID);
1027 error.SetErrorStringWithFormat(
1028 "failed to get object file from '%s' for arch %s",
1029 exe_module->GetFileSpec().GetFilename().AsCString(),
1030 exe_module->GetArchitecture().GetArchitectureName());
1031 }
1032 return error;
Ewan Crawford78baa192015-05-13 09:18:18 +00001033}
1034
Zachary Turner97206d52017-05-12 04:51:55 +00001035Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
1036 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037 // Only connect if we have a valid connect URL
1038 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1039
Zachary Turner31659452016-11-17 21:15:14 +00001040 if (!connect_url.empty()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001041 LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
1042 connect_url.str().c_str());
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001043 std::unique_ptr<ConnectionFileDescriptor> conn_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044 new ConnectionFileDescriptor());
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001045 if (conn_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 const uint32_t max_retry_count = 50;
1047 uint32_t retry_count = 0;
1048 while (!m_gdb_comm.IsConnected()) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001049 if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
1050 m_gdb_comm.SetConnection(conn_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051 break;
1052 } else if (error.WasInterrupted()) {
1053 // If we were interrupted, don't keep retrying.
1054 break;
1055 }
1056
1057 retry_count++;
1058
1059 if (retry_count >= max_retry_count)
1060 break;
1061
1062 usleep(100000);
1063 }
1064 }
1065 }
1066
1067 if (!m_gdb_comm.IsConnected()) {
1068 if (error.Success())
1069 error.SetErrorString("not connected to remote gdb server");
1070 return error;
1071 }
1072
Adrian Prantl05097242018-04-30 16:49:04 +00001073 // Start the communications read thread so all incoming data can be parsed
1074 // into packets and queued as they arrive.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 if (GetTarget().GetNonStopModeEnabled())
1076 m_gdb_comm.StartReadThread();
1077
Adrian Prantl05097242018-04-30 16:49:04 +00001078 // We always seem to be able to open a connection to a local port so we need
1079 // to make sure we can then send data to it. If we can't then we aren't
1080 // actually connected to anything, so try and do the handshake with the
1081 // remote GDB server and make sure that goes alright.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 if (!m_gdb_comm.HandshakeWithServer(&error)) {
1083 m_gdb_comm.Disconnect();
1084 if (error.Success())
1085 error.SetErrorString("not connected to remote gdb server");
1086 return error;
1087 }
1088
1089 // Send $QNonStop:1 packet on startup if required
1090 if (GetTarget().GetNonStopModeEnabled())
1091 GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true));
1092
1093 m_gdb_comm.GetEchoSupported();
1094 m_gdb_comm.GetThreadSuffixSupported();
1095 m_gdb_comm.GetListThreadsInStopReplySupported();
1096 m_gdb_comm.GetHostInfo();
1097 m_gdb_comm.GetVContSupported('c');
1098 m_gdb_comm.GetVAttachOrWaitSupported();
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001099 m_gdb_comm.EnableErrorStringInPacket();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100
1101 // Ask the remote server for the default thread id
1102 if (GetTarget().GetNonStopModeEnabled())
1103 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1104
1105 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1106 for (size_t idx = 0; idx < num_cmds; idx++) {
1107 StringExtractorGDBRemote response;
1108 m_gdb_comm.SendPacketAndWaitForResponse(
1109 GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1110 }
1111 return error;
1112}
1113
1114void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
1115 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001116 LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117 if (GetID() != LLDB_INVALID_PROCESS_ID) {
1118 BuildDynamicRegisterInfo(false);
1119
1120 // See if the GDB server supports the qHostInfo information
1121
Adrian Prantl05097242018-04-30 16:49:04 +00001122 // See if the GDB server supports the qProcessInfo packet, if so prefer
1123 // that over the Host information as it will be more specific to our
1124 // process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125
1126 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1127 if (remote_process_arch.IsValid()) {
1128 process_arch = remote_process_arch;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001129 LLDB_LOGF(log,
1130 "ProcessGDBRemote::%s gdb-remote had process architecture, "
1131 "using %s %s",
1132 __FUNCTION__,
1133 process_arch.GetArchitectureName()
1134 ? process_arch.GetArchitectureName()
1135 : "<null>",
1136 process_arch.GetTriple().getTriple().c_str()
1137 ? process_arch.GetTriple().getTriple().c_str()
1138 : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 } else {
1140 process_arch = m_gdb_comm.GetHostArchitecture();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001141 LLDB_LOGF(log,
1142 "ProcessGDBRemote::%s gdb-remote did not have process "
1143 "architecture, using gdb-remote host architecture %s %s",
1144 __FUNCTION__,
1145 process_arch.GetArchitectureName()
1146 ? process_arch.GetArchitectureName()
1147 : "<null>",
1148 process_arch.GetTriple().getTriple().c_str()
1149 ? process_arch.GetTriple().getTriple().c_str()
1150 : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001151 }
1152
1153 if (process_arch.IsValid()) {
1154 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1155 if (target_arch.IsValid()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001156 LLDB_LOGF(log,
1157 "ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1158 __FUNCTION__,
1159 target_arch.GetArchitectureName()
1160 ? target_arch.GetArchitectureName()
1161 : "<null>",
1162 target_arch.GetTriple().getTriple().c_str()
1163 ? target_arch.GetTriple().getTriple().c_str()
1164 : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165
1166 // If the remote host is ARM and we have apple as the vendor, then
1167 // ARM executables and shared libraries can have mixed ARM
1168 // architectures.
1169 // You can have an armv6 executable, and if the host is armv7, then the
1170 // system will load the best possible architecture for all shared
Adrian Prantl05097242018-04-30 16:49:04 +00001171 // libraries it has, so we really need to take the remote host
1172 // architecture as our defacto architecture in this case.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173
1174 if ((process_arch.GetMachine() == llvm::Triple::arm ||
1175 process_arch.GetMachine() == llvm::Triple::thumb) &&
1176 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1177 GetTarget().SetArchitecture(process_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001178 LLDB_LOGF(log,
1179 "ProcessGDBRemote::%s remote process is ARM/Apple, "
1180 "setting target arch to %s %s",
1181 __FUNCTION__,
1182 process_arch.GetArchitectureName()
1183 ? process_arch.GetArchitectureName()
1184 : "<null>",
1185 process_arch.GetTriple().getTriple().c_str()
1186 ? process_arch.GetTriple().getTriple().c_str()
1187 : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001188 } else {
1189 // Fill in what is missing in the triple
1190 const llvm::Triple &remote_triple = process_arch.GetTriple();
1191 llvm::Triple new_target_triple = target_arch.GetTriple();
1192 if (new_target_triple.getVendorName().size() == 0) {
1193 new_target_triple.setVendor(remote_triple.getVendor());
1194
1195 if (new_target_triple.getOSName().size() == 0) {
1196 new_target_triple.setOS(remote_triple.getOS());
1197
1198 if (new_target_triple.getEnvironmentName().size() == 0)
1199 new_target_triple.setEnvironment(
1200 remote_triple.getEnvironment());
1201 }
1202
1203 ArchSpec new_target_arch = target_arch;
1204 new_target_arch.SetTriple(new_target_triple);
1205 GetTarget().SetArchitecture(new_target_arch);
1206 }
1207 }
1208
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001209 LLDB_LOGF(log,
1210 "ProcessGDBRemote::%s final target arch after "
1211 "adjustments for remote architecture: %s %s",
1212 __FUNCTION__,
1213 target_arch.GetArchitectureName()
1214 ? target_arch.GetArchitectureName()
1215 : "<null>",
1216 target_arch.GetTriple().getTriple().c_str()
1217 ? target_arch.GetTriple().getTriple().c_str()
1218 : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001219 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001220 // The target doesn't have a valid architecture yet, set it from the
1221 // architecture we got from the remote GDB server
Kate Stoneb9c1b512016-09-06 20:57:50 +00001222 GetTarget().SetArchitecture(process_arch);
1223 }
1224 }
1225
Adrian Prantl05097242018-04-30 16:49:04 +00001226 // Find out which StructuredDataPlugins are supported by the debug monitor.
1227 // These plugins transmit data over async $J packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001228 auto supported_packets_array =
1229 m_gdb_comm.GetSupportedStructuredDataPlugins();
1230 if (supported_packets_array)
1231 MapSupportedStructuredDataPlugins(*supported_packets_array);
1232 }
1233}
1234
1235void ProcessGDBRemote::DidLaunch() {
1236 ArchSpec process_arch;
1237 DidLaunchOrAttach(process_arch);
1238}
1239
Zachary Turner97206d52017-05-12 04:51:55 +00001240Status ProcessGDBRemote::DoAttachToProcessWithID(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1242 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00001243 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001244
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001245 LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246
1247 // Clear out and clean up from any current state
1248 Clear();
1249 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1250 error = EstablishConnectionIfNeeded(attach_info);
1251 if (error.Success()) {
1252 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1253
1254 char packet[64];
1255 const int packet_len =
1256 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1257 SetID(attach_pid);
1258 m_async_broadcaster.BroadcastEvent(
1259 eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1260 } else
1261 SetExitStatus(-1, error.AsCString());
1262 }
1263
1264 return error;
1265}
1266
Zachary Turner97206d52017-05-12 04:51:55 +00001267Status ProcessGDBRemote::DoAttachToProcessWithName(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001268 const char *process_name, const ProcessAttachInfo &attach_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001269 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 // Clear out and clean up from any current state
1271 Clear();
1272
1273 if (process_name && process_name[0]) {
1274 error = EstablishConnectionIfNeeded(attach_info);
1275 if (error.Success()) {
1276 StreamString packet;
1277
1278 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1279
1280 if (attach_info.GetWaitForLaunch()) {
1281 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1282 packet.PutCString("vAttachWait");
1283 } else {
1284 if (attach_info.GetIgnoreExisting())
1285 packet.PutCString("vAttachWait");
1286 else
1287 packet.PutCString("vAttachOrWait");
1288 }
1289 } else
1290 packet.PutCString("vAttachName");
1291 packet.PutChar(';');
1292 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1293 endian::InlHostByteOrder(),
1294 endian::InlHostByteOrder());
1295
1296 m_async_broadcaster.BroadcastEvent(
1297 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001298 new EventDataBytes(packet.GetString().data(), packet.GetSize()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299
1300 } else
1301 SetExitStatus(-1, error.AsCString());
1302 }
1303 return error;
1304}
1305
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001306lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options,
1307 Status &error) {
1308 return m_gdb_comm.SendStartTracePacket(options, error);
1309}
1310
1311Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
1312 return m_gdb_comm.SendStopTracePacket(uid, thread_id);
1313}
1314
1315Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
1316 llvm::MutableArrayRef<uint8_t> &buffer,
1317 size_t offset) {
1318 return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset);
1319}
1320
1321Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
1322 llvm::MutableArrayRef<uint8_t> &buffer,
1323 size_t offset) {
1324 return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset);
1325}
1326
1327Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid,
1328 TraceOptions &options) {
1329 return m_gdb_comm.SendGetTraceConfigPacket(uid, options);
1330}
1331
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332void ProcessGDBRemote::DidExit() {
1333 // When we exit, disconnect from the GDB server communications
1334 m_gdb_comm.Disconnect();
1335}
1336
1337void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1338 // If you can figure out what the architecture is, fill it in here.
1339 process_arch.Clear();
1340 DidLaunchOrAttach(process_arch);
1341}
1342
Zachary Turner97206d52017-05-12 04:51:55 +00001343Status ProcessGDBRemote::WillResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 m_continue_c_tids.clear();
1345 m_continue_C_tids.clear();
1346 m_continue_s_tids.clear();
1347 m_continue_S_tids.clear();
1348 m_jstopinfo_sp.reset();
1349 m_jthreadsinfo_sp.reset();
Zachary Turner97206d52017-05-12 04:51:55 +00001350 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001351}
1352
Zachary Turner97206d52017-05-12 04:51:55 +00001353Status ProcessGDBRemote::DoResume() {
1354 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001355 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001356 LLDB_LOGF(log, "ProcessGDBRemote::Resume()");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001357
1358 ListenerSP listener_sp(
1359 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1360 if (listener_sp->StartListeningForEvents(
1361 &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
1362 listener_sp->StartListeningForEvents(
1363 &m_async_broadcaster,
1364 ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1365
1366 const size_t num_threads = GetThreadList().GetSize();
1367
1368 StreamString continue_packet;
1369 bool continue_packet_error = false;
1370 if (m_gdb_comm.HasAnyVContSupport()) {
1371 if (!GetTarget().GetNonStopModeEnabled() &&
1372 (m_continue_c_tids.size() == num_threads ||
1373 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1374 m_continue_s_tids.empty() && m_continue_S_tids.empty()))) {
1375 // All threads are continuing, just send a "c" packet
1376 continue_packet.PutCString("c");
1377 } else {
1378 continue_packet.PutCString("vCont");
1379
1380 if (!m_continue_c_tids.empty()) {
1381 if (m_gdb_comm.GetVContSupported('c')) {
1382 for (tid_collection::const_iterator
1383 t_pos = m_continue_c_tids.begin(),
1384 t_end = m_continue_c_tids.end();
1385 t_pos != t_end; ++t_pos)
1386 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1387 } else
1388 continue_packet_error = true;
1389 }
1390
1391 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1392 if (m_gdb_comm.GetVContSupported('C')) {
1393 for (tid_sig_collection::const_iterator
1394 s_pos = m_continue_C_tids.begin(),
1395 s_end = m_continue_C_tids.end();
1396 s_pos != s_end; ++s_pos)
1397 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
1398 s_pos->first);
1399 } else
1400 continue_packet_error = true;
1401 }
1402
1403 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1404 if (m_gdb_comm.GetVContSupported('s')) {
1405 for (tid_collection::const_iterator
1406 t_pos = m_continue_s_tids.begin(),
1407 t_end = m_continue_s_tids.end();
1408 t_pos != t_end; ++t_pos)
1409 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1410 } else
1411 continue_packet_error = true;
1412 }
1413
1414 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1415 if (m_gdb_comm.GetVContSupported('S')) {
1416 for (tid_sig_collection::const_iterator
1417 s_pos = m_continue_S_tids.begin(),
1418 s_end = m_continue_S_tids.end();
1419 s_pos != s_end; ++s_pos)
1420 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
1421 s_pos->first);
1422 } else
1423 continue_packet_error = true;
1424 }
1425
1426 if (continue_packet_error)
Zachary Turnerc1564272016-11-16 21:15:24 +00001427 continue_packet.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001428 }
1429 } else
1430 continue_packet_error = true;
1431
1432 if (continue_packet_error) {
Adrian Prantl05097242018-04-30 16:49:04 +00001433 // Either no vCont support, or we tried to use part of the vCont packet
1434 // that wasn't supported by the remote GDB server. We need to try and
1435 // make a simple packet that can do our continue
Kate Stoneb9c1b512016-09-06 20:57:50 +00001436 const size_t num_continue_c_tids = m_continue_c_tids.size();
1437 const size_t num_continue_C_tids = m_continue_C_tids.size();
1438 const size_t num_continue_s_tids = m_continue_s_tids.size();
1439 const size_t num_continue_S_tids = m_continue_S_tids.size();
1440 if (num_continue_c_tids > 0) {
1441 if (num_continue_c_tids == num_threads) {
1442 // All threads are resuming...
1443 m_gdb_comm.SetCurrentThreadForRun(-1);
1444 continue_packet.PutChar('c');
1445 continue_packet_error = false;
1446 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1447 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1448 // Only one thread is continuing
1449 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1450 continue_packet.PutChar('c');
1451 continue_packet_error = false;
1452 }
1453 }
1454
1455 if (continue_packet_error && num_continue_C_tids > 0) {
1456 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1457 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1458 num_continue_S_tids == 0) {
1459 const int continue_signo = m_continue_C_tids.front().second;
1460 // Only one thread is continuing
1461 if (num_continue_C_tids > 1) {
Adrian Prantl05097242018-04-30 16:49:04 +00001462 // More that one thread with a signal, yet we don't have vCont
1463 // support and we are being asked to resume each thread with a
1464 // signal, we need to make sure they are all the same signal, or we
1465 // can't issue the continue accurately with the current support...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466 if (num_continue_C_tids > 1) {
1467 continue_packet_error = false;
1468 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1469 if (m_continue_C_tids[i].second != continue_signo)
1470 continue_packet_error = true;
1471 }
1472 }
1473 if (!continue_packet_error)
1474 m_gdb_comm.SetCurrentThreadForRun(-1);
1475 } else {
1476 // Set the continue thread ID
1477 continue_packet_error = false;
1478 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1479 }
1480 if (!continue_packet_error) {
1481 // Add threads continuing with the same signo...
1482 continue_packet.Printf("C%2.2x", continue_signo);
1483 }
1484 }
1485 }
1486
1487 if (continue_packet_error && num_continue_s_tids > 0) {
1488 if (num_continue_s_tids == num_threads) {
1489 // All threads are resuming...
1490 m_gdb_comm.SetCurrentThreadForRun(-1);
1491
1492 // If in Non-Stop-Mode use vCont when stepping
1493 if (GetTarget().GetNonStopModeEnabled()) {
1494 if (m_gdb_comm.GetVContSupported('s'))
1495 continue_packet.PutCString("vCont;s");
1496 else
1497 continue_packet.PutChar('s');
1498 } else
1499 continue_packet.PutChar('s');
1500
1501 continue_packet_error = false;
1502 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1503 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1504 // Only one thread is stepping
1505 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1506 continue_packet.PutChar('s');
1507 continue_packet_error = false;
1508 }
1509 }
1510
1511 if (!continue_packet_error && num_continue_S_tids > 0) {
1512 if (num_continue_S_tids == num_threads) {
1513 const int step_signo = m_continue_S_tids.front().second;
1514 // Are all threads trying to step with the same signal?
1515 continue_packet_error = false;
1516 if (num_continue_S_tids > 1) {
1517 for (size_t i = 1; i < num_threads; ++i) {
1518 if (m_continue_S_tids[i].second != step_signo)
1519 continue_packet_error = true;
1520 }
1521 }
1522 if (!continue_packet_error) {
1523 // Add threads stepping with the same signo...
1524 m_gdb_comm.SetCurrentThreadForRun(-1);
1525 continue_packet.Printf("S%2.2x", step_signo);
1526 }
1527 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1528 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1529 // Only one thread is stepping with signal
1530 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1531 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1532 continue_packet_error = false;
1533 }
1534 }
1535 }
1536
1537 if (continue_packet_error) {
1538 error.SetErrorString("can't make continue packet for this resume");
1539 } else {
1540 EventSP event_sp;
1541 if (!m_async_thread.IsJoinable()) {
1542 error.SetErrorString("Trying to resume but the async thread is dead.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001543 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
1544 "async thread is dead.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001545 return error;
1546 }
1547
1548 m_async_broadcaster.BroadcastEvent(
1549 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001550 new EventDataBytes(continue_packet.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001551 continue_packet.GetSize()));
1552
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001553 if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001554 error.SetErrorString("Resume timed out.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001555 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001556 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1557 error.SetErrorString("Broadcast continue, but the async thread was "
1558 "killed before we got an ack back.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001559 LLDB_LOGF(log,
1560 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1561 "async thread was killed before we got an ack back.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001562 return error;
1563 }
1564 }
1565 }
1566
1567 return error;
1568}
1569
1570void ProcessGDBRemote::HandleStopReplySequence() {
1571 while (true) {
1572 // Send vStopped
1573 StringExtractorGDBRemote response;
1574 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1575
1576 // OK represents end of signal list
1577 if (response.IsOKResponse())
1578 break;
1579
1580 // If not OK or a normal packet we have a problem
1581 if (!response.IsNormalResponse())
1582 break;
1583
1584 SetLastStopPacket(response);
1585 }
1586}
1587
1588void ProcessGDBRemote::ClearThreadIDList() {
1589 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1590 m_thread_ids.clear();
1591 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00001592}
1593
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001594size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
1596 m_thread_ids.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001597 size_t comma_pos;
1598 lldb::tid_t tid;
1599 while ((comma_pos = value.find(',')) != std::string::npos) {
1600 value[comma_pos] = '\0';
1601 // thread in big endian hex
1602 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001603 if (tid != LLDB_INVALID_THREAD_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001604 m_thread_ids.push_back(tid);
1605 value.erase(0, comma_pos + 1);
1606 }
1607 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1608 if (tid != LLDB_INVALID_THREAD_ID)
1609 m_thread_ids.push_back(tid);
1610 return m_thread_ids.size();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001611}
1612
Jason Molenda545304d2015-12-18 00:45:35 +00001613size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001614ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
1615 m_thread_pcs.clear();
1616 size_t comma_pos;
1617 lldb::addr_t pc;
1618 while ((comma_pos = value.find(',')) != std::string::npos) {
1619 value[comma_pos] = '\0';
1620 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1621 if (pc != LLDB_INVALID_ADDRESS)
1622 m_thread_pcs.push_back(pc);
1623 value.erase(0, comma_pos + 1);
1624 }
1625 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1626 if (pc != LLDB_INVALID_THREAD_ID)
1627 m_thread_pcs.push_back(pc);
1628 return m_thread_pcs.size();
Jason Molenda545304d2015-12-18 00:45:35 +00001629}
1630
Kate Stoneb9c1b512016-09-06 20:57:50 +00001631bool ProcessGDBRemote::UpdateThreadIDList() {
1632 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001633
Kate Stoneb9c1b512016-09-06 20:57:50 +00001634 if (m_jthreadsinfo_sp) {
1635 // If we have the JSON threads info, we can get the thread list from that
1636 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1637 if (thread_infos && thread_infos->GetSize() > 0) {
1638 m_thread_ids.clear();
1639 m_thread_pcs.clear();
1640 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1641 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1642 if (thread_dict) {
1643 // Set the thread stop info from the JSON dictionary
1644 SetThreadStopInfo(thread_dict);
1645 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1646 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1647 m_thread_ids.push_back(tid);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001648 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001649 return true; // Keep iterating through all thread_info objects
1650 });
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001651 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001652 if (!m_thread_ids.empty())
1653 return true;
1654 } else {
1655 // See if we can get the thread IDs from the current stop reply packets
1656 // that might contain a "threads" key/value pair
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001657
Kate Stoneb9c1b512016-09-06 20:57:50 +00001658 // Lock the thread stack while we access it
1659 // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1660 std::unique_lock<std::recursive_mutex> stop_stack_lock(
1661 m_last_stop_packet_mutex, std::defer_lock);
1662 if (stop_stack_lock.try_lock()) {
1663 // Get the number of stop packets on the stack
1664 int nItems = m_stop_packet_stack.size();
1665 // Iterate over them
1666 for (int i = 0; i < nItems; i++) {
1667 // Get the thread stop info
1668 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1669 const std::string &stop_info_str = stop_info.GetStringRef();
Jason Molenda545304d2015-12-18 00:45:35 +00001670
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671 m_thread_pcs.clear();
1672 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1673 if (thread_pcs_pos != std::string::npos) {
1674 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1675 const size_t end = stop_info_str.find(';', start);
1676 if (end != std::string::npos) {
1677 std::string value = stop_info_str.substr(start, end - start);
1678 UpdateThreadPCsFromStopReplyThreadsValue(value);
1679 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001680 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001681
Kate Stoneb9c1b512016-09-06 20:57:50 +00001682 const size_t threads_pos = stop_info_str.find(";threads:");
1683 if (threads_pos != std::string::npos) {
1684 const size_t start = threads_pos + strlen(";threads:");
1685 const size_t end = stop_info_str.find(';', start);
1686 if (end != std::string::npos) {
1687 std::string value = stop_info_str.substr(start, end - start);
1688 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1689 return true;
1690 }
1691 }
1692 }
1693 }
1694 }
1695
1696 bool sequence_mutex_unavailable = false;
1697 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1698 if (sequence_mutex_unavailable) {
1699 return false; // We just didn't get the list
1700 }
1701 return true;
1702}
1703
1704bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
1705 ThreadList &new_thread_list) {
1706 // locker will keep a mutex locked until it goes out of scope
1707 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
Pavel Labathe8a7b982017-02-06 19:31:09 +00001708 LLDB_LOGV(log, "pid = {0}", GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001709
1710 size_t num_thread_ids = m_thread_ids.size();
1711 // The "m_thread_ids" thread ID list should always be updated after each stop
1712 // reply packet, but in case it isn't, update it here.
1713 if (num_thread_ids == 0) {
1714 if (!UpdateThreadIDList())
1715 return false;
1716 num_thread_ids = m_thread_ids.size();
1717 }
1718
1719 ThreadList old_thread_list_copy(old_thread_list);
1720 if (num_thread_ids > 0) {
1721 for (size_t i = 0; i < num_thread_ids; ++i) {
1722 tid_t tid = m_thread_ids[i];
1723 ThreadSP thread_sp(
1724 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1725 if (!thread_sp) {
Jonas Devlieghere796ac802019-02-11 23:13:08 +00001726 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
Pavel Labathe8a7b982017-02-06 19:31:09 +00001727 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1728 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729 } else {
Pavel Labathe8a7b982017-02-06 19:31:09 +00001730 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1731 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732 }
Pavel Labathe0a5b572017-01-20 14:17:16 +00001733
1734 SetThreadPc(thread_sp, i);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001735 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1736 }
1737 }
1738
Adrian Prantl05097242018-04-30 16:49:04 +00001739 // Whatever that is left in old_thread_list_copy are not present in
1740 // new_thread_list. Remove non-existent threads from internal id table.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001741 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1742 for (size_t i = 0; i < old_num_thread_ids; i++) {
1743 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1744 if (old_thread_sp) {
1745 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1746 m_thread_id_to_index_id_map.erase(old_thread_id);
1747 }
1748 }
1749
1750 return true;
1751}
1752
Pavel Labathe0a5b572017-01-20 14:17:16 +00001753void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1754 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1755 GetByteOrder() != eByteOrderInvalid) {
1756 ThreadGDBRemote *gdb_thread =
1757 static_cast<ThreadGDBRemote *>(thread_sp.get());
1758 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1759 if (reg_ctx_sp) {
1760 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1761 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1762 if (pc_regnum != LLDB_INVALID_REGNUM) {
1763 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1764 }
1765 }
1766 }
1767}
1768
Kate Stoneb9c1b512016-09-06 20:57:50 +00001769bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1770 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1771 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1772 // packet
1773 if (thread_infos_sp) {
1774 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1775 if (thread_infos) {
1776 lldb::tid_t tid;
1777 const size_t n = thread_infos->GetSize();
1778 for (size_t i = 0; i < n; ++i) {
1779 StructuredData::Dictionary *thread_dict =
1780 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1781 if (thread_dict) {
1782 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1783 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1784 if (tid == thread->GetID())
1785 return (bool)SetThreadStopInfo(thread_dict);
1786 }
1787 }
1788 }
1789 }
1790 }
1791 return false;
1792}
1793
1794bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1795 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1796 // packet
1797 if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1798 return true;
1799
1800 // See if we got thread stop info for any threads valid stop info reasons
Adrian Prantl05097242018-04-30 16:49:04 +00001801 // threads via the "jstopinfo" packet stop reply packet key/value pair?
Kate Stoneb9c1b512016-09-06 20:57:50 +00001802 if (m_jstopinfo_sp) {
1803 // If we have "jstopinfo" then we have stop descriptions for all threads
Adrian Prantl05097242018-04-30 16:49:04 +00001804 // that have stop reasons, and if there is no entry for a thread, then it
1805 // has no stop reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001806 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1807 if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1808 thread->SetStopInfo(StopInfoSP());
Greg Clayton9e920902012-04-10 02:25:43 +00001809 }
1810 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001811 }
1812
1813 // Fall back to using the qThreadStopInfo packet
1814 StringExtractorGDBRemote stop_packet;
1815 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1816 return SetThreadStopInfo(stop_packet) == eStateStopped;
1817 return false;
Greg Clayton9e920902012-04-10 02:25:43 +00001818}
1819
Kate Stoneb9c1b512016-09-06 20:57:50 +00001820ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1821 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1822 uint8_t signo, const std::string &thread_name, const std::string &reason,
1823 const std::string &description, uint32_t exc_type,
1824 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1825 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1826 // queue_serial are valid
1827 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1828 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1829 ThreadSP thread_sp;
1830 if (tid != LLDB_INVALID_THREAD_ID) {
1831 // Scope for "locker" below
Greg Clayton9e920902012-04-10 02:25:43 +00001832 {
Adrian Prantl05097242018-04-30 16:49:04 +00001833 // m_thread_list_real does have its own mutex, but we need to hold onto
1834 // the mutex between the call to m_thread_list_real.FindThreadByID(...)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001835 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1836 std::lock_guard<std::recursive_mutex> guard(
1837 m_thread_list_real.GetMutex());
1838 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1839
1840 if (!thread_sp) {
1841 // Create the thread if we need to
Jonas Devlieghere796ac802019-02-11 23:13:08 +00001842 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001843 m_thread_list_real.AddThread(thread_sp);
1844 }
Greg Clayton9e920902012-04-10 02:25:43 +00001845 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001846
Kate Stoneb9c1b512016-09-06 20:57:50 +00001847 if (thread_sp) {
1848 ThreadGDBRemote *gdb_thread =
1849 static_cast<ThreadGDBRemote *>(thread_sp.get());
1850 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1851
Pavel Labathe0a5b572017-01-20 14:17:16 +00001852 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1853 if (iter != m_thread_ids.end()) {
1854 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1855 }
1856
Kate Stoneb9c1b512016-09-06 20:57:50 +00001857 for (const auto &pair : expedited_register_map) {
1858 StringExtractor reg_value_extractor;
1859 reg_value_extractor.GetStringRef() = pair.second;
1860 DataBufferSP buffer_sp(new DataBufferHeap(
1861 reg_value_extractor.GetStringRef().size() / 2, 0));
1862 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1863 gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
1864 }
1865
Konrad Kleine248a1302019-05-23 11:14:47 +00001866 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001867
1868 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1869 // Check if the GDB server was able to provide the queue name, kind and
1870 // serial number
1871 if (queue_vars_valid)
1872 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1873 queue_serial, dispatch_queue_t,
1874 associated_with_dispatch_queue);
1875 else
1876 gdb_thread->ClearQueueInfo();
1877
1878 gdb_thread->SetAssociatedWithLibdispatchQueue(
1879 associated_with_dispatch_queue);
1880
1881 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1882 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1883
1884 // Make sure we update our thread stop reason just once
1885 if (!thread_sp->StopInfoIsUpToDate()) {
1886 thread_sp->SetStopInfo(StopInfoSP());
1887 // If there's a memory thread backed by this thread, we need to use it
Jonas Devlieghere8db3f7e2018-04-13 11:31:34 +00001888 // to calculate StopInfo.
1889 if (ThreadSP memory_thread_sp =
1890 m_thread_list.GetBackingThread(thread_sp))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001891 thread_sp = memory_thread_sp;
1892
1893 if (exc_type != 0) {
1894 const size_t exc_data_size = exc_data.size();
1895
1896 thread_sp->SetStopInfo(
1897 StopInfoMachException::CreateStopReasonWithMachException(
1898 *thread_sp, exc_type, exc_data_size,
1899 exc_data_size >= 1 ? exc_data[0] : 0,
1900 exc_data_size >= 2 ? exc_data[1] : 0,
1901 exc_data_size >= 3 ? exc_data[2] : 0));
1902 } else {
1903 bool handled = false;
1904 bool did_exec = false;
1905 if (!reason.empty()) {
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001906 if (reason == "trace") {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001907 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1908 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1909 ->GetBreakpointSiteList()
1910 .FindByAddress(pc);
1911
Adrian Prantl05097242018-04-30 16:49:04 +00001912 // If the current pc is a breakpoint site then the StopInfo
1913 // should be set to Breakpoint Otherwise, it will be set to
1914 // Trace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001915 if (bp_site_sp &&
1916 bp_site_sp->ValidForThisThread(thread_sp.get())) {
1917 thread_sp->SetStopInfo(
1918 StopInfo::CreateStopReasonWithBreakpointSiteID(
1919 *thread_sp, bp_site_sp->GetID()));
1920 } else
1921 thread_sp->SetStopInfo(
1922 StopInfo::CreateStopReasonToTrace(*thread_sp));
1923 handled = true;
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001924 } else if (reason == "breakpoint") {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001925 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1926 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1927 ->GetBreakpointSiteList()
1928 .FindByAddress(pc);
1929 if (bp_site_sp) {
1930 // If the breakpoint is for this thread, then we'll report the
Adrian Prantl05097242018-04-30 16:49:04 +00001931 // hit, but if it is for another thread, we can just report no
1932 // reason. We don't need to worry about stepping over the
1933 // breakpoint here, that will be taken care of when the thread
1934 // resumes and notices that there's a breakpoint under the pc.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935 handled = true;
1936 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1937 thread_sp->SetStopInfo(
1938 StopInfo::CreateStopReasonWithBreakpointSiteID(
1939 *thread_sp, bp_site_sp->GetID()));
1940 } else {
1941 StopInfoSP invalid_stop_info_sp;
1942 thread_sp->SetStopInfo(invalid_stop_info_sp);
Jason Molenda545304d2015-12-18 00:45:35 +00001943 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001944 }
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001945 } else if (reason == "trap") {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001946 // Let the trap just use the standard signal stop reason below...
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001947 } else if (reason == "watchpoint") {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001948 StringExtractor desc_extractor(description.c_str());
1949 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1950 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1951 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1952 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1953 if (wp_addr != LLDB_INVALID_ADDRESS) {
1954 WatchpointSP wp_sp;
1955 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1956 if ((core >= ArchSpec::kCore_mips_first &&
1957 core <= ArchSpec::kCore_mips_last) ||
1958 (core >= ArchSpec::eCore_arm_generic &&
1959 core <= ArchSpec::eCore_arm_aarch64))
1960 wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1961 wp_hit_addr);
1962 if (!wp_sp)
1963 wp_sp =
1964 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1965 if (wp_sp) {
1966 wp_sp->SetHardwareIndex(wp_index);
1967 watch_id = wp_sp->GetID();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001968 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001969 }
1970 if (watch_id == LLDB_INVALID_WATCH_ID) {
1971 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1972 GDBR_LOG_WATCHPOINTS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001973 LLDB_LOGF(log, "failed to find watchpoint");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001974 }
1975 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1976 *thread_sp, watch_id, wp_hit_addr));
1977 handled = true;
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001978 } else if (reason == "exception") {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001979 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1980 *thread_sp, description.c_str()));
1981 handled = true;
Jonas Devlieghere8d20cfd2018-12-21 22:46:10 +00001982 } else if (reason == "exec") {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001983 did_exec = true;
1984 thread_sp->SetStopInfo(
1985 StopInfo::CreateStopReasonWithExec(*thread_sp));
1986 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001987 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001988 } else if (!signo) {
1989 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1990 lldb::BreakpointSiteSP bp_site_sp =
1991 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1992 pc);
Greg Clayton2e309072015-07-17 23:42:28 +00001993
Kate Stoneb9c1b512016-09-06 20:57:50 +00001994 // If the current pc is a breakpoint site then the StopInfo should
Adrian Prantl05097242018-04-30 16:49:04 +00001995 // be set to Breakpoint even though the remote stub did not set it
1996 // as such. This can happen when the thread is involuntarily
1997 // interrupted (e.g. due to stops on other threads) just as it is
1998 // about to execute the breakpoint instruction.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001999 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
2000 thread_sp->SetStopInfo(
2001 StopInfo::CreateStopReasonWithBreakpointSiteID(
2002 *thread_sp, bp_site_sp->GetID()));
2003 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002004 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002005 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002006
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002007 if (!handled && signo && !did_exec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002008 if (signo == SIGTRAP) {
2009 // Currently we are going to assume SIGTRAP means we are either
2010 // hitting a breakpoint or hardware single stepping.
2011 handled = true;
2012 addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
2013 m_breakpoint_pc_offset;
2014 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
2015 ->GetBreakpointSiteList()
2016 .FindByAddress(pc);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002017
Kate Stoneb9c1b512016-09-06 20:57:50 +00002018 if (bp_site_sp) {
2019 // If the breakpoint is for this thread, then we'll report the
Adrian Prantl05097242018-04-30 16:49:04 +00002020 // hit, but if it is for another thread, we can just report no
2021 // reason. We don't need to worry about stepping over the
2022 // breakpoint here, that will be taken care of when the thread
2023 // resumes and notices that there's a breakpoint under the pc.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002024 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
2025 if (m_breakpoint_pc_offset != 0)
2026 thread_sp->GetRegisterContext()->SetPC(pc);
2027 thread_sp->SetStopInfo(
2028 StopInfo::CreateStopReasonWithBreakpointSiteID(
2029 *thread_sp, bp_site_sp->GetID()));
2030 } else {
2031 StopInfoSP invalid_stop_info_sp;
2032 thread_sp->SetStopInfo(invalid_stop_info_sp);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002033 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002034 } else {
2035 // If we were stepping then assume the stop was the result of
Adrian Prantl05097242018-04-30 16:49:04 +00002036 // the trace. If we were not stepping then report the SIGTRAP.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002037 // FIXME: We are still missing the case where we single step
2038 // over a trap instruction.
2039 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2040 thread_sp->SetStopInfo(
2041 StopInfo::CreateStopReasonToTrace(*thread_sp));
Greg Clayton2e309072015-07-17 23:42:28 +00002042 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002043 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2044 *thread_sp, signo, description.c_str()));
2045 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002046 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002047 if (!handled)
2048 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2049 *thread_sp, signo, description.c_str()));
2050 }
2051
2052 if (!description.empty()) {
2053 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
2054 if (stop_info_sp) {
2055 const char *stop_info_desc = stop_info_sp->GetDescription();
2056 if (!stop_info_desc || !stop_info_desc[0])
2057 stop_info_sp->SetDescription(description.c_str());
2058 } else {
2059 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2060 *thread_sp, description.c_str()));
2061 }
2062 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002063 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002064 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002065 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002066 }
2067 return thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002068}
2069
Greg Clayton2e309072015-07-17 23:42:28 +00002070lldb::ThreadSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00002071ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
2072 static ConstString g_key_tid("tid");
2073 static ConstString g_key_name("name");
2074 static ConstString g_key_reason("reason");
2075 static ConstString g_key_metype("metype");
2076 static ConstString g_key_medata("medata");
2077 static ConstString g_key_qaddr("qaddr");
2078 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2079 static ConstString g_key_associated_with_dispatch_queue(
2080 "associated_with_dispatch_queue");
2081 static ConstString g_key_queue_name("qname");
2082 static ConstString g_key_queue_kind("qkind");
2083 static ConstString g_key_queue_serial_number("qserialnum");
2084 static ConstString g_key_registers("registers");
2085 static ConstString g_key_memory("memory");
2086 static ConstString g_key_address("address");
2087 static ConstString g_key_bytes("bytes");
2088 static ConstString g_key_description("description");
2089 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002090
Kate Stoneb9c1b512016-09-06 20:57:50 +00002091 // Stop with signal and thread info
2092 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2093 uint8_t signo = 0;
2094 std::string value;
2095 std::string thread_name;
2096 std::string reason;
2097 std::string description;
2098 uint32_t exc_type = 0;
2099 std::vector<addr_t> exc_data;
2100 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2101 ExpeditedRegisterMap expedited_register_map;
2102 bool queue_vars_valid = false;
2103 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2104 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2105 std::string queue_name;
2106 QueueKind queue_kind = eQueueKindUnknown;
2107 uint64_t queue_serial_number = 0;
2108 // Iterate through all of the thread dictionary key/value pairs from the
2109 // structured data dictionary
2110
2111 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2112 &signo, &reason, &description, &exc_type, &exc_data,
2113 &thread_dispatch_qaddr, &queue_vars_valid,
2114 &associated_with_dispatch_queue, &dispatch_queue_t,
2115 &queue_name, &queue_kind, &queue_serial_number](
2116 ConstString key,
2117 StructuredData::Object *object) -> bool {
2118 if (key == g_key_tid) {
2119 // thread in big endian hex
2120 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2121 } else if (key == g_key_metype) {
2122 // exception type in big endian hex
2123 exc_type = object->GetIntegerValue(0);
2124 } else if (key == g_key_medata) {
2125 // exception data in big endian hex
2126 StructuredData::Array *array = object->GetAsArray();
2127 if (array) {
2128 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2129 exc_data.push_back(object->GetIntegerValue());
2130 return true; // Keep iterating through all array items
2131 });
2132 }
2133 } else if (key == g_key_name) {
2134 thread_name = object->GetStringValue();
2135 } else if (key == g_key_qaddr) {
2136 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2137 } else if (key == g_key_queue_name) {
2138 queue_vars_valid = true;
2139 queue_name = object->GetStringValue();
2140 } else if (key == g_key_queue_kind) {
2141 std::string queue_kind_str = object->GetStringValue();
2142 if (queue_kind_str == "serial") {
2143 queue_vars_valid = true;
2144 queue_kind = eQueueKindSerial;
2145 } else if (queue_kind_str == "concurrent") {
2146 queue_vars_valid = true;
2147 queue_kind = eQueueKindConcurrent;
2148 }
2149 } else if (key == g_key_queue_serial_number) {
2150 queue_serial_number = object->GetIntegerValue(0);
2151 if (queue_serial_number != 0)
2152 queue_vars_valid = true;
2153 } else if (key == g_key_dispatch_queue_t) {
2154 dispatch_queue_t = object->GetIntegerValue(0);
2155 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2156 queue_vars_valid = true;
2157 } else if (key == g_key_associated_with_dispatch_queue) {
2158 queue_vars_valid = true;
2159 bool associated = object->GetBooleanValue();
2160 if (associated)
2161 associated_with_dispatch_queue = eLazyBoolYes;
2162 else
2163 associated_with_dispatch_queue = eLazyBoolNo;
2164 } else if (key == g_key_reason) {
2165 reason = object->GetStringValue();
2166 } else if (key == g_key_description) {
2167 description = object->GetStringValue();
2168 } else if (key == g_key_registers) {
2169 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2170
2171 if (registers_dict) {
2172 registers_dict->ForEach(
2173 [&expedited_register_map](ConstString key,
2174 StructuredData::Object *object) -> bool {
2175 const uint32_t reg =
2176 StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
2177 if (reg != UINT32_MAX)
2178 expedited_register_map[reg] = object->GetStringValue();
2179 return true; // Keep iterating through all array items
2180 });
2181 }
2182 } else if (key == g_key_memory) {
2183 StructuredData::Array *array = object->GetAsArray();
2184 if (array) {
2185 array->ForEach([this](StructuredData::Object *object) -> bool {
2186 StructuredData::Dictionary *mem_cache_dict =
2187 object->GetAsDictionary();
2188 if (mem_cache_dict) {
2189 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2190 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2191 "address", mem_cache_addr)) {
2192 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
Zachary Turner28333212017-05-12 05:49:54 +00002193 llvm::StringRef str;
2194 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2195 StringExtractor bytes(str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002196 bytes.SetFilePos(0);
2197
2198 const size_t byte_size = bytes.GetStringRef().size() / 2;
2199 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2200 const size_t bytes_copied =
2201 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2202 if (bytes_copied == byte_size)
2203 m_memory_cache.AddL1CacheData(mem_cache_addr,
2204 data_buffer_sp);
2205 }
2206 }
2207 }
2208 }
2209 return true; // Keep iterating through all array items
2210 });
2211 }
2212
2213 } else if (key == g_key_signal)
2214 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2215 return true; // Keep iterating through all dictionary key/value pairs
2216 });
2217
2218 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2219 reason, description, exc_type, exc_data,
2220 thread_dispatch_qaddr, queue_vars_valid,
2221 associated_with_dispatch_queue, dispatch_queue_t,
2222 queue_name, queue_kind, queue_serial_number);
2223}
2224
2225StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2226 stop_packet.SetFilePos(0);
2227 const char stop_type = stop_packet.GetChar();
2228 switch (stop_type) {
2229 case 'T':
2230 case 'S': {
Adrian Prantl05097242018-04-30 16:49:04 +00002231 // This is a bit of a hack, but is is required. If we did exec, we need to
2232 // clear our thread lists and also know to rebuild our dynamic register
2233 // info before we lookup and threads and populate the expedited register
2234 // values so we need to know this right away so we can cleanup and update
2235 // our registers.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002236 const uint32_t stop_id = GetStopID();
2237 if (stop_id == 0) {
Adrian Prantl05097242018-04-30 16:49:04 +00002238 // Our first stop, make sure we have a process ID, and also make sure we
2239 // know about our registers
Kate Stoneb9c1b512016-09-06 20:57:50 +00002240 if (GetID() == LLDB_INVALID_PROCESS_ID) {
2241 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2242 if (pid != LLDB_INVALID_PROCESS_ID)
2243 SetID(pid);
2244 }
2245 BuildDynamicRegisterInfo(true);
2246 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002247 // Stop with signal and thread info
2248 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002249 const uint8_t signo = stop_packet.GetHexU8();
2250 llvm::StringRef key;
2251 llvm::StringRef value;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002252 std::string thread_name;
2253 std::string reason;
2254 std::string description;
2255 uint32_t exc_type = 0;
2256 std::vector<addr_t> exc_data;
2257 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002258 bool queue_vars_valid =
2259 false; // says if locals below that start with "queue_" are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002260 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2261 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002262 std::string queue_name;
2263 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002264 uint64_t queue_serial_number = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265 ExpeditedRegisterMap expedited_register_map;
2266 while (stop_packet.GetNameColonValue(key, value)) {
2267 if (key.compare("metype") == 0) {
2268 // exception type in big endian hex
2269 value.getAsInteger(16, exc_type);
2270 } else if (key.compare("medata") == 0) {
2271 // exception data in big endian hex
2272 uint64_t x;
2273 value.getAsInteger(16, x);
2274 exc_data.push_back(x);
2275 } else if (key.compare("thread") == 0) {
2276 // thread in big endian hex
2277 if (value.getAsInteger(16, tid))
2278 tid = LLDB_INVALID_THREAD_ID;
2279 } else if (key.compare("threads") == 0) {
2280 std::lock_guard<std::recursive_mutex> guard(
2281 m_thread_list_real.GetMutex());
Greg Clayton358cf1e2015-06-25 21:46:34 +00002282
Kate Stoneb9c1b512016-09-06 20:57:50 +00002283 m_thread_ids.clear();
2284 // A comma separated list of all threads in the current
Adrian Prantl05097242018-04-30 16:49:04 +00002285 // process that includes the thread for this stop reply packet
Kate Stoneb9c1b512016-09-06 20:57:50 +00002286 lldb::tid_t tid;
2287 while (!value.empty()) {
2288 llvm::StringRef tid_str;
2289 std::tie(tid_str, value) = value.split(',');
2290 if (tid_str.getAsInteger(16, tid))
2291 tid = LLDB_INVALID_THREAD_ID;
2292 m_thread_ids.push_back(tid);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002293 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294 } else if (key.compare("thread-pcs") == 0) {
2295 m_thread_pcs.clear();
2296 // A comma separated list of all threads in the current
Adrian Prantl05097242018-04-30 16:49:04 +00002297 // process that includes the thread for this stop reply packet
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298 lldb::addr_t pc;
2299 while (!value.empty()) {
2300 llvm::StringRef pc_str;
2301 std::tie(pc_str, value) = value.split(',');
2302 if (pc_str.getAsInteger(16, pc))
2303 pc = LLDB_INVALID_ADDRESS;
2304 m_thread_pcs.push_back(pc);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002305 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002306 } else if (key.compare("jstopinfo") == 0) {
2307 StringExtractor json_extractor(value);
2308 std::string json;
2309 // Now convert the HEX bytes into a string value
2310 json_extractor.GetHexByteString(json);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002311
Kate Stoneb9c1b512016-09-06 20:57:50 +00002312 // This JSON contains thread IDs and thread stop info for all threads.
2313 // It doesn't contain expedited registers, memory or queue info.
2314 m_jstopinfo_sp = StructuredData::ParseJSON(json);
2315 } else if (key.compare("hexname") == 0) {
2316 StringExtractor name_extractor(value);
2317 std::string name;
2318 // Now convert the HEX bytes into a string value
2319 name_extractor.GetHexByteString(thread_name);
2320 } else if (key.compare("name") == 0) {
2321 thread_name = value;
2322 } else if (key.compare("qaddr") == 0) {
2323 value.getAsInteger(16, thread_dispatch_qaddr);
2324 } else if (key.compare("dispatch_queue_t") == 0) {
2325 queue_vars_valid = true;
2326 value.getAsInteger(16, dispatch_queue_t);
2327 } else if (key.compare("qname") == 0) {
2328 queue_vars_valid = true;
2329 StringExtractor name_extractor(value);
2330 // Now convert the HEX bytes into a string value
2331 name_extractor.GetHexByteString(queue_name);
2332 } else if (key.compare("qkind") == 0) {
2333 queue_kind = llvm::StringSwitch<QueueKind>(value)
2334 .Case("serial", eQueueKindSerial)
2335 .Case("concurrent", eQueueKindConcurrent)
2336 .Default(eQueueKindUnknown);
2337 queue_vars_valid = queue_kind != eQueueKindUnknown;
2338 } else if (key.compare("qserialnum") == 0) {
2339 if (!value.getAsInteger(0, queue_serial_number))
2340 queue_vars_valid = true;
2341 } else if (key.compare("reason") == 0) {
2342 reason = value;
2343 } else if (key.compare("description") == 0) {
2344 StringExtractor desc_extractor(value);
2345 // Now convert the HEX bytes into a string value
2346 desc_extractor.GetHexByteString(description);
2347 } else if (key.compare("memory") == 0) {
2348 // Expedited memory. GDB servers can choose to send back expedited
Adrian Prantl05097242018-04-30 16:49:04 +00002349 // memory that can populate the L1 memory cache in the process so that
2350 // things like the frame pointer backchain can be expedited. This will
2351 // help stack backtracing be more efficient by not having to send as
2352 // many memory read requests down the remote GDB server.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002353
2354 // Key/value pair format: memory:<addr>=<bytes>;
2355 // <addr> is a number whose base will be interpreted by the prefix:
2356 // "0x[0-9a-fA-F]+" for hex
2357 // "0[0-7]+" for octal
2358 // "[1-9]+" for decimal
2359 // <bytes> is native endian ASCII hex bytes just like the register
2360 // values
2361 llvm::StringRef addr_str, bytes_str;
2362 std::tie(addr_str, bytes_str) = value.split('=');
2363 if (!addr_str.empty() && !bytes_str.empty()) {
2364 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2365 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2366 StringExtractor bytes(bytes_str);
2367 const size_t byte_size = bytes.GetBytesLeft() / 2;
2368 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2369 const size_t bytes_copied =
2370 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2371 if (bytes_copied == byte_size)
2372 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2373 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002374 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002375 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2376 key.compare("awatch") == 0) {
2377 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2378 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2379 value.getAsInteger(16, wp_addr);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002380
Kate Stoneb9c1b512016-09-06 20:57:50 +00002381 WatchpointSP wp_sp =
2382 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2383 uint32_t wp_index = LLDB_INVALID_INDEX32;
Eugene Zelenko0722f082015-10-24 01:28:05 +00002384
Kate Stoneb9c1b512016-09-06 20:57:50 +00002385 if (wp_sp)
2386 wp_index = wp_sp->GetHardwareIndex();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002387
Kate Stoneb9c1b512016-09-06 20:57:50 +00002388 reason = "watchpoint";
2389 StreamString ostr;
2390 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002391 description = ostr.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002392 } else if (key.compare("library") == 0) {
Antonio Afonsod6682602019-07-25 14:28:21 +00002393 auto error = LoadModules();
2394 if (error) {
2395 Log *log(
2396 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2397 LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2398 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002399 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2400 uint32_t reg = UINT32_MAX;
2401 if (!key.getAsInteger(16, reg))
2402 expedited_register_map[reg] = std::move(value);
2403 }
2404 }
2405
2406 if (tid == LLDB_INVALID_THREAD_ID) {
2407 // A thread id may be invalid if the response is old style 'S' packet
2408 // which does not provide the
Adrian Prantl05097242018-04-30 16:49:04 +00002409 // thread information. So update the thread list and choose the first
2410 // one.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002411 UpdateThreadIDList();
2412
2413 if (!m_thread_ids.empty()) {
2414 tid = m_thread_ids.front();
2415 }
2416 }
2417
2418 ThreadSP thread_sp = SetThreadStopInfo(
2419 tid, expedited_register_map, signo, thread_name, reason, description,
2420 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2421 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2422 queue_kind, queue_serial_number);
2423
2424 return eStateStopped;
2425 } break;
2426
2427 case 'W':
2428 case 'X':
2429 // process exited
2430 return eStateExited;
2431
2432 default:
2433 break;
2434 }
2435 return eStateInvalid;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002436}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002437
Kate Stoneb9c1b512016-09-06 20:57:50 +00002438void ProcessGDBRemote::RefreshStateAfterStop() {
2439 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002440
Kate Stoneb9c1b512016-09-06 20:57:50 +00002441 m_thread_ids.clear();
2442 m_thread_pcs.clear();
Adrian Prantl05097242018-04-30 16:49:04 +00002443 // Set the thread stop info. It might have a "threads" key whose value is a
2444 // list of all thread IDs in the current process, so m_thread_ids might get
2445 // set.
Greg Claytona5801ad2015-07-15 22:59:03 +00002446
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447 // Scope for the lock
2448 {
Jim Ingham8864b432019-06-28 17:57:19 +00002449 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2450 if (m_thread_ids.empty()) {
2451 // No, we need to fetch the thread list manually
2452 UpdateThreadIDList();
2453 }
2454 // We might set some stop info's so make sure the thread list is up to
2455 // date before we do that or we might overwrite what was computed here.
2456 UpdateThreadListIfNeeded();
2457
Kate Stoneb9c1b512016-09-06 20:57:50 +00002458 // Lock the thread stack while we access it
2459 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2460 // Get the number of stop packets on the stack
2461 int nItems = m_stop_packet_stack.size();
2462 // Iterate over them
2463 for (int i = 0; i < nItems; i++) {
2464 // Get the thread stop info
2465 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2466 // Process thread stop info
2467 SetThreadStopInfo(stop_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002468 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002469 // Clear the thread stop stack
2470 m_stop_packet_stack.clear();
2471 }
Jim Ingham8864b432019-06-28 17:57:19 +00002472
Kate Stoneb9c1b512016-09-06 20:57:50 +00002473 // If we have queried for a default thread id
2474 if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2475 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2476 m_initial_tid = LLDB_INVALID_THREAD_ID;
2477 }
2478
Adrian Prantl05097242018-04-30 16:49:04 +00002479 // Let all threads recover from stopping and do any clean up based on the
2480 // previous thread state (if any).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002481 m_thread_list_real.RefreshStateAfterStop();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002482}
2483
Zachary Turner97206d52017-05-12 04:51:55 +00002484Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2485 Status error;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002486
Kate Stoneb9c1b512016-09-06 20:57:50 +00002487 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00002488 // We are being asked to halt during an attach. We need to just close our
2489 // file handle and debugserver will go away, and we can be done...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002490 m_gdb_comm.Disconnect();
2491 } else
2492 caused_stop = m_gdb_comm.Interrupt();
2493 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002494}
2495
Zachary Turner97206d52017-05-12 04:51:55 +00002496Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2497 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002499 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002500
Kate Stoneb9c1b512016-09-06 20:57:50 +00002501 error = m_gdb_comm.Detach(keep_stopped);
2502 if (log) {
2503 if (error.Success())
2504 log->PutCString(
2505 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
Greg Clayton513c26c2011-01-29 07:10:55 +00002506 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002507 LLDB_LOGF(log,
2508 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2509 error.AsCString() ? error.AsCString() : "<unknown error>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002510 }
2511
2512 if (!error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002513 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514
2515 // Sleep for one second to let the process get all detached...
2516 StopAsyncThread();
2517
2518 SetPrivateState(eStateDetached);
2519 ResumePrivateStateThread();
2520
2521 // KillDebugserverProcess ();
2522 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002523}
2524
Zachary Turner97206d52017-05-12 04:51:55 +00002525Status ProcessGDBRemote::DoDestroy() {
2526 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002527 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002528 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
Ed Maste81b4c5f2016-01-04 01:43:47 +00002529
Kate Stoneb9c1b512016-09-06 20:57:50 +00002530 // There is a bug in older iOS debugservers where they don't shut down the
Adrian Prantl05097242018-04-30 16:49:04 +00002531 // process they are debugging properly. If the process is sitting at a
2532 // breakpoint or an exception, this can cause problems with restarting. So
2533 // we check to see if any of our threads are stopped at a breakpoint, and if
2534 // so we remove all the breakpoints, resume the process, and THEN destroy it
2535 // again.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002536 //
2537 // Note, we don't have a good way to test the version of debugserver, but I
Adrian Prantl05097242018-04-30 16:49:04 +00002538 // happen to know that the set of all the iOS debugservers which don't
2539 // support GetThreadSuffixSupported() and that of the debugservers with this
2540 // bug are equal. There really should be a better way to test this!
Kate Stoneb9c1b512016-09-06 20:57:50 +00002541 //
2542 // We also use m_destroy_tried_resuming to make sure we only do this once, if
Adrian Prantl05097242018-04-30 16:49:04 +00002543 // we resume and then halt and get called here to destroy again and we're
2544 // still at a breakpoint or exception, then we should just do the straight-
2545 // forward kill.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002546 //
2547 // And of course, if we weren't able to stop the process by the time we get
Adrian Prantl05097242018-04-30 16:49:04 +00002548 // here, it isn't necessary (or helpful) to do any of this.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002549
Kate Stoneb9c1b512016-09-06 20:57:50 +00002550 if (!m_gdb_comm.GetThreadSuffixSupported() &&
2551 m_public_state.GetValue() != eStateRunning) {
2552 PlatformSP platform_sp = GetTarget().GetPlatform();
Jim Inghamacff8952013-05-02 00:27:30 +00002553
Kate Stoneb9c1b512016-09-06 20:57:50 +00002554 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2555 if (platform_sp && platform_sp->GetName() &&
2556 platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2557 if (m_destroy_tried_resuming) {
Greg Clayton8cda7f02013-05-21 21:55:59 +00002558 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002559 log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2560 "destroy once already, not doing it again.");
2561 } else {
2562 // At present, the plans are discarded and the breakpoints disabled
Adrian Prantl05097242018-04-30 16:49:04 +00002563 // Process::Destroy, but we really need it to happen here and it
2564 // doesn't matter if we do it twice.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002565 m_thread_list.DiscardThreadPlans();
2566 DisableAllBreakpointSites();
Greg Clayton8cda7f02013-05-21 21:55:59 +00002567
Kate Stoneb9c1b512016-09-06 20:57:50 +00002568 bool stop_looks_like_crash = false;
2569 ThreadList &threads = GetThreadList();
2570
2571 {
2572 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2573
2574 size_t num_threads = threads.GetSize();
2575 for (size_t i = 0; i < num_threads; i++) {
2576 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2577 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2578 StopReason reason = eStopReasonInvalid;
2579 if (stop_info_sp)
2580 reason = stop_info_sp->GetStopReason();
2581 if (reason == eStopReasonBreakpoint ||
2582 reason == eStopReasonException) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002583 LLDB_LOGF(log,
2584 "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2585 " stopped with reason: %s.",
2586 thread_sp->GetProtocolID(),
2587 stop_info_sp->GetDescription());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002588 stop_looks_like_crash = true;
2589 break;
2590 }
2591 }
2592 }
2593
2594 if (stop_looks_like_crash) {
2595 if (log)
2596 log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2597 "breakpoint, continue and then kill.");
2598 m_destroy_tried_resuming = true;
2599
2600 // If we are going to run again before killing, it would be good to
Adrian Prantl05097242018-04-30 16:49:04 +00002601 // suspend all the threads before resuming so they won't get into
2602 // more trouble. Sadly, for the threads stopped with the breakpoint
2603 // or exception, the exception doesn't get cleared if it is
2604 // suspended, so we do have to run the risk of letting those threads
2605 // proceed a bit.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002606
2607 {
2608 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2609
2610 size_t num_threads = threads.GetSize();
2611 for (size_t i = 0; i < num_threads; i++) {
2612 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2613 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2614 StopReason reason = eStopReasonInvalid;
2615 if (stop_info_sp)
2616 reason = stop_info_sp->GetStopReason();
2617 if (reason != eStopReasonBreakpoint &&
2618 reason != eStopReasonException) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002619 LLDB_LOGF(log,
2620 "ProcessGDBRemote::DoDestroy() - Suspending "
2621 "thread: 0x%4.4" PRIx64 " before running.",
2622 thread_sp->GetProtocolID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002623 thread_sp->SetResumeState(eStateSuspended);
2624 }
2625 }
2626 }
2627 Resume();
2628 return Destroy(false);
2629 }
2630 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002631 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002632 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002633
Kate Stoneb9c1b512016-09-06 20:57:50 +00002634 // Interrupt if our inferior is running...
2635 int exit_status = SIGABRT;
2636 std::string exit_string;
Greg Clayton2e309072015-07-17 23:42:28 +00002637
Kate Stoneb9c1b512016-09-06 20:57:50 +00002638 if (m_gdb_comm.IsConnected()) {
2639 if (m_public_state.GetValue() != eStateAttaching) {
2640 StringExtractorGDBRemote response;
2641 bool send_async = true;
Pavel Labath3aa04912016-10-31 17:19:42 +00002642 GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2643 std::chrono::seconds(3));
Greg Clayton2e309072015-07-17 23:42:28 +00002644
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002645 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002646 GDBRemoteCommunication::PacketResult::Success) {
2647 char packet_cmd = response.GetChar(0);
2648
2649 if (packet_cmd == 'W' || packet_cmd == 'X') {
2650#if defined(__APPLE__)
2651 // For Native processes on Mac OS X, we launch through the Host
Adrian Prantl05097242018-04-30 16:49:04 +00002652 // Platform, then hand the process off to debugserver, which becomes
2653 // the parent process through "PT_ATTACH". Then when we go to kill
2654 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2655 // we call waitpid which returns with no error and the correct
2656 // status. But amusingly enough that doesn't seem to actually reap
Kate Stoneb9c1b512016-09-06 20:57:50 +00002657 // the process, but instead it is left around as a Zombie. Probably
Adrian Prantl05097242018-04-30 16:49:04 +00002658 // the kernel is in the process of switching ownership back to lldb
2659 // which was the original parent, and gets confused in the handoff.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002660 // Anyway, so call waitpid here to finally reap it.
2661 PlatformSP platform_sp(GetTarget().GetPlatform());
2662 if (platform_sp && platform_sp->IsHost()) {
2663 int status;
2664 ::pid_t reap_pid;
2665 reap_pid = waitpid(GetID(), &status, WNOHANG);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002666 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002667 }
2668#endif
2669 SetLastStopPacket(response);
2670 ClearThreadIDList();
2671 exit_status = response.GetHexU8();
2672 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002673 LLDB_LOGF(log,
2674 "ProcessGDBRemote::DoDestroy - got unexpected response "
2675 "to k packet: %s",
2676 response.GetStringRef().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002677 exit_string.assign("got unexpected response to k packet: ");
2678 exit_string.append(response.GetStringRef());
2679 }
2680 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002681 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - failed to send k packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002682 exit_string.assign("failed to send the k packet");
2683 }
2684 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002685 LLDB_LOGF(log,
2686 "ProcessGDBRemote::DoDestroy - killed or interrupted while "
2687 "attaching");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002688 exit_string.assign("killed or interrupted while attaching.");
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002689 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002690 } else {
2691 // If we missed setting the exit status on the way out, do it here.
2692 // NB set exit status can be called multiple times, the first one sets the
2693 // status.
2694 exit_string.assign("destroying when not connected to debugserver");
2695 }
2696
2697 SetExitStatus(exit_status, exit_string.c_str());
2698
2699 StopAsyncThread();
2700 KillDebugserverProcess();
2701 return error;
Greg Clayton8cda7f02013-05-21 21:55:59 +00002702}
2703
Kate Stoneb9c1b512016-09-06 20:57:50 +00002704void ProcessGDBRemote::SetLastStopPacket(
2705 const StringExtractorGDBRemote &response) {
2706 const bool did_exec =
2707 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2708 if (did_exec) {
2709 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002710 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002711
2712 m_thread_list_real.Clear();
2713 m_thread_list.Clear();
2714 BuildDynamicRegisterInfo(true);
2715 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2716 }
2717
2718 // Scope the lock
2719 {
2720 // Lock the thread stack while we access it
2721 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2722
2723 // We are are not using non-stop mode, there can only be one last stop
2724 // reply packet, so clear the list.
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002725 if (!GetTarget().GetNonStopModeEnabled())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002726 m_stop_packet_stack.clear();
2727
Adrian Prantl05097242018-04-30 16:49:04 +00002728 // Add this stop packet to the stop packet stack This stack will get popped
2729 // and examined when we switch to the Stopped state
Kate Stoneb9c1b512016-09-06 20:57:50 +00002730 m_stop_packet_stack.push_back(response);
2731 }
2732}
2733
2734void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2735 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
Chaoren Linc963a222015-09-01 16:58:45 +00002736}
2737
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738// Process Queries
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739
Kate Stoneb9c1b512016-09-06 20:57:50 +00002740bool ProcessGDBRemote::IsAlive() {
2741 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002742}
2743
Kate Stoneb9c1b512016-09-06 20:57:50 +00002744addr_t ProcessGDBRemote::GetImageInfoAddress() {
2745 // request the link map address via the $qShlibInfoAddr packet
2746 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
Aidan Doddsc0c83852015-05-08 09:36:31 +00002747
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748 // the loaded module list can also provides a link map address
2749 if (addr == LLDB_INVALID_ADDRESS) {
Antonio Afonsod6682602019-07-25 14:28:21 +00002750 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2751 if (!list) {
2752 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2753 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}");
2754 } else {
2755 addr = list->m_link_map;
2756 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002757 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00002758
Kate Stoneb9c1b512016-09-06 20:57:50 +00002759 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002760}
2761
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762void ProcessGDBRemote::WillPublicStop() {
Adrian Prantl05097242018-04-30 16:49:04 +00002763 // See if the GDB remote client supports the JSON threads info. If so, we
2764 // gather stop info for all threads, expedited registers, expedited memory,
2765 // runtime queue information (iOS and MacOSX only), and more. Expediting
2766 // memory will help stack backtracing be much faster. Expediting registers
2767 // will make sure we don't have to read the thread registers for GPRs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002768 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
Greg Clayton2e309072015-07-17 23:42:28 +00002769
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770 if (m_jthreadsinfo_sp) {
2771 // Now set the stop info for each thread and also expedite any registers
2772 // and memory that was in the jThreadsInfo response.
2773 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2774 if (thread_infos) {
2775 const size_t n = thread_infos->GetSize();
2776 for (size_t i = 0; i < n; ++i) {
2777 StructuredData::Dictionary *thread_dict =
2778 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2779 if (thread_dict)
2780 SetThreadStopInfo(thread_dict);
2781 }
Greg Clayton2e309072015-07-17 23:42:28 +00002782 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 }
Greg Clayton2e309072015-07-17 23:42:28 +00002784}
2785
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002786// Process Memory
Kate Stoneb9c1b512016-09-06 20:57:50 +00002787size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002788 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002789 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002790 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2791 // M and m packets take 2 bytes for 1 byte of memory
2792 size_t max_memory_size =
2793 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2794 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 // Keep memory read sizes down to a sane limit. This function will be
2796 // called multiple times in order to complete the task by
2797 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002798 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002800
Kate Stoneb9c1b512016-09-06 20:57:50 +00002801 char packet[64];
2802 int packet_len;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002803 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2804 binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2805 (uint64_t)size);
2806 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002807 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002808 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002809 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002810 GDBRemoteCommunication::PacketResult::Success) {
2811 if (response.IsNormalResponse()) {
2812 error.Clear();
2813 if (binary_memory_read) {
2814 // The lower level GDBRemoteCommunication packet receive layer has
Adrian Prantl05097242018-04-30 16:49:04 +00002815 // already de-quoted any 0x7d character escaping that was present in
2816 // the packet
Jason Molenda6076bf42014-05-06 04:34:52 +00002817
Kate Stoneb9c1b512016-09-06 20:57:50 +00002818 size_t data_received_size = response.GetBytesLeft();
2819 if (data_received_size > size) {
2820 // Don't write past the end of BUF if the remote debug server gave us
Adrian Prantl05097242018-04-30 16:49:04 +00002821 // too much data for some reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 data_received_size = size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002823 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002824 memcpy(buf, response.GetStringRef().data(), data_received_size);
2825 return data_received_size;
2826 } else {
2827 return response.GetHexBytes(
2828 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2829 }
2830 } else if (response.IsErrorResponse())
2831 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2832 else if (response.IsUnsupportedResponse())
2833 error.SetErrorStringWithFormat(
2834 "GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002835 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002836 error.SetErrorStringWithFormat(
2837 "unexpected response to GDB server memory read packet '%s': '%s'",
2838 packet, response.GetStringRef().c_str());
2839 } else {
2840 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2841 }
2842 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002843}
2844
Pavel Labath16064d32018-03-20 11:56:24 +00002845Status ProcessGDBRemote::WriteObjectFile(
2846 std::vector<ObjectFile::LoadableData> entries) {
2847 Status error;
2848 // Sort the entries by address because some writes, like those to flash
2849 // memory, must happen in order of increasing address.
2850 std::stable_sort(
2851 std::begin(entries), std::end(entries),
2852 [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2853 return a.Dest < b.Dest;
2854 });
2855 m_allow_flash_writes = true;
2856 error = Process::WriteObjectFile(entries);
2857 if (error.Success())
2858 error = FlashDone();
2859 else
Adrian Prantl05097242018-04-30 16:49:04 +00002860 // Even though some of the writing failed, try to send a flash done if some
2861 // of the writing succeeded so the flash state is reset to normal, but
2862 // don't stomp on the error status that was set in the write failure since
2863 // that's the one we want to report back.
Pavel Labath16064d32018-03-20 11:56:24 +00002864 FlashDone();
2865 m_allow_flash_writes = false;
2866 return error;
2867}
2868
2869bool ProcessGDBRemote::HasErased(FlashRange range) {
2870 auto size = m_erased_flash_ranges.GetSize();
2871 for (size_t i = 0; i < size; ++i)
2872 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2873 return true;
2874 return false;
2875}
2876
2877Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2878 Status status;
2879
2880 MemoryRegionInfo region;
2881 status = GetMemoryRegionInfo(addr, region);
2882 if (!status.Success())
2883 return status;
2884
2885 // The gdb spec doesn't say if erasures are allowed across multiple regions,
2886 // but we'll disallow it to be safe and to keep the logic simple by worring
2887 // about only one region's block size. DoMemoryWrite is this function's
2888 // primary user, and it can easily keep writes within a single memory region
2889 if (addr + size > region.GetRange().GetRangeEnd()) {
2890 status.SetErrorString("Unable to erase flash in multiple regions");
2891 return status;
2892 }
2893
2894 uint64_t blocksize = region.GetBlocksize();
2895 if (blocksize == 0) {
2896 status.SetErrorString("Unable to erase flash because blocksize is 0");
2897 return status;
2898 }
2899
2900 // Erasures can only be done on block boundary adresses, so round down addr
2901 // and round up size
2902 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2903 size += (addr - block_start_addr);
2904 if ((size % blocksize) != 0)
2905 size += (blocksize - size % blocksize);
2906
2907 FlashRange range(block_start_addr, size);
2908
2909 if (HasErased(range))
2910 return status;
2911
2912 // We haven't erased the entire range, but we may have erased part of it.
Adrian Prantl05097242018-04-30 16:49:04 +00002913 // (e.g., block A is already erased and range starts in A and ends in B). So,
2914 // adjust range if necessary to exclude already erased blocks.
Pavel Labath16064d32018-03-20 11:56:24 +00002915 if (!m_erased_flash_ranges.IsEmpty()) {
2916 // Assuming that writes and erasures are done in increasing addr order,
Adrian Prantl05097242018-04-30 16:49:04 +00002917 // because that is a requirement of the vFlashWrite command. Therefore, we
2918 // only need to look at the last range in the list for overlap.
Pavel Labath16064d32018-03-20 11:56:24 +00002919 const auto &last_range = *m_erased_flash_ranges.Back();
2920 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2921 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
Adrian Prantl05097242018-04-30 16:49:04 +00002922 // overlap will be less than range.GetByteSize() or else HasErased()
2923 // would have been true
Pavel Labath16064d32018-03-20 11:56:24 +00002924 range.SetByteSize(range.GetByteSize() - overlap);
2925 range.SetRangeBase(range.GetRangeBase() + overlap);
2926 }
2927 }
2928
2929 StreamString packet;
2930 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2931 (uint64_t)range.GetByteSize());
2932
2933 StringExtractorGDBRemote response;
2934 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2935 true) ==
2936 GDBRemoteCommunication::PacketResult::Success) {
2937 if (response.IsOKResponse()) {
2938 m_erased_flash_ranges.Insert(range, true);
2939 } else {
2940 if (response.IsErrorResponse())
2941 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2942 addr);
2943 else if (response.IsUnsupportedResponse())
2944 status.SetErrorStringWithFormat("GDB server does not support flashing");
2945 else
2946 status.SetErrorStringWithFormat(
2947 "unexpected response to GDB server flash erase packet '%s': '%s'",
2948 packet.GetData(), response.GetStringRef().c_str());
2949 }
2950 } else {
2951 status.SetErrorStringWithFormat("failed to send packet: '%s'",
2952 packet.GetData());
2953 }
2954 return status;
2955}
2956
2957Status ProcessGDBRemote::FlashDone() {
2958 Status status;
2959 // If we haven't erased any blocks, then we must not have written anything
2960 // either, so there is no need to actually send a vFlashDone command
2961 if (m_erased_flash_ranges.IsEmpty())
2962 return status;
2963 StringExtractorGDBRemote response;
2964 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, true) ==
2965 GDBRemoteCommunication::PacketResult::Success) {
2966 if (response.IsOKResponse()) {
2967 m_erased_flash_ranges.Clear();
2968 } else {
2969 if (response.IsErrorResponse())
2970 status.SetErrorStringWithFormat("flash done failed");
2971 else if (response.IsUnsupportedResponse())
2972 status.SetErrorStringWithFormat("GDB server does not support flashing");
2973 else
2974 status.SetErrorStringWithFormat(
2975 "unexpected response to GDB server flash done packet: '%s'",
2976 response.GetStringRef().c_str());
2977 }
2978 } else {
2979 status.SetErrorStringWithFormat("failed to send flash done packet");
2980 }
2981 return status;
2982}
2983
Kate Stoneb9c1b512016-09-06 20:57:50 +00002984size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
Zachary Turner97206d52017-05-12 04:51:55 +00002985 size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002986 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002987 // M and m packets take 2 bytes for 1 byte of memory
2988 size_t max_memory_size = m_max_memory_size / 2;
2989 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002990 // Keep memory read sizes down to a sane limit. This function will be
2991 // called multiple times in order to complete the task by
2992 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002993 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002994 }
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002995
Pavel Labath16064d32018-03-20 11:56:24 +00002996 StreamGDBRemote packet;
2997
2998 MemoryRegionInfo region;
2999 Status region_status = GetMemoryRegionInfo(addr, region);
3000
3001 bool is_flash =
3002 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
3003
3004 if (is_flash) {
3005 if (!m_allow_flash_writes) {
3006 error.SetErrorString("Writing to flash memory is not allowed");
3007 return 0;
3008 }
3009 // Keep the write within a flash memory region
3010 if (addr + size > region.GetRange().GetRangeEnd())
3011 size = region.GetRange().GetRangeEnd() - addr;
3012 // Flash memory must be erased before it can be written
3013 error = FlashErase(addr, size);
3014 if (!error.Success())
3015 return 0;
3016 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
3017 packet.PutEscapedBytes(buf, size);
3018 } else {
3019 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
3020 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
3021 endian::InlHostByteOrder());
3022 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003023 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003024 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3025 true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003026 GDBRemoteCommunication::PacketResult::Success) {
3027 if (response.IsOKResponse()) {
3028 error.Clear();
3029 return size;
3030 } else if (response.IsErrorResponse())
3031 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
3032 addr);
3033 else if (response.IsUnsupportedResponse())
3034 error.SetErrorStringWithFormat(
3035 "GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 error.SetErrorStringWithFormat(
3038 "unexpected response to GDB server memory write packet '%s': '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00003039 packet.GetData(), response.GetStringRef().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003040 } else {
3041 error.SetErrorStringWithFormat("failed to send packet: '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00003042 packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003043 }
3044 return 0;
3045}
3046
3047lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
3048 uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00003049 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003050 Log *log(
3051 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
3052 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3053
3054 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
3055 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
3056 if (allocated_addr != LLDB_INVALID_ADDRESS ||
3057 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3058 return allocated_addr;
3059 }
3060
3061 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
3062 // Call mmap() to create memory in the inferior..
3063 unsigned prot = 0;
3064 if (permissions & lldb::ePermissionsReadable)
3065 prot |= eMmapProtRead;
3066 if (permissions & lldb::ePermissionsWritable)
3067 prot |= eMmapProtWrite;
3068 if (permissions & lldb::ePermissionsExecutable)
3069 prot |= eMmapProtExec;
3070
3071 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3072 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3073 m_addr_to_mmap_size[allocated_addr] = size;
3074 else {
3075 allocated_addr = LLDB_INVALID_ADDRESS;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003076 LLDB_LOGF(log,
3077 "ProcessGDBRemote::%s no direct stub support for memory "
3078 "allocation, and InferiorCallMmap also failed - is stub "
3079 "missing register context save/restore capability?",
3080 __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003081 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003082 }
3083
3084 if (allocated_addr == LLDB_INVALID_ADDRESS)
3085 error.SetErrorStringWithFormat(
3086 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
3087 (uint64_t)size, GetPermissionsAsCString(permissions));
3088 else
3089 error.Clear();
3090 return allocated_addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091}
3092
Zachary Turner97206d52017-05-12 04:51:55 +00003093Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
3094 MemoryRegionInfo &region_info) {
Ed Maste81b4c5f2016-01-04 01:43:47 +00003095
Zachary Turner97206d52017-05-12 04:51:55 +00003096 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003097 return error;
3098}
3099
Zachary Turner97206d52017-05-12 04:51:55 +00003100Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003101
Zachary Turner97206d52017-05-12 04:51:55 +00003102 Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003103 return error;
3104}
3105
Zachary Turner97206d52017-05-12 04:51:55 +00003106Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
3107 Status error(m_gdb_comm.GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003108 num, after, GetTarget().GetArchitecture()));
3109 return error;
3110}
3111
Zachary Turner97206d52017-05-12 04:51:55 +00003112Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
3113 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003114 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3115
3116 switch (supported) {
3117 case eLazyBoolCalculate:
Adrian Prantl05097242018-04-30 16:49:04 +00003118 // We should never be deallocating memory without allocating memory first
3119 // so we should never get eLazyBoolCalculate
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120 error.SetErrorString(
3121 "tried to deallocate memory without ever allocating memory");
3122 break;
3123
3124 case eLazyBoolYes:
3125 if (!m_gdb_comm.DeallocateMemory(addr))
3126 error.SetErrorStringWithFormat(
3127 "unable to deallocate memory at 0x%" PRIx64, addr);
3128 break;
3129
3130 case eLazyBoolNo:
3131 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2a48f522011-05-14 01:50:35 +00003132 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003133 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3134 if (pos != m_addr_to_mmap_size.end() &&
3135 InferiorCallMunmap(this, addr, pos->second))
3136 m_addr_to_mmap_size.erase(pos);
3137 else
3138 error.SetErrorStringWithFormat(
3139 "unable to deallocate memory at 0x%" PRIx64, addr);
Greg Claytoncec91ef2016-02-26 01:20:20 +00003140 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003141 break;
3142 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003143
Kate Stoneb9c1b512016-09-06 20:57:50 +00003144 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003145}
3146
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003147// Process STDIO
Kate Stoneb9c1b512016-09-06 20:57:50 +00003148size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00003149 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003150 if (m_stdio_communication.IsConnected()) {
3151 ConnectionStatus status;
Konrad Kleine248a1302019-05-23 11:14:47 +00003152 m_stdio_communication.Write(src, src_len, status, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003153 } else if (m_stdin_forward) {
3154 m_gdb_comm.SendStdinNotification(src, src_len);
3155 }
3156 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003157}
3158
Zachary Turner97206d52017-05-12 04:51:55 +00003159Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
3160 Status error;
Konrad Kleine248a1302019-05-23 11:14:47 +00003161 assert(bp_site != nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003162
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163 // Get logging info
3164 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3165 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003166
Kate Stoneb9c1b512016-09-06 20:57:50 +00003167 // Get the breakpoint address
3168 const addr_t addr = bp_site->GetLoadAddress();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003169
Kate Stoneb9c1b512016-09-06 20:57:50 +00003170 // Log that a breakpoint was requested
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003171 LLDB_LOGF(log,
3172 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3173 ") address = 0x%" PRIx64,
3174 site_id, (uint64_t)addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003175
3176 // Breakpoint already exists and is enabled
3177 if (bp_site->IsEnabled()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003178 LLDB_LOGF(log,
3179 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3180 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3181 site_id, (uint64_t)addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003182 return error;
3183 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003184
Kate Stoneb9c1b512016-09-06 20:57:50 +00003185 // Get the software breakpoint trap opcode size
3186 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3187
3188 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
Adrian Prantl05097242018-04-30 16:49:04 +00003189 // breakpoint type is supported by the remote stub. These are set to true by
3190 // default, and later set to false only after we receive an unimplemented
3191 // response when sending a breakpoint packet. This means initially that
3192 // unless we were specifically instructed to use a hardware breakpoint, LLDB
3193 // will attempt to set a software breakpoint. HardwareRequired() also queries
3194 // a boolean variable which indicates if the user specifically asked for
3195 // hardware breakpoints. If true then we will skip over software
3196 // breakpoints.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003197 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3198 (!bp_site->HardwareRequired())) {
3199 // Try to send off a software breakpoint packet ($Z0)
3200 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3201 eBreakpointSoftware, true, addr, bp_op_size);
3202 if (error_no == 0) {
3203 // The breakpoint was placed successfully
3204 bp_site->SetEnabled(true);
3205 bp_site->SetType(BreakpointSite::eExternal);
3206 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003207 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003208
Adrian Prantl05097242018-04-30 16:49:04 +00003209 // SendGDBStoppointTypePacket() will return an error if it was unable to
3210 // set this breakpoint. We need to differentiate between a error specific
3211 // to placing this breakpoint or if we have learned that this breakpoint
3212 // type is unsupported. To do this, we must test the support boolean for
3213 // this breakpoint type to see if it now indicates that this breakpoint
3214 // type is unsupported. If they are still supported then we should return
Kate Stoneb9c1b512016-09-06 20:57:50 +00003215 // with the error code. If they are now unsupported, then we would like to
Adrian Prantl05097242018-04-30 16:49:04 +00003216 // fall through and try another form of breakpoint.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003217 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3218 if (error_no != UINT8_MAX)
3219 error.SetErrorStringWithFormat(
3220 "error: %d sending the breakpoint request", errno);
3221 else
3222 error.SetErrorString("error sending the breakpoint request");
3223 return error;
3224 }
3225
3226 // We reach here when software breakpoints have been found to be
Adrian Prantl05097242018-04-30 16:49:04 +00003227 // unsupported. For future calls to set a breakpoint, we will not attempt
3228 // to set a breakpoint with a type that is known not to be supported.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003229 LLDB_LOGF(log, "Software breakpoints are unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003230
3231 // So we will fall through and try a hardware breakpoint
3232 }
3233
Adrian Prantl05097242018-04-30 16:49:04 +00003234 // The process of setting a hardware breakpoint is much the same as above.
3235 // We check the supported boolean for this breakpoint type, and if it is
3236 // thought to be supported then we will try to set this breakpoint with a
3237 // hardware breakpoint.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003238 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3239 // Try to send off a hardware breakpoint packet ($Z1)
3240 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3241 eBreakpointHardware, true, addr, bp_op_size);
3242 if (error_no == 0) {
3243 // The breakpoint was placed successfully
3244 bp_site->SetEnabled(true);
3245 bp_site->SetType(BreakpointSite::eHardware);
3246 return error;
3247 }
3248
3249 // Check if the error was something other then an unsupported breakpoint
3250 // type
3251 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3252 // Unable to set this hardware breakpoint
3253 if (error_no != UINT8_MAX)
3254 error.SetErrorStringWithFormat(
3255 "error: %d sending the hardware breakpoint request "
3256 "(hardware breakpoint resources might be exhausted or unavailable)",
3257 error_no);
3258 else
3259 error.SetErrorString("error sending the hardware breakpoint request "
3260 "(hardware breakpoint resources "
3261 "might be exhausted or unavailable)");
3262 return error;
3263 }
3264
3265 // We will reach here when the stub gives an unsupported response to a
3266 // hardware breakpoint
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003267 LLDB_LOGF(log, "Hardware breakpoints are unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003268
3269 // Finally we will falling through to a #trap style breakpoint
3270 }
3271
3272 // Don't fall through when hardware breakpoints were specifically requested
3273 if (bp_site->HardwareRequired()) {
3274 error.SetErrorString("hardware breakpoints are not supported");
3275 return error;
3276 }
3277
Adrian Prantl05097242018-04-30 16:49:04 +00003278 // As a last resort we want to place a manual breakpoint. An instruction is
3279 // placed into the process memory using memory write packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003280 return EnableSoftwareBreakpoint(bp_site);
3281}
3282
Zachary Turner97206d52017-05-12 04:51:55 +00003283Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3284 Status error;
Konrad Kleine248a1302019-05-23 11:14:47 +00003285 assert(bp_site != nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003286 addr_t addr = bp_site->GetLoadAddress();
3287 user_id_t site_id = bp_site->GetID();
3288 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003289 LLDB_LOGF(log,
3290 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3291 ") addr = 0x%8.8" PRIx64,
3292 site_id, (uint64_t)addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003293
3294 if (bp_site->IsEnabled()) {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003295 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3296
Kate Stoneb9c1b512016-09-06 20:57:50 +00003297 BreakpointSite::Type bp_type = bp_site->GetType();
3298 switch (bp_type) {
3299 case BreakpointSite::eSoftware:
3300 error = DisableSoftwareBreakpoint(bp_site);
3301 break;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003302
Kate Stoneb9c1b512016-09-06 20:57:50 +00003303 case BreakpointSite::eHardware:
3304 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3305 addr, bp_op_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003306 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003307 break;
3308
3309 case BreakpointSite::eExternal: {
3310 GDBStoppointType stoppoint_type;
3311 if (bp_site->IsHardware())
3312 stoppoint_type = eBreakpointHardware;
3313 else
3314 stoppoint_type = eBreakpointSoftware;
3315
3316 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr,
3317 bp_op_size))
3318 error.SetErrorToGenericError();
3319 } break;
3320 }
3321 if (error.Success())
3322 bp_site->SetEnabled(false);
3323 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003324 LLDB_LOGF(log,
3325 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3326 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3327 site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003328 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003329 }
3330
3331 if (error.Success())
3332 error.SetErrorToGenericError();
3333 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003334}
3335
Johnny Chen11309a32011-09-06 22:38:36 +00003336// Pre-requisite: wp != NULL.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003337static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3338 assert(wp);
3339 bool watch_read = wp->WatchpointRead();
3340 bool watch_write = wp->WatchpointWrite();
Johnny Chen11309a32011-09-06 22:38:36 +00003341
Kate Stoneb9c1b512016-09-06 20:57:50 +00003342 // watch_read and watch_write cannot both be false.
3343 assert(watch_read || watch_write);
3344 if (watch_read && watch_write)
3345 return eWatchpointReadWrite;
3346 else if (watch_read)
3347 return eWatchpointRead;
3348 else // Must be watch_write, then.
3349 return eWatchpointWrite;
Johnny Chen11309a32011-09-06 22:38:36 +00003350}
3351
Zachary Turner97206d52017-05-12 04:51:55 +00003352Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3353 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003354 if (wp) {
3355 user_id_t watchID = wp->GetID();
3356 addr_t addr = wp->GetLoadAddress();
3357 Log *log(
3358 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003359 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3360 watchID);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003361 if (wp->IsEnabled()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003362 LLDB_LOGF(log,
3363 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3364 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3365 watchID, (uint64_t)addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003366 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003367 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003368
3369 GDBStoppointType type = GetGDBStoppointType(wp);
3370 // Pass down an appropriate z/Z packet...
3371 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3372 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3373 wp->GetByteSize()) == 0) {
3374 wp->SetEnabled(true, notify);
3375 return error;
3376 } else
3377 error.SetErrorString("sending gdb watchpoint packet failed");
3378 } else
3379 error.SetErrorString("watchpoints not supported");
3380 } else {
3381 error.SetErrorString("Watchpoint argument was NULL.");
3382 }
3383 if (error.Success())
3384 error.SetErrorToGenericError();
3385 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003386}
Kate Stoneb9c1b512016-09-06 20:57:50 +00003387
Zachary Turner97206d52017-05-12 04:51:55 +00003388Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3389 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003390 if (wp) {
3391 user_id_t watchID = wp->GetID();
3392
3393 Log *log(
3394 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3395
3396 addr_t addr = wp->GetLoadAddress();
3397
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003398 LLDB_LOGF(log,
3399 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3400 ") addr = 0x%8.8" PRIx64,
3401 watchID, (uint64_t)addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003402
3403 if (!wp->IsEnabled()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003404 LLDB_LOGF(log,
3405 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3406 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3407 watchID, (uint64_t)addr);
Adrian Prantl05097242018-04-30 16:49:04 +00003408 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3409 // attempt might come from the user-supplied actions, we'll route it in
3410 // order for the watchpoint object to intelligently process this action.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003411 wp->SetEnabled(false, notify);
3412 return error;
3413 }
3414
3415 if (wp->IsHardware()) {
3416 GDBStoppointType type = GetGDBStoppointType(wp);
3417 // Pass down an appropriate z/Z packet...
3418 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3419 wp->GetByteSize()) == 0) {
3420 wp->SetEnabled(false, notify);
3421 return error;
3422 } else
3423 error.SetErrorString("sending gdb watchpoint packet failed");
3424 }
3425 // TODO: clear software watchpoints if we implement them
3426 } else {
3427 error.SetErrorString("Watchpoint argument was NULL.");
3428 }
3429 if (error.Success())
3430 error.SetErrorToGenericError();
3431 return error;
3432}
3433
3434void ProcessGDBRemote::Clear() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003435 m_thread_list_real.Clear();
3436 m_thread_list.Clear();
3437}
3438
Zachary Turner97206d52017-05-12 04:51:55 +00003439Status ProcessGDBRemote::DoSignal(int signo) {
3440 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003441 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003442 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003443
3444 if (!m_gdb_comm.SendAsyncSignal(signo))
3445 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3446 return error;
3447}
3448
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00003449Status ProcessGDBRemote::ConnectToReplayServer(repro::Loader *loader) {
3450 if (!loader)
3451 return Status("No loader provided.");
3452
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00003453 // Construct replay history path.
Jonas Devlieghereef96e982019-06-12 22:17:38 +00003454 FileSpec history_file = loader->GetFile<ProcessGDBRemoteProvider::Info>();
Jonas Devliegheree912cc52019-01-18 01:04:59 +00003455 if (!history_file)
3456 return Status("No provider for gdb-remote.");
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00003457
3458 // Enable replay mode.
3459 m_replay_mode = true;
3460
3461 // Load replay history.
3462 if (auto error = m_gdb_replay_server.LoadReplayHistory(history_file))
3463 return Status("Unable to load replay history");
3464
3465 // Make a local connection.
3466 if (auto error = GDBRemoteCommunication::ConnectLocally(m_gdb_comm,
3467 m_gdb_replay_server))
3468 return Status("Unable to connect to replay server");
3469
3470 // Start server thread.
3471 m_gdb_replay_server.StartAsyncThread();
3472
3473 // Start client thread.
3474 StartAsyncThread();
3475
3476 // Do the usual setup.
3477 return ConnectToDebugserver("");
3478}
3479
Zachary Turner97206d52017-05-12 04:51:55 +00003480Status
3481ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003482 // Make sure we aren't already connected?
3483 if (m_gdb_comm.IsConnected())
Zachary Turner97206d52017-05-12 04:51:55 +00003484 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003485
3486 PlatformSP platform_sp(GetTarget().GetPlatform());
3487 if (platform_sp && !platform_sp->IsHost())
Zachary Turner97206d52017-05-12 04:51:55 +00003488 return Status("Lost debug server connection");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003489
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00003490 if (repro::Loader *loader = repro::Reproducer::Instance().GetLoader())
3491 return ConnectToReplayServer(loader);
3492
Kate Stoneb9c1b512016-09-06 20:57:50 +00003493 auto error = LaunchAndConnectToDebugserver(process_info);
3494 if (error.Fail()) {
3495 const char *error_string = error.AsCString();
3496 if (error_string == nullptr)
3497 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3498 }
3499 return error;
3500}
Eugene Zemtsov30153412017-09-25 17:41:16 +00003501#if !defined(_WIN32)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003502#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3503#endif
3504
3505#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Kate Stoneb9c1b512016-09-06 20:57:50 +00003506static bool SetCloexecFlag(int fd) {
3507#if defined(FD_CLOEXEC)
3508 int flags = ::fcntl(fd, F_GETFD);
3509 if (flags == -1)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003510 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003511 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3512#else
3513 return false;
Greg Claytonc6c420f2016-08-12 16:46:18 +00003514#endif
3515}
3516#endif
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003517
Zachary Turner97206d52017-05-12 04:51:55 +00003518Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003519 const ProcessInfo &process_info) {
3520 using namespace std::placeholders; // For _1, _2, etc.
Pavel Labath998bdc52016-05-11 16:59:04 +00003521
Zachary Turner97206d52017-05-12 04:51:55 +00003522 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003523 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3524 // If we locate debugserver, keep that located version around
3525 static FileSpec g_debugserver_file_spec;
3526
3527 ProcessLaunchInfo debugserver_launch_info;
Adrian Prantl05097242018-04-30 16:49:04 +00003528 // Make debugserver run in its own session so signals generated by special
3529 // terminal key sequences (^C) don't affect debugserver.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003530 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3531
3532 const std::weak_ptr<ProcessGDBRemote> this_wp =
3533 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3534 debugserver_launch_info.SetMonitorProcessCallback(
3535 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3536 debugserver_launch_info.SetUserID(process_info.GetUserID());
3537
3538 int communication_fd = -1;
3539#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Eugene Zemtsov30153412017-09-25 17:41:16 +00003540 // Use a socketpair on non-Windows systems for security and performance
3541 // reasons.
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003542 int sockets[2]; /* the pair of socket descriptors */
3543 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3544 error.SetErrorToErrno();
3545 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003546 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003547
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003548 int our_socket = sockets[0];
3549 int gdb_socket = sockets[1];
3550 CleanUp cleanup_our(close, our_socket);
3551 CleanUp cleanup_gdb(close, gdb_socket);
3552
Kate Stoneb9c1b512016-09-06 20:57:50 +00003553 // Don't let any child processes inherit our communication socket
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003554 SetCloexecFlag(our_socket);
3555 communication_fd = gdb_socket;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003556#endif
3557
3558 error = m_gdb_comm.StartDebugserverProcess(
3559 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3560 nullptr, nullptr, communication_fd);
3561
3562 if (error.Success())
3563 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3564 else
3565 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3566
3567 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3568#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Adrian Prantl05097242018-04-30 16:49:04 +00003569 // Our process spawned correctly, we can now set our connection to use
3570 // our end of the socket pair
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003571 cleanup_our.disable();
3572 m_gdb_comm.SetConnection(new ConnectionFileDescriptor(our_socket, true));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003573#endif
3574 StartAsyncThread();
3575 }
3576
3577 if (error.Fail()) {
3578 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3579
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003580 LLDB_LOGF(log, "failed to start debugserver process: %s",
3581 error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003582 return error;
3583 }
3584
3585 if (m_gdb_comm.IsConnected()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003586 // Finish the connection process by doing the handshake without
3587 // connecting (send NULL URL)
Jonas Devlieghere03772dd2018-07-25 15:20:15 +00003588 error = ConnectToDebugserver("");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003589 } else {
3590 error.SetErrorString("connection failed");
3591 }
3592 }
3593 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003594}
3595
Kate Stoneb9c1b512016-09-06 20:57:50 +00003596bool ProcessGDBRemote::MonitorDebugserverProcess(
3597 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3598 bool exited, // True if the process did exit
3599 int signo, // Zero for no signal
3600 int exit_status // Exit value of process if signal is zero
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00003601) {
Adrian Prantl05097242018-04-30 16:49:04 +00003602 // "debugserver_pid" argument passed in is the process ID for debugserver
3603 // that we are tracking...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003604 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3605 const bool handled = true;
Greg Claytone4e45922011-11-16 05:37:56 +00003606
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003607 LLDB_LOGF(log,
3608 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3609 ", signo=%i (0x%x), exit_status=%i)",
3610 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00003611
Kate Stoneb9c1b512016-09-06 20:57:50 +00003612 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003613 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3614 static_cast<void *>(process_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003615 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
Pavel Labath194357c2016-05-12 11:10:01 +00003616 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003617
Adrian Prantl05097242018-04-30 16:49:04 +00003618 // Sleep for a half a second to make sure our inferior process has time to
3619 // set its exit status before we set it incorrectly when both the debugserver
3620 // and the inferior process shut down.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003621 usleep(500000);
Adrian Prantl05097242018-04-30 16:49:04 +00003622 // If our process hasn't yet exited, debugserver might have died. If the
3623 // process did exit, then we are reaping it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003624 const StateType state = process_sp->GetState();
3625
3626 if (state != eStateInvalid && state != eStateUnloaded &&
3627 state != eStateExited && state != eStateDetached) {
3628 char error_str[1024];
3629 if (signo) {
3630 const char *signal_cstr =
3631 process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3632 if (signal_cstr)
3633 ::snprintf(error_str, sizeof(error_str),
3634 DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3635 else
3636 ::snprintf(error_str, sizeof(error_str),
3637 DEBUGSERVER_BASENAME " died with signal %i", signo);
3638 } else {
3639 ::snprintf(error_str, sizeof(error_str),
3640 DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3641 exit_status);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003642 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003643
3644 process_sp->SetExitStatus(-1, error_str);
3645 }
Adrian Prantl05097242018-04-30 16:49:04 +00003646 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3647 // longer has a debugserver instance
Kate Stoneb9c1b512016-09-06 20:57:50 +00003648 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3649 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003650}
3651
Kate Stoneb9c1b512016-09-06 20:57:50 +00003652void ProcessGDBRemote::KillDebugserverProcess() {
3653 m_gdb_comm.Disconnect();
3654 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3655 Host::Kill(m_debugserver_pid, SIGINT);
3656 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3657 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003658}
3659
Kate Stoneb9c1b512016-09-06 20:57:50 +00003660void ProcessGDBRemote::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003661 static llvm::once_flag g_once_flag;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003662
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003663 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003664 PluginManager::RegisterPlugin(GetPluginNameStatic(),
3665 GetPluginDescriptionStatic(), CreateInstance,
3666 DebuggerInitialize);
3667 });
Greg Clayton7f982402013-07-15 22:54:20 +00003668}
3669
Kate Stoneb9c1b512016-09-06 20:57:50 +00003670void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3671 if (!PluginManager::GetSettingForProcessPlugin(
3672 debugger, PluginProperties::GetSettingName())) {
3673 const bool is_global_setting = true;
3674 PluginManager::CreateSettingForProcessPlugin(
3675 debugger, GetGlobalPluginProperties()->GetValueProperties(),
3676 ConstString("Properties for the gdb-remote process plug-in."),
3677 is_global_setting);
3678 }
3679}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003680
Kate Stoneb9c1b512016-09-06 20:57:50 +00003681bool ProcessGDBRemote::StartAsyncThread() {
3682 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3683
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003684 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003685
3686 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3687 if (!m_async_thread.IsJoinable()) {
3688 // Create a thread that watches our internal state and controls which
3689 // events make it to clients (into the DCProcess event queue).
3690
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003691 llvm::Expected<HostThread> async_thread = ThreadLauncher::LaunchThread(
3692 "<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this);
3693 if (!async_thread) {
3694 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3695 "failed to launch host thread: {}",
3696 llvm::toString(async_thread.takeError()));
3697 return false;
3698 }
3699 m_async_thread = *async_thread;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003700 } else
3701 LLDB_LOGF(log,
3702 "ProcessGDBRemote::%s () - Called when Async thread was "
3703 "already running.",
3704 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003705
3706 return m_async_thread.IsJoinable();
3707}
3708
3709void ProcessGDBRemote::StopAsyncThread() {
3710 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3711
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003712 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003713
3714 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3715 if (m_async_thread.IsJoinable()) {
3716 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3717
3718 // This will shut down the async thread.
3719 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3720
3721 // Stop the stdio thread
3722 m_async_thread.Join(nullptr);
3723 m_async_thread.Reset();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003724 } else
3725 LLDB_LOGF(
3726 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003727 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3728 __FUNCTION__);
3729}
3730
3731bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3732 // get the packet at a string
3733 const std::string &pkt = packet.GetStringRef();
3734 // skip %stop:
3735 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3736
3737 // pass as a thread stop info packet
3738 SetLastStopPacket(stop_info);
3739
3740 // check for more stop reasons
3741 HandleStopReplySequence();
3742
Adrian Prantl05097242018-04-30 16:49:04 +00003743 // if the process is stopped then we need to fake a resume so that we can
3744 // stop properly with the new break. This is possible due to
3745 // SetPrivateState() broadcasting the state change as a side effect.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003746 if (GetPrivateState() == lldb::StateType::eStateStopped) {
3747 SetPrivateState(lldb::StateType::eStateRunning);
3748 }
3749
3750 // since we have some stopped packets we can halt the process
3751 SetPrivateState(lldb::StateType::eStateStopped);
3752
3753 return true;
3754}
3755
3756thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3757 ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3758
3759 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003760 LLDB_LOGF(log,
3761 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3762 ") thread starting...",
3763 __FUNCTION__, arg, process->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003764
3765 EventSP event_sp;
3766 bool done = false;
3767 while (!done) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003768 LLDB_LOGF(log,
3769 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3770 ") listener.WaitForEvent (NULL, event_sp)...",
3771 __FUNCTION__, arg, process->GetID());
Pavel Labathd35031e12016-11-30 10:41:42 +00003772 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003773 const uint32_t event_type = event_sp->GetType();
3774 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003775 LLDB_LOGF(log,
3776 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3777 ") Got an event of type: %d...",
3778 __FUNCTION__, arg, process->GetID(), event_type);
Pavel Labath50556852015-09-03 09:36:22 +00003779
Kate Stoneb9c1b512016-09-06 20:57:50 +00003780 switch (event_type) {
3781 case eBroadcastBitAsyncContinue: {
3782 const EventDataBytes *continue_packet =
3783 EventDataBytes::GetEventDataFromEvent(event_sp.get());
Pavel Labath50556852015-09-03 09:36:22 +00003784
Kate Stoneb9c1b512016-09-06 20:57:50 +00003785 if (continue_packet) {
3786 const char *continue_cstr =
3787 (const char *)continue_packet->GetBytes();
3788 const size_t continue_cstr_len = continue_packet->GetByteSize();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003789 LLDB_LOGF(log,
3790 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3791 ") got eBroadcastBitAsyncContinue: %s",
3792 __FUNCTION__, arg, process->GetID(), continue_cstr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003793
Konrad Kleine248a1302019-05-23 11:14:47 +00003794 if (::strstr(continue_cstr, "vAttach") == nullptr)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003795 process->SetPrivateState(eStateRunning);
3796 StringExtractorGDBRemote response;
3797
3798 // If in Non-Stop-Mode
3799 if (process->GetTarget().GetNonStopModeEnabled()) {
3800 // send the vCont packet
3801 if (!process->GetGDBRemote().SendvContPacket(
3802 llvm::StringRef(continue_cstr, continue_cstr_len),
3803 response)) {
3804 // Something went wrong
3805 done = true;
3806 break;
3807 }
3808 }
3809 // If in All-Stop-Mode
3810 else {
3811 StateType stop_state =
3812 process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3813 *process, *process->GetUnixSignals(),
3814 llvm::StringRef(continue_cstr, continue_cstr_len),
3815 response);
3816
3817 // We need to immediately clear the thread ID list so we are sure
Adrian Prantl05097242018-04-30 16:49:04 +00003818 // to get a valid list of threads. The thread ID list might be
3819 // contained within the "response", or the stop reply packet that
Kate Stoneb9c1b512016-09-06 20:57:50 +00003820 // caused the stop. So clear it now before we give the stop reply
Adrian Prantl05097242018-04-30 16:49:04 +00003821 // packet to the process using the
3822 // process->SetLastStopPacket()...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003823 process->ClearThreadIDList();
3824
3825 switch (stop_state) {
3826 case eStateStopped:
3827 case eStateCrashed:
3828 case eStateSuspended:
3829 process->SetLastStopPacket(response);
3830 process->SetPrivateState(stop_state);
3831 break;
3832
3833 case eStateExited: {
3834 process->SetLastStopPacket(response);
3835 process->ClearThreadIDList();
3836 response.SetFilePos(1);
3837
3838 int exit_status = response.GetHexU8();
3839 std::string desc_string;
3840 if (response.GetBytesLeft() > 0 &&
3841 response.GetChar('-') == ';') {
3842 llvm::StringRef desc_str;
3843 llvm::StringRef desc_token;
3844 while (response.GetNameColonValue(desc_token, desc_str)) {
3845 if (desc_token != "description")
3846 continue;
3847 StringExtractor extractor(desc_str);
3848 extractor.GetHexByteString(desc_string);
3849 }
3850 }
3851 process->SetExitStatus(exit_status, desc_string.c_str());
3852 done = true;
3853 break;
3854 }
3855 case eStateInvalid: {
3856 // Check to see if we were trying to attach and if we got back
3857 // the "E87" error code from debugserver -- this indicates that
3858 // the process is not debuggable. Return a slightly more
Adrian Prantl05097242018-04-30 16:49:04 +00003859 // helpful error message about why the attach failed.
Konrad Kleine248a1302019-05-23 11:14:47 +00003860 if (::strstr(continue_cstr, "vAttach") != nullptr &&
Kate Stoneb9c1b512016-09-06 20:57:50 +00003861 response.GetError() == 0x87) {
3862 process->SetExitStatus(-1, "cannot attach to process due to "
3863 "System Integrity Protection");
Konrad Kleine248a1302019-05-23 11:14:47 +00003864 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
Pavel Labathacebc432018-04-18 11:56:21 +00003865 response.GetStatus().Fail()) {
3866 process->SetExitStatus(-1, response.GetStatus().AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003867 } else {
3868 process->SetExitStatus(-1, "lost connection");
3869 }
3870 break;
3871 }
3872
3873 default:
3874 process->SetPrivateState(stop_state);
3875 break;
3876 } // switch(stop_state)
3877 } // else // if in All-stop-mode
3878 } // if (continue_packet)
3879 } // case eBroadcastBitAysncContinue
3880 break;
3881
3882 case eBroadcastBitAsyncThreadShouldExit:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003883 LLDB_LOGF(log,
3884 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3885 ") got eBroadcastBitAsyncThreadShouldExit...",
3886 __FUNCTION__, arg, process->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003887 done = true;
3888 break;
3889
3890 default:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003891 LLDB_LOGF(log,
3892 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3893 ") got unknown event 0x%8.8x",
3894 __FUNCTION__, arg, process->GetID(), event_type);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003895 done = true;
3896 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003897 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003898 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3899 switch (event_type) {
3900 case Communication::eBroadcastBitReadThreadDidExit:
3901 process->SetExitStatus(-1, "lost connection");
3902 done = true;
3903 break;
3904
3905 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3906 lldb_private::Event *event = event_sp.get();
3907 const EventDataBytes *continue_packet =
3908 EventDataBytes::GetEventDataFromEvent(event);
3909 StringExtractorGDBRemote notify(
3910 (const char *)continue_packet->GetBytes());
3911 // Hand this over to the process to handle
3912 process->HandleNotifyPacket(notify);
3913 break;
3914 }
3915
3916 default:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003917 LLDB_LOGF(log,
3918 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3919 ") got unknown event 0x%8.8x",
3920 __FUNCTION__, arg, process->GetID(), event_type);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003921 done = true;
3922 break;
3923 }
3924 }
3925 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003926 LLDB_LOGF(log,
3927 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3928 ") listener.WaitForEvent (NULL, event_sp) => false",
3929 __FUNCTION__, arg, process->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003930 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003931 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003932 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003933
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003934 LLDB_LOGF(log,
3935 "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3936 ") thread exiting...",
3937 __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003938
Jonas Devliegherea83bf472019-05-23 19:32:46 +00003939 return {};
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003940}
3941
Kate Stoneb9c1b512016-09-06 20:57:50 +00003942// uint32_t
3943// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3944// &matches, std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00003945//{
Kate Stoneb9c1b512016-09-06 20:57:50 +00003946// // If we are planning to launch the debugserver remotely, then we need to
3947// fire up a debugserver
3948// // process and ask it for the list of processes. But if we are local, we
3949// can let the Host do it.
Greg Claytone996fd32011-03-08 22:40:15 +00003950// if (m_local_debugserver)
3951// {
3952// return Host::ListProcessesMatchingName (name, matches, pids);
3953// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003954// else
Greg Claytone996fd32011-03-08 22:40:15 +00003955// {
3956// // FIXME: Implement talking to the remote debugserver.
3957// return 0;
3958// }
3959//
3960//}
3961//
Kate Stoneb9c1b512016-09-06 20:57:50 +00003962bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3963 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3964 lldb::user_id_t break_loc_id) {
3965 // I don't think I have to do anything here, just make sure I notice the new
3966 // thread when it starts to
3967 // run so I can stop it if that's what I want to do.
3968 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003969 LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003970 return false;
Jim Ingham1c823b42011-01-22 01:33:44 +00003971}
3972
Zachary Turner97206d52017-05-12 04:51:55 +00003973Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003974 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3975 LLDB_LOG(log, "Check if need to update ignored signals");
3976
Adrian Prantl05097242018-04-30 16:49:04 +00003977 // QPassSignals package is not supported by the server, there is no way we
3978 // can ignore any signals on server side.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003979 if (!m_gdb_comm.GetQPassSignalsSupported())
Zachary Turner97206d52017-05-12 04:51:55 +00003980 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003981
3982 // No signals, nothing to send.
3983 if (m_unix_signals_sp == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00003984 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003985
3986 // Signals' version hasn't changed, no need to send anything.
3987 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3988 if (new_signals_version == m_last_signals_version) {
3989 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3990 m_last_signals_version);
Zachary Turner97206d52017-05-12 04:51:55 +00003991 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003992 }
3993
3994 auto signals_to_ignore =
3995 m_unix_signals_sp->GetFilteredSignals(false, false, false);
Zachary Turner97206d52017-05-12 04:51:55 +00003996 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003997
3998 LLDB_LOG(log,
3999 "Signals' version changed. old version={0}, new version={1}, "
4000 "signals ignored={2}, update result={3}",
4001 m_last_signals_version, new_signals_version,
4002 signals_to_ignore.size(), error);
4003
4004 if (error.Success())
4005 m_last_signals_version = new_signals_version;
4006
4007 return error;
4008}
4009
Kate Stoneb9c1b512016-09-06 20:57:50 +00004010bool ProcessGDBRemote::StartNoticingNewThreads() {
4011 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
4012 if (m_thread_create_bp_sp) {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004013 if (log && log->GetVerbose())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004014 LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004015 m_thread_create_bp_sp->SetEnabled(true);
4016 } else {
4017 PlatformSP platform_sp(GetTarget().GetPlatform());
4018 if (platform_sp) {
4019 m_thread_create_bp_sp =
4020 platform_sp->SetThreadCreationBreakpoint(GetTarget());
4021 if (m_thread_create_bp_sp) {
4022 if (log && log->GetVerbose())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004023 LLDB_LOGF(
4024 log, "Successfully created new thread notification breakpoint %i",
Kate Stoneb9c1b512016-09-06 20:57:50 +00004025 m_thread_create_bp_sp->GetID());
4026 m_thread_create_bp_sp->SetCallback(
4027 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
4028 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004029 LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004030 }
Jason Molendaa3329782014-03-29 18:54:20 +00004031 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004032 }
Konrad Kleine248a1302019-05-23 11:14:47 +00004033 return m_thread_create_bp_sp.get() != nullptr;
Jason Molendaa3329782014-03-29 18:54:20 +00004034}
4035
Kate Stoneb9c1b512016-09-06 20:57:50 +00004036bool ProcessGDBRemote::StopNoticingNewThreads() {
4037 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
4038 if (log && log->GetVerbose())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004039 LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004040
4041 if (m_thread_create_bp_sp)
4042 m_thread_create_bp_sp->SetEnabled(false);
4043
4044 return true;
4045}
4046
4047DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
Konrad Kleine248a1302019-05-23 11:14:47 +00004048 if (m_dyld_up.get() == nullptr)
4049 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004050 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004051}
4052
Zachary Turner97206d52017-05-12 04:51:55 +00004053Status ProcessGDBRemote::SendEventData(const char *data) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004054 int return_value;
4055 bool was_supported;
4056
Zachary Turner97206d52017-05-12 04:51:55 +00004057 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004058
4059 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
4060 if (return_value != 0) {
4061 if (!was_supported)
4062 error.SetErrorString("Sending events is not supported for this process.");
4063 else
4064 error.SetErrorStringWithFormat("Error sending event data: %d.",
4065 return_value);
4066 }
4067 return error;
4068}
4069
Antonio Afonso943faef2019-06-11 20:16:13 +00004070DataExtractor ProcessGDBRemote::GetAuxvData() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004071 DataBufferSP buf;
4072 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
4073 std::string response_string;
4074 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
4075 response_string) ==
4076 GDBRemoteCommunication::PacketResult::Success)
Jonas Devlieghere796ac802019-02-11 23:13:08 +00004077 buf = std::make_shared<DataBufferHeap>(response_string.c_str(),
4078 response_string.length());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004079 }
Antonio Afonso943faef2019-06-11 20:16:13 +00004080 return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
Steve Pucci03904ac2014-03-04 23:18:46 +00004081}
4082
Jason Molenda705b1802014-06-13 02:37:02 +00004083StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004084ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
4085 StructuredData::ObjectSP object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00004086
Kate Stoneb9c1b512016-09-06 20:57:50 +00004087 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004088 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004089 SystemRuntime *runtime = GetSystemRuntime();
4090 if (runtime) {
4091 runtime->AddThreadExtendedInfoPacketHints(args_dict);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004092 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004093 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004094
Kate Stoneb9c1b512016-09-06 20:57:50 +00004095 StreamString packet;
4096 packet << "jThreadExtendedInfo:";
4097 args_dict->Dump(packet, false);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004098
Kate Stoneb9c1b512016-09-06 20:57:50 +00004099 // FIXME the final character of a JSON dictionary, '}', is the escape
4100 // character in gdb-remote binary mode. lldb currently doesn't escape
Adrian Prantl05097242018-04-30 16:49:04 +00004101 // these characters in its packet output -- so we add the quoted version of
4102 // the } character here manually in case we talk to a debugserver which un-
4103 // escapes the characters at packet read time.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004104 packet << (char)(0x7d ^ 0x20);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004105
Kate Stoneb9c1b512016-09-06 20:57:50 +00004106 StringExtractorGDBRemote response;
4107 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004108 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4109 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004110 GDBRemoteCommunication::PacketResult::Success) {
4111 StringExtractorGDBRemote::ResponseType response_type =
4112 response.GetResponseType();
4113 if (response_type == StringExtractorGDBRemote::eResponse) {
4114 if (!response.Empty()) {
4115 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda705b1802014-06-13 02:37:02 +00004116 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004117 }
Jason Molenda705b1802014-06-13 02:37:02 +00004118 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004119 }
4120 return object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00004121}
4122
Kate Stoneb9c1b512016-09-06 20:57:50 +00004123StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4124 lldb::addr_t image_list_address, lldb::addr_t image_count) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004125
Kate Stoneb9c1b512016-09-06 20:57:50 +00004126 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4127 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4128 image_list_address);
4129 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004130
Kate Stoneb9c1b512016-09-06 20:57:50 +00004131 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4132}
4133
4134StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
4135 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4136
4137 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4138
4139 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4140}
4141
4142StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4143 const std::vector<lldb::addr_t> &load_addresses) {
4144 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4145 StructuredData::ArraySP addresses(new StructuredData::Array);
4146
4147 for (auto addr : load_addresses) {
4148 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
4149 addresses->AddItem(addr_sp);
4150 }
4151
4152 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4153
4154 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4155}
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004156
Jason Molenda37397352016-07-22 00:17:55 +00004157StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004158ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
4159 StructuredData::ObjectSP args_dict) {
4160 StructuredData::ObjectSP object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00004161
Kate Stoneb9c1b512016-09-06 20:57:50 +00004162 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4163 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +00004164 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
4165 std::chrono::seconds(10));
Jason Molenda37397352016-07-22 00:17:55 +00004166
Kate Stoneb9c1b512016-09-06 20:57:50 +00004167 StreamString packet;
4168 packet << "jGetLoadedDynamicLibrariesInfos:";
4169 args_dict->Dump(packet, false);
Jason Molenda37397352016-07-22 00:17:55 +00004170
Kate Stoneb9c1b512016-09-06 20:57:50 +00004171 // FIXME the final character of a JSON dictionary, '}', is the escape
4172 // character in gdb-remote binary mode. lldb currently doesn't escape
Adrian Prantl05097242018-04-30 16:49:04 +00004173 // these characters in its packet output -- so we add the quoted version of
4174 // the } character here manually in case we talk to a debugserver which un-
4175 // escapes the characters at packet read time.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004176 packet << (char)(0x7d ^ 0x20);
4177
4178 StringExtractorGDBRemote response;
4179 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004180 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4181 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004182 GDBRemoteCommunication::PacketResult::Success) {
4183 StringExtractorGDBRemote::ResponseType response_type =
4184 response.GetResponseType();
4185 if (response_type == StringExtractorGDBRemote::eResponse) {
4186 if (!response.Empty()) {
4187 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda37397352016-07-22 00:17:55 +00004188 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004189 }
Jason Molenda37397352016-07-22 00:17:55 +00004190 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004191 }
4192 return object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00004193}
4194
Kate Stoneb9c1b512016-09-06 20:57:50 +00004195StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
4196 StructuredData::ObjectSP object_sp;
4197 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4198
4199 if (m_gdb_comm.GetSharedCacheInfoSupported()) {
4200 StreamString packet;
4201 packet << "jGetSharedCacheInfo:";
4202 args_dict->Dump(packet, false);
4203
4204 // FIXME the final character of a JSON dictionary, '}', is the escape
4205 // character in gdb-remote binary mode. lldb currently doesn't escape
Adrian Prantl05097242018-04-30 16:49:04 +00004206 // these characters in its packet output -- so we add the quoted version of
4207 // the } character here manually in case we talk to a debugserver which un-
4208 // escapes the characters at packet read time.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004209 packet << (char)(0x7d ^ 0x20);
4210
4211 StringExtractorGDBRemote response;
4212 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004213 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4214 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004215 GDBRemoteCommunication::PacketResult::Success) {
4216 StringExtractorGDBRemote::ResponseType response_type =
4217 response.GetResponseType();
4218 if (response_type == StringExtractorGDBRemote::eResponse) {
4219 if (!response.Empty()) {
4220 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4221 }
4222 }
4223 }
4224 }
4225 return object_sp;
4226}
4227
Zachary Turner97206d52017-05-12 04:51:55 +00004228Status ProcessGDBRemote::ConfigureStructuredData(
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004229 ConstString type_name, const StructuredData::ObjectSP &config_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004230 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
Todd Fiala75930012016-08-19 04:21:48 +00004231}
Jason Molenda37397352016-07-22 00:17:55 +00004232
Adrian Prantl05097242018-04-30 16:49:04 +00004233// Establish the largest memory read/write payloads we should use. If the
4234// remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004235//
Adrian Prantl05097242018-04-30 16:49:04 +00004236// If the remote stub's max packet size is crazy large, use a reasonable
4237// largeish default.
Jason Molenda6076bf42014-05-06 04:34:52 +00004238//
Adrian Prantl05097242018-04-30 16:49:04 +00004239// If the remote stub doesn't advertise a max packet size, use a conservative
4240// default.
Jason Molenda6076bf42014-05-06 04:34:52 +00004241
Kate Stoneb9c1b512016-09-06 20:57:50 +00004242void ProcessGDBRemote::GetMaxMemorySize() {
4243 const uint64_t reasonable_largeish_default = 128 * 1024;
4244 const uint64_t conservative_default = 512;
Jason Molenda6076bf42014-05-06 04:34:52 +00004245
Kate Stoneb9c1b512016-09-06 20:57:50 +00004246 if (m_max_memory_size == 0) {
4247 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4248 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4249 // Save the stub's claimed maximum packet size
4250 m_remote_stub_max_memory_size = stub_max_size;
Jason Molenda6076bf42014-05-06 04:34:52 +00004251
Adrian Prantl05097242018-04-30 16:49:04 +00004252 // Even if the stub says it can support ginormous packets, don't exceed
4253 // our reasonable largeish default packet size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004254 if (stub_max_size > reasonable_largeish_default) {
4255 stub_max_size = reasonable_largeish_default;
4256 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004257
Adrian Prantl05097242018-04-30 16:49:04 +00004258 // Memory packet have other overheads too like Maddr,size:#NN Instead of
4259 // calculating the bytes taken by size and addr every time, we take a
4260 // maximum guess here.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00004261 if (stub_max_size > 70)
4262 stub_max_size -= 32 + 32 + 6;
4263 else {
4264 // In unlikely scenario that max packet size is less then 70, we will
4265 // hope that data being written is small enough to fit.
4266 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4267 GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4268 if (log)
4269 log->Warning("Packet size is too small. "
4270 "LLDB may face problems while writing memory");
4271 }
4272
Kate Stoneb9c1b512016-09-06 20:57:50 +00004273 m_max_memory_size = stub_max_size;
4274 } else {
4275 m_max_memory_size = conservative_default;
Jason Molenda6076bf42014-05-06 04:34:52 +00004276 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004277 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004278}
4279
Kate Stoneb9c1b512016-09-06 20:57:50 +00004280void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4281 uint64_t user_specified_max) {
4282 if (user_specified_max != 0) {
4283 GetMaxMemorySize();
Jason Molenda6076bf42014-05-06 04:34:52 +00004284
Kate Stoneb9c1b512016-09-06 20:57:50 +00004285 if (m_remote_stub_max_memory_size != 0) {
4286 if (m_remote_stub_max_memory_size < user_specified_max) {
4287 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4288 // packet size too
4289 // big, go as big
4290 // as the remote stub says we can go.
4291 } else {
4292 m_max_memory_size = user_specified_max; // user's packet size is good
4293 }
4294 } else {
4295 m_max_memory_size =
4296 user_specified_max; // user's packet size is probably fine
Jason Molenda6076bf42014-05-06 04:34:52 +00004297 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004298 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004299}
4300
Kate Stoneb9c1b512016-09-06 20:57:50 +00004301bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4302 const ArchSpec &arch,
4303 ModuleSpec &module_spec) {
4304 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004305
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004306 const ModuleCacheKey key(module_file_spec.GetPath(),
4307 arch.GetTriple().getTriple());
4308 auto cached = m_cached_module_specs.find(key);
4309 if (cached != m_cached_module_specs.end()) {
4310 module_spec = cached->second;
4311 return bool(module_spec);
4312 }
4313
Kate Stoneb9c1b512016-09-06 20:57:50 +00004314 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004315 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4316 __FUNCTION__, module_file_spec.GetPath().c_str(),
4317 arch.GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004318 return false;
4319 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004320
Kate Stoneb9c1b512016-09-06 20:57:50 +00004321 if (log) {
4322 StreamString stream;
4323 module_spec.Dump(stream);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004324 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4325 __FUNCTION__, module_file_spec.GetPath().c_str(),
4326 arch.GetTriple().getTriple().c_str(), stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004327 }
4328
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004329 m_cached_module_specs[key] = module_spec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004330 return true;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004331}
4332
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004333void ProcessGDBRemote::PrefetchModuleSpecs(
4334 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4335 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4336 if (module_specs) {
4337 for (const FileSpec &spec : module_file_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004338 m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4339 triple.getTriple())] = ModuleSpec();
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004340 for (const ModuleSpec &spec : *module_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004341 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4342 triple.getTriple())] = spec;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004343 }
4344}
4345
Pavel Labath2272c482018-06-18 15:02:23 +00004346llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
4347 return m_gdb_comm.GetOSVersion();
Jim Ingham13c30d22015-11-05 22:33:17 +00004348}
4349
Colin Rileyc3c95b22015-04-16 15:51:33 +00004350namespace {
4351
4352typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004353
4354typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004355struct RegisterSetInfo {
4356 ConstString name;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004357};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004358
Greg Claytond04f0ed2015-05-26 18:00:51 +00004359typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004360
Kate Stoneb9c1b512016-09-06 20:57:50 +00004361struct GdbServerTargetInfo {
4362 std::string arch;
4363 std::string osabi;
4364 stringVec includes;
4365 RegisterSetMap reg_set_map;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004366};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004367
Kate Stoneb9c1b512016-09-06 20:57:50 +00004368bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4369 GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4370 uint32_t &cur_reg_num, uint32_t &reg_offset) {
4371 if (!feature_node)
4372 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004373
Kate Stoneb9c1b512016-09-06 20:57:50 +00004374 feature_node.ForEachChildElementWithName(
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00004375 "reg",
4376 [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset,
4377 &abi_sp](const XMLNode &reg_node) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004378 std::string gdb_group;
4379 std::string gdb_type;
4380 ConstString reg_name;
4381 ConstString alt_name;
4382 ConstString set_name;
4383 std::vector<uint32_t> value_regs;
4384 std::vector<uint32_t> invalidate_regs;
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004385 std::vector<uint8_t> dwarf_opcode_bytes;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004386 bool encoding_set = false;
4387 bool format_set = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004388 RegisterInfo reg_info = {
Konrad Kleine248a1302019-05-23 11:14:47 +00004389 nullptr, // Name
4390 nullptr, // Alt name
Kate Stoneb9c1b512016-09-06 20:57:50 +00004391 0, // byte size
4392 reg_offset, // offset
4393 eEncodingUint, // encoding
4394 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004395 {
Jason Molendabf67a302015-09-01 05:17:01 +00004396 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004397 LLDB_INVALID_REGNUM, // DWARF reg num
4398 LLDB_INVALID_REGNUM, // generic reg num
Kate Stoneb9c1b512016-09-06 20:57:50 +00004399 cur_reg_num, // process plugin reg num
4400 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004401 },
Konrad Kleine248a1302019-05-23 11:14:47 +00004402 nullptr,
4403 nullptr,
4404 nullptr, // Dwarf Expression opcode bytes pointer
4405 0 // Dwarf Expression opcode bytes length
Greg Claytond04f0ed2015-05-26 18:00:51 +00004406 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004407
Kate Stoneb9c1b512016-09-06 20:57:50 +00004408 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4409 &reg_name, &alt_name, &set_name, &value_regs,
4410 &invalidate_regs, &encoding_set, &format_set,
Zachary Turner3bc714b2017-03-02 00:05:25 +00004411 &reg_info, &reg_offset, &dwarf_opcode_bytes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004412 const llvm::StringRef &name,
4413 const llvm::StringRef &value) -> bool {
4414 if (name == "name") {
4415 reg_name.SetString(value);
4416 } else if (name == "bitsize") {
4417 reg_info.byte_size =
4418 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4419 } else if (name == "type") {
4420 gdb_type = value.str();
4421 } else if (name == "group") {
4422 gdb_group = value.str();
4423 } else if (name == "regnum") {
4424 const uint32_t regnum =
4425 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4426 if (regnum != LLDB_INVALID_REGNUM) {
4427 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004428 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004429 } else if (name == "offset") {
4430 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4431 } else if (name == "altname") {
4432 alt_name.SetString(value);
4433 } else if (name == "encoding") {
4434 encoding_set = true;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004435 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004436 } else if (name == "format") {
4437 format_set = true;
4438 Format format = eFormatInvalid;
Konrad Kleine248a1302019-05-23 11:14:47 +00004439 if (OptionArgParser::ToFormat(value.data(), format, nullptr)
4440 .Success())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004441 reg_info.format = format;
4442 else if (value == "vector-sint8")
4443 reg_info.format = eFormatVectorOfSInt8;
4444 else if (value == "vector-uint8")
4445 reg_info.format = eFormatVectorOfUInt8;
4446 else if (value == "vector-sint16")
4447 reg_info.format = eFormatVectorOfSInt16;
4448 else if (value == "vector-uint16")
4449 reg_info.format = eFormatVectorOfUInt16;
4450 else if (value == "vector-sint32")
4451 reg_info.format = eFormatVectorOfSInt32;
4452 else if (value == "vector-uint32")
4453 reg_info.format = eFormatVectorOfUInt32;
4454 else if (value == "vector-float32")
4455 reg_info.format = eFormatVectorOfFloat32;
Valentina Giusticda0ae42016-09-08 14:16:45 +00004456 else if (value == "vector-uint64")
4457 reg_info.format = eFormatVectorOfUInt64;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004458 else if (value == "vector-uint128")
4459 reg_info.format = eFormatVectorOfUInt128;
4460 } else if (name == "group_id") {
4461 const uint32_t set_id =
4462 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4463 RegisterSetMap::const_iterator pos =
4464 target_info.reg_set_map.find(set_id);
4465 if (pos != target_info.reg_set_map.end())
4466 set_name = pos->second.name;
4467 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4468 reg_info.kinds[eRegisterKindEHFrame] =
4469 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4470 } else if (name == "dwarf_regnum") {
4471 reg_info.kinds[eRegisterKindDWARF] =
4472 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4473 } else if (name == "generic") {
4474 reg_info.kinds[eRegisterKindGeneric] =
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004475 Args::StringToGenericRegister(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004476 } else if (name == "value_regnums") {
4477 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4478 } else if (name == "invalidate_regnums") {
4479 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4480 } else if (name == "dynamic_size_dwarf_expr_bytes") {
4481 StringExtractor opcode_extractor;
4482 std::string opcode_string = value.str();
4483 size_t dwarf_opcode_len = opcode_string.length() / 2;
4484 assert(dwarf_opcode_len > 0);
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004485
Kate Stoneb9c1b512016-09-06 20:57:50 +00004486 dwarf_opcode_bytes.resize(dwarf_opcode_len);
4487 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4488 opcode_extractor.GetStringRef().swap(opcode_string);
4489 uint32_t ret_val =
4490 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4491 assert(dwarf_opcode_len == ret_val);
Hafiz Abid Qadeer05008ca2017-01-19 15:11:01 +00004492 UNUSED_IF_ASSERT_DISABLED(ret_val);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004493 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4494 } else {
4495 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4496 }
4497 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004498 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004499
Kate Stoneb9c1b512016-09-06 20:57:50 +00004500 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4501 if (gdb_type.find("int") == 0) {
4502 reg_info.format = eFormatHex;
4503 reg_info.encoding = eEncodingUint;
4504 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4505 reg_info.format = eFormatAddressInfo;
4506 reg_info.encoding = eEncodingUint;
4507 } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4508 reg_info.format = eFormatFloat;
4509 reg_info.encoding = eEncodingIEEE754;
4510 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004511 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004512
Kate Stoneb9c1b512016-09-06 20:57:50 +00004513 // Only update the register set name if we didn't get a "reg_set"
Adrian Prantl05097242018-04-30 16:49:04 +00004514 // attribute. "set_name" will be empty if we didn't have a "reg_set"
Kate Stoneb9c1b512016-09-06 20:57:50 +00004515 // attribute.
Jason Molenda16592762019-06-26 21:59:39 +00004516 if (!set_name) {
4517 if (!gdb_group.empty()) {
4518 set_name.SetCString(gdb_group.c_str());
4519 } else {
4520 // If no register group name provided anywhere,
4521 // we'll create a 'general' register set
4522 set_name.SetCString("general");
4523 }
4524 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004525
Greg Claytond04f0ed2015-05-26 18:00:51 +00004526 reg_info.byte_offset = reg_offset;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004527 assert(reg_info.byte_size != 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004528 reg_offset += reg_info.byte_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004529 if (!value_regs.empty()) {
4530 value_regs.push_back(LLDB_INVALID_REGNUM);
4531 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004532 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004533 if (!invalidate_regs.empty()) {
4534 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4535 reg_info.invalidate_regs = invalidate_regs.data();
Greg Claytond04f0ed2015-05-26 18:00:51 +00004536 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004537
Jason Molenda63bd0db2015-09-15 23:20:34 +00004538 ++cur_reg_num;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004539 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004540 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004541
Greg Claytond04f0ed2015-05-26 18:00:51 +00004542 return true; // Keep iterating through all "reg" elements
Kate Stoneb9c1b512016-09-06 20:57:50 +00004543 });
4544 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004545}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004546
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00004547} // namespace
Colin Rileyc3c95b22015-04-16 15:51:33 +00004548
Jason Molenda16592762019-06-26 21:59:39 +00004549// This method fetches a register description feature xml file from
4550// the remote stub and adds registers/register groupsets/architecture
4551// information to the current process. It will call itself recursively
4552// for nested register definition files. It returns true if it was able
4553// to fetch and parse an xml file.
4554bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(ArchSpec &arch_to_use,
4555 std::string xml_filename,
4556 uint32_t &cur_reg_num,
4557 uint32_t &reg_offset) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004558 // request the target xml file
4559 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004560 lldb_private::Status lldberr;
Jason Molenda16592762019-06-26 21:59:39 +00004561 if (!m_gdb_comm.ReadExtFeature(ConstString("features"),
4562 ConstString(xml_filename.c_str()),
Kate Stoneb9c1b512016-09-06 20:57:50 +00004563 raw, lldberr)) {
4564 return false;
4565 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004566
Kate Stoneb9c1b512016-09-06 20:57:50 +00004567 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004568
Jason Molenda16592762019-06-26 21:59:39 +00004569 if (xml_document.ParseMemory(raw.c_str(), raw.size(), xml_filename.c_str())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004570 GdbServerTargetInfo target_info;
Jason Molenda16592762019-06-26 21:59:39 +00004571 std::vector<XMLNode> feature_nodes;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004572
Jason Molenda16592762019-06-26 21:59:39 +00004573 // The top level feature XML file will start with a <target> tag.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004574 XMLNode target_node = xml_document.GetRootElement("target");
4575 if (target_node) {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004576 target_node.ForEachChildElement([&target_info, &feature_nodes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004577 const XMLNode &node) -> bool {
4578 llvm::StringRef name = node.GetName();
4579 if (name == "architecture") {
4580 node.GetElementText(target_info.arch);
4581 } else if (name == "osabi") {
4582 node.GetElementText(target_info.osabi);
4583 } else if (name == "xi:include" || name == "include") {
4584 llvm::StringRef href = node.GetAttributeValue("href");
4585 if (!href.empty())
4586 target_info.includes.push_back(href.str());
4587 } else if (name == "feature") {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004588 feature_nodes.push_back(node);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004589 } else if (name == "groups") {
4590 node.ForEachChildElementWithName(
4591 "group", [&target_info](const XMLNode &node) -> bool {
4592 uint32_t set_id = UINT32_MAX;
4593 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004594
Kate Stoneb9c1b512016-09-06 20:57:50 +00004595 node.ForEachAttribute(
4596 [&set_id, &set_info](const llvm::StringRef &name,
4597 const llvm::StringRef &value) -> bool {
4598 if (name == "id")
4599 set_id = StringConvert::ToUInt32(value.data(),
4600 UINT32_MAX, 0);
4601 if (name == "name")
4602 set_info.name = ConstString(value);
4603 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004604 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004605
Kate Stoneb9c1b512016-09-06 20:57:50 +00004606 if (set_id != UINT32_MAX)
4607 target_info.reg_set_map[set_id] = set_info;
4608 return true; // Keep iterating through all "group" elements
4609 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004610 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004611 return true; // Keep iterating through all children of the target_node
4612 });
Jason Molenda16592762019-06-26 21:59:39 +00004613 } else {
4614 // In an included XML feature file, we're already "inside" the <target>
4615 // tag of the initial XML file; this included file will likely only have
4616 // a <feature> tag. Need to check for any more included files in this
4617 // <feature> element.
4618 XMLNode feature_node = xml_document.GetRootElement("feature");
4619 if (feature_node) {
4620 feature_nodes.push_back(feature_node);
4621 feature_node.ForEachChildElement([&target_info](
4622 const XMLNode &node) -> bool {
4623 llvm::StringRef name = node.GetName();
4624 if (name == "xi:include" || name == "include") {
4625 llvm::StringRef href = node.GetAttributeValue("href");
4626 if (!href.empty())
4627 target_info.includes.push_back(href.str());
4628 }
4629 return true;
4630 });
4631 }
4632 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004633
Jason Molenda16592762019-06-26 21:59:39 +00004634 // If the target.xml includes an architecture entry like
4635 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4636 // <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board)
4637 // use that if we don't have anything better.
4638 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4639 if (target_info.arch == "i386:x86-64") {
4640 // We don't have any information about vendor or OS.
4641 arch_to_use.SetTriple("x86_64--");
4642 GetTarget().MergeArchitecture(arch_to_use);
Jason Molendac4dd04c2018-01-12 01:16:13 +00004643 }
4644
Jason Molenda16592762019-06-26 21:59:39 +00004645 // SEGGER J-Link jtag boards send this very-generic arch name,
4646 // we'll need to use this if we have absolutely nothing better
4647 // to work with or the register definitions won't be accepted.
4648 if (target_info.arch == "arm") {
4649 arch_to_use.SetTriple("arm--");
4650 GetTarget().MergeArchitecture(arch_to_use);
4651 }
4652 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004653
Jason Molenda16592762019-06-26 21:59:39 +00004654 if (arch_to_use.IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004655 // Don't use Process::GetABI, this code gets called from DidAttach, and
4656 // in that context we haven't set the Target's architecture yet, so the
4657 // ABI is also potentially incorrect.
Jason Molenda43294c92017-06-29 02:57:03 +00004658 ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004659 for (auto &feature_node : feature_nodes) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004660 ParseRegisters(feature_node, target_info, this->m_register_info,
4661 abi_to_use_sp, cur_reg_num, reg_offset);
4662 }
4663
4664 for (const auto &include : target_info.includes) {
Jason Molenda16592762019-06-26 21:59:39 +00004665 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4666 cur_reg_num, reg_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004667 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004668 }
Jason Molenda16592762019-06-26 21:59:39 +00004669 } else {
4670 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004671 }
Jason Molenda16592762019-06-26 21:59:39 +00004672 return true;
4673}
4674
4675// query the target of gdb-remote for extended target information returns
4676// true on success (got register definitions), false on failure (did not).
4677bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4678 // Make sure LLDB has an XML parser it can use first
4679 if (!XMLDocument::XMLEnabled())
4680 return false;
4681
4682 // check that we have extended feature read support
4683 if (!m_gdb_comm.GetQXferFeaturesReadSupported())
4684 return false;
4685
4686 uint32_t cur_reg_num = 0;
4687 uint32_t reg_offset = 0;
4688 if (GetGDBServerRegisterInfoXMLAndProcess (arch_to_use, "target.xml", cur_reg_num, reg_offset))
4689 this->m_register_info.Finalize(arch_to_use);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004690
4691 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004692}
4693
Antonio Afonsod6682602019-07-25 14:28:21 +00004694llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004695 // Make sure LLDB has an XML parser it can use first
4696 if (!XMLDocument::XMLEnabled())
Antonio Afonsod6682602019-07-25 14:28:21 +00004697 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4698 "XML parsing not available");
Greg Claytond04f0ed2015-05-26 18:00:51 +00004699
Kate Stoneb9c1b512016-09-06 20:57:50 +00004700 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004701 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004702
Antonio Afonsod6682602019-07-25 14:28:21 +00004703 LoadedModuleInfoList list;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004704 GDBRemoteCommunicationClient &comm = m_gdb_comm;
Antonio Afonsof8251f12019-07-03 17:30:07 +00004705 bool can_use_svr4 = GetGlobalPluginProperties()->GetUseSVR4();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004706
4707 // check that we have extended feature read support
Antonio Afonsof8251f12019-07-03 17:30:07 +00004708 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004709 // request the loaded library list
4710 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004711 lldb_private::Status lldberr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004712
4713 if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4714 raw, lldberr))
Antonio Afonsod6682602019-07-25 14:28:21 +00004715 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4716 "Error in libraries-svr4 packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004717
4718 // parse the xml file in memory
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004719 LLDB_LOGF(log, "parsing: %s", raw.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004720 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004721
Kate Stoneb9c1b512016-09-06 20:57:50 +00004722 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Antonio Afonsod6682602019-07-25 14:28:21 +00004723 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4724 "Error reading noname.xml");
Aidan Doddsc0c83852015-05-08 09:36:31 +00004725
Kate Stoneb9c1b512016-09-06 20:57:50 +00004726 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4727 if (!root_element)
Antonio Afonsod6682602019-07-25 14:28:21 +00004728 return llvm::createStringError(
4729 llvm::inconvertibleErrorCode(),
4730 "Error finding library-list-svr4 xml element");
Aidan Doddsc0c83852015-05-08 09:36:31 +00004731
Kate Stoneb9c1b512016-09-06 20:57:50 +00004732 // main link map structure
4733 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4734 if (!main_lm.empty()) {
4735 list.m_link_map =
4736 StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4737 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004738
Kate Stoneb9c1b512016-09-06 20:57:50 +00004739 root_element.ForEachChildElementWithName(
4740 "library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004741
Kate Stoneb9c1b512016-09-06 20:57:50 +00004742 LoadedModuleInfoList::LoadedModuleInfo module;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004743
Kate Stoneb9c1b512016-09-06 20:57:50 +00004744 library.ForEachAttribute(
Zachary Turner3bc714b2017-03-02 00:05:25 +00004745 [&module](const llvm::StringRef &name,
4746 const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004747
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004748 if (name == "name")
Kate Stoneb9c1b512016-09-06 20:57:50 +00004749 module.set_name(value.str());
4750 else if (name == "lm") {
4751 // the address of the link_map struct.
4752 module.set_link_map(StringConvert::ToUInt64(
4753 value.data(), LLDB_INVALID_ADDRESS, 0));
4754 } else if (name == "l_addr") {
4755 // the displacement as read from the field 'l_addr' of the
4756 // link_map struct.
4757 module.set_base(StringConvert::ToUInt64(
4758 value.data(), LLDB_INVALID_ADDRESS, 0));
4759 // base address is always a displacement, not an absolute
4760 // value.
4761 module.set_base_is_offset(true);
4762 } else if (name == "l_ld") {
4763 // the memory address of the libraries PT_DYAMIC section.
4764 module.set_dynamic(StringConvert::ToUInt64(
4765 value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004766 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004767
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004768 return true; // Keep iterating over all properties of "library"
Kate Stoneb9c1b512016-09-06 20:57:50 +00004769 });
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004770
Kate Stoneb9c1b512016-09-06 20:57:50 +00004771 if (log) {
4772 std::string name;
4773 lldb::addr_t lm = 0, base = 0, ld = 0;
4774 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004775
Kate Stoneb9c1b512016-09-06 20:57:50 +00004776 module.get_name(name);
4777 module.get_link_map(lm);
4778 module.get_base(base);
4779 module.get_base_is_offset(base_is_offset);
4780 module.get_dynamic(ld);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004781
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004782 LLDB_LOGF(log,
4783 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4784 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4785 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4786 name.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004787 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004788
Kate Stoneb9c1b512016-09-06 20:57:50 +00004789 list.add(module);
4790 return true; // Keep iterating over all "library" elements in the root
4791 // node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004792 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004793
Antonio Afonsod6682602019-07-25 14:28:21 +00004794 if (log)
4795 LLDB_LOGF(log, "found %" PRId32 " modules in total",
4796 (int)list.m_list.size());
4797 return list;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004798 } else if (comm.GetQXferLibrariesReadSupported()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004799 // request the loaded library list
4800 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004801 lldb_private::Status lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004802
Kate Stoneb9c1b512016-09-06 20:57:50 +00004803 if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4804 lldberr))
Antonio Afonsod6682602019-07-25 14:28:21 +00004805 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4806 "Error in libraries packet");
Aidan Doddsc0c83852015-05-08 09:36:31 +00004807
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004808 LLDB_LOGF(log, "parsing: %s", raw.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004809 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004810
Kate Stoneb9c1b512016-09-06 20:57:50 +00004811 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Antonio Afonsod6682602019-07-25 14:28:21 +00004812 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4813 "Error reading noname.xml");
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004814
Kate Stoneb9c1b512016-09-06 20:57:50 +00004815 XMLNode root_element = doc.GetRootElement("library-list");
4816 if (!root_element)
Antonio Afonsod6682602019-07-25 14:28:21 +00004817 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4818 "Error finding library-list xml element");
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004819
Kate Stoneb9c1b512016-09-06 20:57:50 +00004820 root_element.ForEachChildElementWithName(
4821 "library", [log, &list](const XMLNode &library) -> bool {
4822 LoadedModuleInfoList::LoadedModuleInfo module;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004823
Kate Stoneb9c1b512016-09-06 20:57:50 +00004824 llvm::StringRef name = library.GetAttributeValue("name");
4825 module.set_name(name.str());
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004826
Kate Stoneb9c1b512016-09-06 20:57:50 +00004827 // The base address of a given library will be the address of its
4828 // first section. Most remotes send only one section for Windows
4829 // targets for example.
4830 const XMLNode &section =
4831 library.FindFirstChildElementWithName("section");
4832 llvm::StringRef address = section.GetAttributeValue("address");
4833 module.set_base(
4834 StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4835 // These addresses are absolute values.
4836 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004837
Kate Stoneb9c1b512016-09-06 20:57:50 +00004838 if (log) {
4839 std::string name;
4840 lldb::addr_t base = 0;
4841 bool base_is_offset;
4842 module.get_name(name);
4843 module.get_base(base);
4844 module.get_base_is_offset(base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004845
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004846 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4847 (base_is_offset ? "offset" : "absolute"), name.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004848 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004849
Kate Stoneb9c1b512016-09-06 20:57:50 +00004850 list.add(module);
4851 return true; // Keep iterating over all "library" elements in the root
4852 // node
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004853 });
4854
Antonio Afonsod6682602019-07-25 14:28:21 +00004855 if (log)
4856 LLDB_LOGF(log, "found %" PRId32 " modules in total",
4857 (int)list.m_list.size());
4858 return list;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004859 } else {
Antonio Afonsod6682602019-07-25 14:28:21 +00004860 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4861 "Remote libraries not supported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004862 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004863}
4864
4865lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4866 lldb::addr_t link_map,
4867 lldb::addr_t base_addr,
4868 bool value_is_offset) {
4869 DynamicLoader *loader = GetDynamicLoader();
4870 if (!loader)
4871 return nullptr;
4872
4873 return loader->LoadModuleAtAddress(file, link_map, base_addr,
4874 value_is_offset);
4875}
4876
Antonio Afonsod6682602019-07-25 14:28:21 +00004877llvm::Error ProcessGDBRemote::LoadModules() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004878 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4879
4880 // request a list of loaded libraries from GDBServer
Antonio Afonsod6682602019-07-25 14:28:21 +00004881 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
4882 if (!module_list)
4883 return module_list.takeError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004884
4885 // get a list of all the modules
4886 ModuleList new_modules;
4887
Antonio Afonsod6682602019-07-25 14:28:21 +00004888 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004889 std::string mod_name;
4890 lldb::addr_t mod_base;
4891 lldb::addr_t link_map;
4892 bool mod_base_is_offset;
4893
4894 bool valid = true;
4895 valid &= modInfo.get_name(mod_name);
4896 valid &= modInfo.get_base(mod_base);
4897 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4898 if (!valid)
4899 continue;
4900
4901 if (!modInfo.get_link_map(link_map))
4902 link_map = LLDB_INVALID_ADDRESS;
4903
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00004904 FileSpec file(mod_name);
4905 FileSystem::Instance().Resolve(file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004906 lldb::ModuleSP module_sp =
4907 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4908
4909 if (module_sp.get())
4910 new_modules.Append(module_sp);
4911 }
4912
4913 if (new_modules.GetSize() > 0) {
4914 ModuleList removed_modules;
4915 Target &target = GetTarget();
4916 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4917
4918 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4919 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4920
4921 bool found = false;
4922 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4923 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4924 found = true;
4925 }
4926
4927 // The main executable will never be included in libraries-svr4, don't
4928 // remove it
4929 if (!found &&
4930 loaded_module.get() != target.GetExecutableModulePointer()) {
4931 removed_modules.Append(loaded_module);
4932 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004933 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004934
Kate Stoneb9c1b512016-09-06 20:57:50 +00004935 loaded_modules.Remove(removed_modules);
4936 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4937
4938 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4939 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4940 if (!obj)
4941 return true;
4942
4943 if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4944 return true;
4945
4946 lldb::ModuleSP module_copy_sp = module_sp;
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00004947 target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004948 return false;
4949 });
4950
4951 loaded_modules.AppendIfNeeded(new_modules);
4952 m_process->GetTarget().ModulesDidLoad(new_modules);
4953 }
4954
Antonio Afonsod6682602019-07-25 14:28:21 +00004955 return llvm::ErrorSuccess();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004956}
4957
Zachary Turner97206d52017-05-12 04:51:55 +00004958Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4959 bool &is_loaded,
4960 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004961 is_loaded = false;
4962 load_addr = LLDB_INVALID_ADDRESS;
4963
4964 std::string file_path = file.GetPath(false);
4965 if (file_path.empty())
Zachary Turner97206d52017-05-12 04:51:55 +00004966 return Status("Empty file name specified");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004967
4968 StreamString packet;
4969 packet.PutCString("qFileLoadAddress:");
Pavel Labath7f815a92019-02-12 14:28:55 +00004970 packet.PutStringAsRawHex8(file_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004971
4972 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004973 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4974 false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00004975 GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00004976 return Status("Sending qFileLoadAddress packet failed");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004977
4978 if (response.IsErrorResponse()) {
4979 if (response.GetError() == 1) {
4980 // The file is not loaded into the inferior
4981 is_loaded = false;
4982 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00004983 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004984 }
4985
Zachary Turner97206d52017-05-12 04:51:55 +00004986 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004987 "Fetching file load address from remote server returned an error");
4988 }
4989
4990 if (response.IsNormalResponse()) {
4991 is_loaded = true;
4992 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
Zachary Turner97206d52017-05-12 04:51:55 +00004993 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004994 }
4995
Zachary Turner97206d52017-05-12 04:51:55 +00004996 return Status(
4997 "Unknown error happened during sending the load address packet");
Aidan Doddsc0c83852015-05-08 09:36:31 +00004998}
4999
Kate Stoneb9c1b512016-09-06 20:57:50 +00005000void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
5001 // We must call the lldb_private::Process::ModulesDidLoad () first before we
5002 // do anything
5003 Process::ModulesDidLoad(module_list);
Aidan Doddsc0c83852015-05-08 09:36:31 +00005004
Adrian Prantl05097242018-04-30 16:49:04 +00005005 // After loading shared libraries, we can ask our remote GDB server if it
5006 // needs any symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005007 m_gdb_comm.ServeSymbolLookups(this);
Aidan Doddsc0c83852015-05-08 09:36:31 +00005008}
5009
Kate Stoneb9c1b512016-09-06 20:57:50 +00005010void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
5011 AppendSTDOUT(out.data(), out.size());
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005012}
5013
5014static const char *end_delimiter = "--end--;";
5015static const int end_delimiter_len = 8;
5016
Kate Stoneb9c1b512016-09-06 20:57:50 +00005017void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
5018 std::string input = data.str(); // '1' to move beyond 'A'
5019 if (m_partial_profile_data.length() > 0) {
5020 m_partial_profile_data.append(input);
5021 input = m_partial_profile_data;
5022 m_partial_profile_data.clear();
5023 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005024
Kate Stoneb9c1b512016-09-06 20:57:50 +00005025 size_t found, pos = 0, len = input.length();
5026 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
5027 StringExtractorGDBRemote profileDataExtractor(
5028 input.substr(pos, found).c_str());
5029 std::string profile_data =
5030 HarmonizeThreadIdsForProfileData(profileDataExtractor);
5031 BroadcastAsyncProfileData(profile_data);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005032
Kate Stoneb9c1b512016-09-06 20:57:50 +00005033 pos = found + end_delimiter_len;
5034 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005035
Kate Stoneb9c1b512016-09-06 20:57:50 +00005036 if (pos < len) {
5037 // Last incomplete chunk.
5038 m_partial_profile_data = input.substr(pos);
5039 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005040}
5041
Kate Stoneb9c1b512016-09-06 20:57:50 +00005042std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
5043 StringExtractorGDBRemote &profileDataExtractor) {
5044 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
5045 std::string output;
5046 llvm::raw_string_ostream output_stream(output);
5047 llvm::StringRef name, value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005048
Kate Stoneb9c1b512016-09-06 20:57:50 +00005049 // Going to assuming thread_used_usec comes first, else bail out.
5050 while (profileDataExtractor.GetNameColonValue(name, value)) {
5051 if (name.compare("thread_used_id") == 0) {
5052 StringExtractor threadIDHexExtractor(value);
5053 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005054
Kate Stoneb9c1b512016-09-06 20:57:50 +00005055 bool has_used_usec = false;
5056 uint32_t curr_used_usec = 0;
5057 llvm::StringRef usec_name, usec_value;
5058 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
5059 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
5060 if (usec_name.equals("thread_used_usec")) {
5061 has_used_usec = true;
5062 usec_value.getAsInteger(0, curr_used_usec);
5063 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005064 // We didn't find what we want, it is probably an older version. Bail
5065 // out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005066 profileDataExtractor.SetFilePos(input_file_pos);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005067 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005068 }
5069
5070 if (has_used_usec) {
5071 uint32_t prev_used_usec = 0;
5072 std::map<uint64_t, uint32_t>::iterator iterator =
5073 m_thread_id_to_used_usec_map.find(thread_id);
5074 if (iterator != m_thread_id_to_used_usec_map.end()) {
5075 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005076 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005077
5078 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
5079 // A good first time record is one that runs for at least 0.25 sec
5080 bool good_first_time =
5081 (prev_used_usec == 0) && (real_used_usec > 250000);
5082 bool good_subsequent_time =
5083 (prev_used_usec > 0) &&
5084 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
5085
5086 if (good_first_time || good_subsequent_time) {
Adrian Prantl05097242018-04-30 16:49:04 +00005087 // We try to avoid doing too many index id reservation, resulting in
5088 // fast increase of index ids.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005089
5090 output_stream << name << ":";
5091 int32_t index_id = AssignIndexIDToThread(thread_id);
5092 output_stream << index_id << ";";
5093
5094 output_stream << usec_name << ":" << usec_value << ";";
5095 } else {
5096 // Skip past 'thread_used_name'.
5097 llvm::StringRef local_name, local_value;
5098 profileDataExtractor.GetNameColonValue(local_name, local_value);
5099 }
5100
5101 // Store current time as previous time so that they can be compared
5102 // later.
5103 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5104 } else {
5105 // Bail out and use old string.
5106 output_stream << name << ":" << value << ";";
5107 }
5108 } else {
5109 output_stream << name << ":" << value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005110 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005111 }
5112 output_stream << end_delimiter;
5113 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005114
Kate Stoneb9c1b512016-09-06 20:57:50 +00005115 return output_stream.str();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005116}
5117
Kate Stoneb9c1b512016-09-06 20:57:50 +00005118void ProcessGDBRemote::HandleStopReply() {
5119 if (GetStopID() != 0)
5120 return;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005121
Kate Stoneb9c1b512016-09-06 20:57:50 +00005122 if (GetID() == LLDB_INVALID_PROCESS_ID) {
5123 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5124 if (pid != LLDB_INVALID_PROCESS_ID)
5125 SetID(pid);
5126 }
5127 BuildDynamicRegisterInfo(true);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005128}
Eugene Zelenko0722f082015-10-24 01:28:05 +00005129
Todd Fialafcdb1af2016-09-10 00:06:29 +00005130static const char *const s_async_json_packet_prefix = "JSON-async:";
5131
5132static StructuredData::ObjectSP
5133ParseStructuredDataPacket(llvm::StringRef packet) {
5134 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
5135
5136 if (!packet.consume_front(s_async_json_packet_prefix)) {
5137 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005138 LLDB_LOGF(
5139 log,
Bruce Mitchener4ebdee02018-05-29 09:10:46 +00005140 "GDBRemoteCommunicationClientBase::%s() received $J packet "
Todd Fialafcdb1af2016-09-10 00:06:29 +00005141 "but was not a StructuredData packet: packet starts with "
5142 "%s",
5143 __FUNCTION__,
5144 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
5145 }
5146 return StructuredData::ObjectSP();
5147 }
5148
Adrian Prantl05097242018-04-30 16:49:04 +00005149 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
Todd Fialafcdb1af2016-09-10 00:06:29 +00005150 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
5151 if (log) {
5152 if (json_sp) {
5153 StreamString json_str;
5154 json_sp->Dump(json_str);
5155 json_str.Flush();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005156 LLDB_LOGF(log,
5157 "ProcessGDBRemote::%s() "
5158 "received Async StructuredData packet: %s",
5159 __FUNCTION__, json_str.GetData());
Todd Fialafcdb1af2016-09-10 00:06:29 +00005160 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005161 LLDB_LOGF(log,
5162 "ProcessGDBRemote::%s"
5163 "() received StructuredData packet:"
5164 " parse failure",
5165 __FUNCTION__);
Todd Fialafcdb1af2016-09-10 00:06:29 +00005166 }
5167 }
5168 return json_sp;
5169}
5170
5171void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
5172 auto structured_data_sp = ParseStructuredDataPacket(data);
5173 if (structured_data_sp)
5174 RouteAsyncStructuredData(structured_data_sp);
Todd Fiala75930012016-08-19 04:21:48 +00005175}
5176
Kate Stoneb9c1b512016-09-06 20:57:50 +00005177class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
Greg Claytone034a042015-05-21 20:52:06 +00005178public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005179 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
5180 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5181 "Tests packet speeds of various sizes to determine "
5182 "the performance characteristics of the GDB remote "
5183 "connection. ",
Konrad Kleine248a1302019-05-23 11:14:47 +00005184 nullptr),
Kate Stoneb9c1b512016-09-06 20:57:50 +00005185 m_option_group(),
5186 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5187 "The number of packets to send of each varying size "
5188 "(default is 1000).",
5189 1000),
5190 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5191 "The maximum number of bytes to send in a packet. Sizes "
5192 "increase in powers of 2 while the size is less than or "
5193 "equal to this option value. (default 1024).",
5194 1024),
5195 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5196 "The maximum number of bytes to receive in a packet. Sizes "
5197 "increase in powers of 2 while the size is less than or "
5198 "equal to this option value. (default 1024).",
5199 1024),
5200 m_json(LLDB_OPT_SET_1, false, "json", 'j',
5201 "Print the output as JSON data for easy parsing.", false, true) {
5202 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5203 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5204 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5205 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5206 m_option_group.Finalize();
5207 }
Greg Claytone034a042015-05-21 20:52:06 +00005208
Raphael Isemann17566302019-05-03 10:03:28 +00005209 ~CommandObjectProcessGDBRemoteSpeedTest() override {}
Eugene Zelenko0722f082015-10-24 01:28:05 +00005210
Kate Stoneb9c1b512016-09-06 20:57:50 +00005211 Options *GetOptions() override { return &m_option_group; }
Greg Claytone034a042015-05-21 20:52:06 +00005212
Kate Stoneb9c1b512016-09-06 20:57:50 +00005213 bool DoExecute(Args &command, CommandReturnObject &result) override {
5214 const size_t argc = command.GetArgumentCount();
5215 if (argc == 0) {
5216 ProcessGDBRemote *process =
5217 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5218 .GetProcessPtr();
5219 if (process) {
5220 StreamSP output_stream_sp(
5221 m_interpreter.GetDebugger().GetAsyncOutputStream());
5222 result.SetImmediateOutputStream(output_stream_sp);
Greg Claytone034a042015-05-21 20:52:06 +00005223
Kate Stoneb9c1b512016-09-06 20:57:50 +00005224 const uint32_t num_packets =
5225 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5226 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5227 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5228 const bool json = m_json.GetOptionValue().GetCurrentValue();
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00005229 const uint64_t k_recv_amount =
5230 4 * 1024 * 1024; // Receive amount in bytes
5231 process->GetGDBRemote().TestPacketSpeed(
5232 num_packets, max_send, max_recv, k_recv_amount, json,
5233 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005234 result.SetStatus(eReturnStatusSuccessFinishResult);
5235 return true;
5236 }
5237 } else {
5238 result.AppendErrorWithFormat("'%s' takes no arguments",
5239 m_cmd_name.c_str());
Greg Claytone034a042015-05-21 20:52:06 +00005240 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005241 result.SetStatus(eReturnStatusFailed);
5242 return false;
5243 }
5244
Greg Claytone034a042015-05-21 20:52:06 +00005245protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005246 OptionGroupOptions m_option_group;
5247 OptionGroupUInt64 m_num_packets;
5248 OptionGroupUInt64 m_max_send;
5249 OptionGroupUInt64 m_max_recv;
5250 OptionGroupBoolean m_json;
Greg Claytone034a042015-05-21 20:52:06 +00005251};
5252
Kate Stoneb9c1b512016-09-06 20:57:50 +00005253class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005254private:
Greg Clayton998255b2012-10-13 02:07:45 +00005255public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005256 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5257 : CommandObjectParsed(interpreter, "process plugin packet history",
Konrad Kleine248a1302019-05-23 11:14:47 +00005258 "Dumps the packet history buffer. ", nullptr) {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005259
Raphael Isemann17566302019-05-03 10:03:28 +00005260 ~CommandObjectProcessGDBRemotePacketHistory() override {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005261
5262 bool DoExecute(Args &command, CommandReturnObject &result) override {
5263 const size_t argc = command.GetArgumentCount();
5264 if (argc == 0) {
5265 ProcessGDBRemote *process =
5266 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5267 .GetProcessPtr();
5268 if (process) {
5269 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5270 result.SetStatus(eReturnStatusSuccessFinishResult);
5271 return true;
5272 }
5273 } else {
5274 result.AppendErrorWithFormat("'%s' takes no arguments",
5275 m_cmd_name.c_str());
5276 }
5277 result.SetStatus(eReturnStatusFailed);
5278 return false;
5279 }
5280};
5281
5282class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5283private:
5284public:
5285 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5286 : CommandObjectParsed(
5287 interpreter, "process plugin packet xfer-size",
5288 "Maximum size that lldb will try to read/write one one chunk.",
Konrad Kleine248a1302019-05-23 11:14:47 +00005289 nullptr) {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005290
Raphael Isemann17566302019-05-03 10:03:28 +00005291 ~CommandObjectProcessGDBRemotePacketXferSize() override {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005292
5293 bool DoExecute(Args &command, CommandReturnObject &result) override {
5294 const size_t argc = command.GetArgumentCount();
5295 if (argc == 0) {
5296 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5297 "amount to be transferred when "
5298 "reading/writing",
5299 m_cmd_name.c_str());
5300 result.SetStatus(eReturnStatusFailed);
5301 return false;
Greg Clayton998255b2012-10-13 02:07:45 +00005302 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005303
Kate Stoneb9c1b512016-09-06 20:57:50 +00005304 ProcessGDBRemote *process =
5305 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5306 if (process) {
5307 const char *packet_size = command.GetArgumentAtIndex(0);
5308 errno = 0;
Konrad Kleine248a1302019-05-23 11:14:47 +00005309 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005310 if (errno == 0 && user_specified_max != 0) {
5311 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5312 result.SetStatus(eReturnStatusSuccessFinishResult);
5313 return true;
5314 }
5315 }
5316 result.SetStatus(eReturnStatusFailed);
5317 return false;
5318 }
5319};
5320
5321class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5322private:
5323public:
5324 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5325 : CommandObjectParsed(interpreter, "process plugin packet send",
5326 "Send a custom packet through the GDB remote "
5327 "protocol and print the answer. "
5328 "The packet header and footer will automatically "
5329 "be added to the packet prior to sending and "
5330 "stripped from the result.",
Konrad Kleine248a1302019-05-23 11:14:47 +00005331 nullptr) {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005332
Raphael Isemann17566302019-05-03 10:03:28 +00005333 ~CommandObjectProcessGDBRemotePacketSend() override {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005334
5335 bool DoExecute(Args &command, CommandReturnObject &result) override {
5336 const size_t argc = command.GetArgumentCount();
5337 if (argc == 0) {
5338 result.AppendErrorWithFormat(
5339 "'%s' takes a one or more packet content arguments",
5340 m_cmd_name.c_str());
5341 result.SetStatus(eReturnStatusFailed);
5342 return false;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005343 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005344
Kate Stoneb9c1b512016-09-06 20:57:50 +00005345 ProcessGDBRemote *process =
5346 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5347 if (process) {
5348 for (size_t i = 0; i < argc; ++i) {
5349 const char *packet_cstr = command.GetArgumentAtIndex(0);
5350 bool send_async = true;
5351 StringExtractorGDBRemote response;
5352 process->GetGDBRemote().SendPacketAndWaitForResponse(
5353 packet_cstr, response, send_async);
5354 result.SetStatus(eReturnStatusSuccessFinishResult);
5355 Stream &output_strm = result.GetOutputStream();
5356 output_strm.Printf(" packet: %s\n", packet_cstr);
5357 std::string &response_str = response.GetStringRef();
5358
Konrad Kleine248a1302019-05-23 11:14:47 +00005359 if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005360 response_str = process->HarmonizeThreadIdsForProfileData(response);
Greg Clayton02686b82012-10-15 22:42:16 +00005361 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005362
5363 if (response_str.empty())
5364 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
Greg Clayton02686b82012-10-15 22:42:16 +00005365 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005366 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5367 }
Greg Clayton02686b82012-10-15 22:42:16 +00005368 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005369 return true;
5370 }
Greg Clayton02686b82012-10-15 22:42:16 +00005371};
5372
Kate Stoneb9c1b512016-09-06 20:57:50 +00005373class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005374private:
Jason Molenda6076bf42014-05-06 04:34:52 +00005375public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005376 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5377 : CommandObjectRaw(interpreter, "process plugin packet monitor",
5378 "Send a qRcmd packet through the GDB remote protocol "
5379 "and print the response."
5380 "The argument passed to this command will be hex "
5381 "encoded into a valid 'qRcmd' packet, sent and the "
Zachary Turnera4496982016-10-05 21:14:38 +00005382 "response will be printed.") {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005383
Raphael Isemann17566302019-05-03 10:03:28 +00005384 ~CommandObjectProcessGDBRemotePacketMonitor() override {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005385
Raphael Isemann4d51a902018-07-12 22:28:52 +00005386 bool DoExecute(llvm::StringRef command,
5387 CommandReturnObject &result) override {
5388 if (command.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005389 result.AppendErrorWithFormat("'%s' takes a command string argument",
5390 m_cmd_name.c_str());
5391 result.SetStatus(eReturnStatusFailed);
5392 return false;
Jason Molenda6076bf42014-05-06 04:34:52 +00005393 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005394
Kate Stoneb9c1b512016-09-06 20:57:50 +00005395 ProcessGDBRemote *process =
5396 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5397 if (process) {
5398 StreamString packet;
5399 packet.PutCString("qRcmd,");
Raphael Isemann4d51a902018-07-12 22:28:52 +00005400 packet.PutBytesAsRawHex8(command.data(), command.size());
Ed Maste81b4c5f2016-01-04 01:43:47 +00005401
Kate Stoneb9c1b512016-09-06 20:57:50 +00005402 bool send_async = true;
5403 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005404 Stream &output_strm = result.GetOutputStream();
Pavel Labath7da84752018-01-10 14:39:08 +00005405 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5406 packet.GetString(), response, send_async,
5407 [&output_strm](llvm::StringRef output) { output_strm << output; });
5408 result.SetStatus(eReturnStatusSuccessFinishResult);
Zachary Turnerc1564272016-11-16 21:15:24 +00005409 output_strm.Printf(" packet: %s\n", packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005410 const std::string &response_str = response.GetStringRef();
Jason Molenda6076bf42014-05-06 04:34:52 +00005411
Kate Stoneb9c1b512016-09-06 20:57:50 +00005412 if (response_str.empty())
5413 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5414 else
5415 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
Jason Molenda6076bf42014-05-06 04:34:52 +00005416 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005417 return true;
5418 }
Jason Molenda6076bf42014-05-06 04:34:52 +00005419};
5420
Kate Stoneb9c1b512016-09-06 20:57:50 +00005421class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005422private:
Greg Clayton02686b82012-10-15 22:42:16 +00005423public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005424 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5425 : CommandObjectMultiword(interpreter, "process plugin packet",
5426 "Commands that deal with GDB remote packets.",
Konrad Kleine248a1302019-05-23 11:14:47 +00005427 nullptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005428 LoadSubCommand(
5429 "history",
5430 CommandObjectSP(
5431 new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5432 LoadSubCommand(
5433 "send", CommandObjectSP(
5434 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5435 LoadSubCommand(
5436 "monitor",
5437 CommandObjectSP(
5438 new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5439 LoadSubCommand(
5440 "xfer-size",
5441 CommandObjectSP(
5442 new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5443 LoadSubCommand("speed-test",
5444 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5445 interpreter)));
5446 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005447
Raphael Isemann17566302019-05-03 10:03:28 +00005448 ~CommandObjectProcessGDBRemotePacket() override {}
Greg Clayton998255b2012-10-13 02:07:45 +00005449};
5450
Kate Stoneb9c1b512016-09-06 20:57:50 +00005451class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
Greg Claytonba4a0a52013-02-01 23:03:47 +00005452public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005453 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5454 : CommandObjectMultiword(
5455 interpreter, "process plugin",
5456 "Commands for operating on a ProcessGDBRemote process.",
5457 "process plugin <subcommand> [<subcommand-options>]") {
5458 LoadSubCommand(
5459 "packet",
5460 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5461 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005462
Raphael Isemann17566302019-05-03 10:03:28 +00005463 ~CommandObjectMultiwordProcessGDBRemote() override {}
Greg Claytonba4a0a52013-02-01 23:03:47 +00005464};
5465
Kate Stoneb9c1b512016-09-06 20:57:50 +00005466CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5467 if (!m_command_sp)
Jonas Devlieghere796ac802019-02-11 23:13:08 +00005468 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
5469 GetTarget().GetDebugger().GetCommandInterpreter());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005470 return m_command_sp.get();
Greg Clayton998255b2012-10-13 02:07:45 +00005471}