blob: 80382007c329c424aa3457cde3721a728c2721ae [file] [log] [blame]
Raphael Isemann80814282020-01-24 08:23:27 +01001//===-- Process.cpp -------------------------------------------------------===//
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002//
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
Greg Clayton5cc45e02016-02-26 19:41:49 +00009#include <atomic>
Jonas Devlieghere796ac802019-02-11 23:13:08 +000010#include <memory>
Greg Clayton04df8ee2016-02-26 19:38:18 +000011#include <mutex>
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +000012
Pavel Labath2ce22162016-12-01 10:57:30 +000013#include "llvm/Support/ScopedPrinter.h"
Zachary Turner777de772017-03-04 16:42:25 +000014#include "llvm/Support/Threading.h"
15
Chris Lattner30fdc8d2010-06-08 16:52:24 +000016#include "lldb/Breakpoint/BreakpointLocation.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000017#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Greg Clayton1f746072012-08-29 21:13:06 +000019#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000020#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000022#include "lldb/Core/StreamFile.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000023#include "lldb/Expression/DiagnosticManager.h"
Alex Langfordbab7e3d2019-07-12 00:58:02 +000024#include "lldb/Expression/DynamicCheckerFunctions.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000025#include "lldb/Expression/UserExpression.h"
Jim Ingham1ecb34f2018-04-17 20:44:47 +000026#include "lldb/Expression/UtilityFunction.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000027#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000028#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000030#include "lldb/Host/HostInfo.h"
Zachary Turner3eb2b442017-03-22 23:33:16 +000031#include "lldb/Host/OptionParser.h"
Greg Clayton100eb932014-07-02 21:10:39 +000032#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000033#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000034#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000035#include "lldb/Interpreter/CommandInterpreter.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000036#include "lldb/Interpreter/OptionArgParser.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000037#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000038#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000039#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Target/ABI.h"
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +010041#include "lldb/Target/AssertFrameRecognizer.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000042#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000043#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000044#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000045#include "lldb/Target/JITLoaderList.h"
Alex Langford03e1a822019-05-29 18:08:22 +000046#include "lldb/Target/Language.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000047#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000048#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000049#include "lldb/Target/MemoryRegionInfo.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000050#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000051#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000052#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000054#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000055#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000056#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057#include "lldb/Target/Target.h"
58#include "lldb/Target/TargetList.h"
59#include "lldb/Target/Thread.h"
60#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000061#include "lldb/Target/ThreadPlanBase.h"
Alex Langford5b2b38e2019-09-13 00:02:05 +000062#include "lldb/Target/ThreadPlanCallFunction.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000063#include "lldb/Target/UnixSignals.h"
Pavel Labath181b8232018-12-14 15:59:49 +000064#include "lldb/Utility/Event.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000065#include "lldb/Utility/Log.h"
Zachary Turner50232572015-03-18 21:31:45 +000066#include "lldb/Utility/NameMatches.h"
Zachary Turner805e7102019-03-04 21:51:03 +000067#include "lldb/Utility/ProcessInfo.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000068#include "lldb/Utility/SelectHelper.h"
Pavel Labathd821c992018-08-07 11:07:21 +000069#include "lldb/Utility/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070
71using namespace lldb;
72using namespace lldb_private;
Pavel Labathe3e21cf2016-11-30 11:56:32 +000073using namespace std::chrono;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074
Kate Stoneb9c1b512016-09-06 20:57:50 +000075// Comment out line below to disable memory caching, overriding the process
Pavel Labath43d35412016-12-06 11:24:51 +000076// setting target.process.disable-memory-cache
Greg Clayton67cc0632012-08-22 17:17:09 +000077#define ENABLE_MEMORY_CACHING
78
79#ifdef ENABLE_MEMORY_CACHING
80#define DISABLE_MEM_CACHE_DEFAULT false
81#else
82#define DISABLE_MEM_CACHE_DEFAULT true
83#endif
84
Kate Stoneb9c1b512016-09-06 20:57:50 +000085class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000086public:
Adrian Prantl0e4c4822019-03-06 21:22:25 +000087 ProcessOptionValueProperties(ConstString name)
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 : OptionValueProperties(name) {}
89
Adrian Prantl05097242018-04-30 16:49:04 +000090 // This constructor is used when creating ProcessOptionValueProperties when
91 // it is part of a new lldb_private::Process instance. It will copy all
92 // current global property values as needed
Kate Stoneb9c1b512016-09-06 20:57:50 +000093 ProcessOptionValueProperties(ProcessProperties *global_properties)
94 : OptionValueProperties(*global_properties->GetValueProperties()) {}
95
96 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
97 bool will_modify,
98 uint32_t idx) const override {
Adrian Prantl05097242018-04-30 16:49:04 +000099 // When getting the value for a key from the process options, we will
100 // always try and grab the setting from the current process if there is
101 // one. Else we just use the one from this instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102 if (exe_ctx) {
103 Process *process = exe_ctx->GetProcessPtr();
104 if (process) {
105 ProcessOptionValueProperties *instance_properties =
106 static_cast<ProcessOptionValueProperties *>(
107 process->GetValueProperties().get());
108 if (this != instance_properties)
109 return instance_properties->ProtectedGetPropertyAtIndex(idx);
110 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000111 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 return ProtectedGetPropertyAtIndex(idx);
113 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000114};
115
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000116#define LLDB_PROPERTIES_process
Jordan Rupprecht6a253d32019-07-29 17:22:10 +0000117#include "TargetProperties.inc"
Greg Clayton67cc0632012-08-22 17:17:09 +0000118
119enum {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000120#define LLDB_PROPERTIES_process
Jordan Rupprecht6a253d32019-07-29 17:22:10 +0000121#include "TargetPropertiesEnum.inc"
Greg Clayton67cc0632012-08-22 17:17:09 +0000122};
123
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124ProcessProperties::ProcessProperties(lldb_private::Process *process)
125 : Properties(),
126 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000127{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 if (process == nullptr) {
129 // Global process properties, set them up one time
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000130 m_collection_sp =
131 std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000132 m_collection_sp->Initialize(g_process_properties);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 m_collection_sp->AppendProperty(
134 ConstString("thread"), ConstString("Settings specific to threads."),
135 true, Thread::GetGlobalProperties()->GetValueProperties());
136 } else {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000137 m_collection_sp = std::make_shared<ProcessOptionValueProperties>(
138 Process::GetGlobalProperties().get());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 m_collection_sp->SetValueChangedCallback(
140 ePropertyPythonOSPluginPath,
Pavel Labath5c4661b2020-01-09 14:14:54 +0100141 [this] { m_process->LoadOperatingSystemPlugin(true); });
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000143}
144
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000145ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147bool ProcessProperties::GetDisableMemoryCache() const {
148 const uint32_t idx = ePropertyDisableMemCache;
149 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000150 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000151}
152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
154 const uint32_t idx = ePropertyMemCacheLineSize;
155 return m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000156 nullptr, idx, g_process_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000157}
158
Kate Stoneb9c1b512016-09-06 20:57:50 +0000159Args ProcessProperties::GetExtraStartupCommands() const {
160 Args args;
161 const uint32_t idx = ePropertyExtraStartCommand;
162 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
163 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000164}
165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166void ProcessProperties::SetExtraStartupCommands(const Args &args) {
167 const uint32_t idx = ePropertyExtraStartCommand;
168 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000169}
170
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171FileSpec ProcessProperties::GetPythonOSPluginPath() const {
172 const uint32_t idx = ePropertyPythonOSPluginPath;
173 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000174}
175
Kate Stoneb9c1b512016-09-06 20:57:50 +0000176void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
177 const uint32_t idx = ePropertyPythonOSPluginPath;
178 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000179}
180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
182 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
183 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000184 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000185}
186
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
188 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
189 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000190}
191
Kate Stoneb9c1b512016-09-06 20:57:50 +0000192bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
193 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
194 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000195 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000196}
197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
199 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
200 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000201}
202
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
204 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
205 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000206 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000207}
208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
210 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
211 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
212}
213
214bool ProcessProperties::GetDetachKeepsStopped() const {
215 const uint32_t idx = ePropertyDetachKeepsStopped;
216 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000217 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000218}
219
220void ProcessProperties::SetDetachKeepsStopped(bool stop) {
221 const uint32_t idx = ePropertyDetachKeepsStopped;
222 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
223}
224
225bool ProcessProperties::GetWarningsOptimization() const {
226 const uint32_t idx = ePropertyWarningOptimization;
227 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000228 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229}
230
Jim Inghamba205c12017-12-05 02:50:45 +0000231bool ProcessProperties::GetStopOnExec() const {
232 const uint32_t idx = ePropertyStopOnExec;
233 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000234 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Inghamba205c12017-12-05 02:50:45 +0000235}
236
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000237std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
238 const uint32_t idx = ePropertyUtilityExpressionTimeout;
239 uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000240 nullptr, idx, g_process_properties[idx].default_uint_value);
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000241 return std::chrono::seconds(value);
242}
243
Zachary Turner97206d52017-05-12 04:51:55 +0000244Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000245 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000246 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000247 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248 const int short_option = m_getopt_table[option_idx].val;
249
250 switch (short_option) {
251 case 's': // Stop at program entry point
252 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
253 break;
254
255 case 'i': // STDIN for read only
256 {
257 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000258 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 launch_info.AppendFileAction(action);
260 break;
261 }
262
263 case 'o': // Open STDOUT for write only
264 {
265 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000266 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 launch_info.AppendFileAction(action);
268 break;
269 }
270
271 case 'e': // STDERR for write only
272 {
273 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000274 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275 launch_info.AppendFileAction(action);
276 break;
277 }
278
279 case 'p': // Process plug-in name
280 launch_info.SetProcessPluginName(option_arg);
281 break;
282
283 case 'n': // Disable STDIO
284 {
285 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000286 const FileSpec dev_null(FileSystem::DEV_NULL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000287 if (action.Open(STDIN_FILENO, dev_null, true, false))
288 launch_info.AppendFileAction(action);
289 if (action.Open(STDOUT_FILENO, dev_null, false, true))
290 launch_info.AppendFileAction(action);
291 if (action.Open(STDERR_FILENO, dev_null, false, true))
292 launch_info.AppendFileAction(action);
293 break;
294 }
295
296 case 'w':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000297 launch_info.SetWorkingDirectory(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 break;
299
300 case 't': // Open process in new terminal window
301 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
302 break;
303
304 case 'a': {
305 TargetSP target_sp =
306 execution_context ? execution_context->GetTargetSP() : TargetSP();
307 PlatformSP platform_sp =
308 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000309 launch_info.GetArchitecture() =
310 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311 } break;
312
313 case 'A': // Disable ASLR.
314 {
315 bool success;
316 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000317 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318 if (success)
319 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000320 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321 error.SetErrorStringWithFormat(
322 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000323 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324 break;
325 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000326
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327 case 'X': // shell expand args.
328 {
329 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000330 const bool expand_args =
331 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 if (success)
333 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000334 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 error.SetErrorStringWithFormat(
336 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000337 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 break;
339 }
340
341 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000342 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000343 launch_info.SetShell(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 else
345 launch_info.SetShell(HostInfo::GetDefaultShell());
346 break;
347
348 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000349 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 break;
351
352 default:
353 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
354 short_option);
355 break;
356 }
357 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000358}
359
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000360static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000362 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 "Stop at the entry point of the program when launching a process."},
364 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000365 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 "Set whether to disable address space layout randomization when launching "
367 "a process."},
368 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000369 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 "Name of the process plugin you want to use."},
371 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000372 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 eArgTypeDirectoryName,
374 "Set the current working directory to <path> when running the inferior."},
375 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000376 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 "Set the architecture for the process to launch when ambiguous."},
378 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000379 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380 "Specify an environment variable name/value string (--environment "
381 "NAME=VALUE). Can be specified multiple times for subsequent environment "
382 "entries."},
383 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000384 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000386
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000388 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389 "Redirect stdin for the process to <filename>."},
390 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000391 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 "Redirect stdout for the process to <filename>."},
393 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000394 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000398 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000402 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 "Do not set up for terminal I/O to go to running process."},
404 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000405 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000407};
408
409llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000410 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000411}
Greg Clayton32e0a752011-03-30 18:16:51 +0000412
Zachary Turner31659452016-11-17 21:15:14 +0000413ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
414 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 ListenerSP listener_sp,
416 const FileSpec *crash_file_path) {
417 static uint32_t g_process_unique_id = 0;
418
419 ProcessSP process_sp;
420 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000421 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422 ConstString const_plugin_name(plugin_name);
423 create_callback =
424 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
425 if (create_callback) {
426 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
427 if (process_sp) {
428 if (process_sp->CanDebug(target_sp, true)) {
429 process_sp->m_process_unique_id = ++g_process_unique_id;
430 } else
431 process_sp.reset();
432 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000433 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434 } else {
435 for (uint32_t idx = 0;
436 (create_callback =
437 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
438 ++idx) {
439 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
440 if (process_sp) {
441 if (process_sp->CanDebug(target_sp, false)) {
442 process_sp->m_process_unique_id = ++g_process_unique_id;
443 break;
444 } else
445 process_sp.reset();
446 }
447 }
448 }
449 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000450}
451
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452ConstString &Process::GetStaticBroadcasterClass() {
453 static ConstString class_name("lldb.process");
454 return class_name;
455}
456
457Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
458 : Process(target_sp, listener_sp,
459 UnixSignals::Create(HostInfo::GetArchitecture())) {
460 // This constructor just delegates to the full Process constructor,
461 // defaulting to using the Host's UnixSignals.
462}
463
464Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
465 const UnixSignalsSP &unix_signals_sp)
466 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
467 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
468 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000469 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470 m_private_state(eStateUnloaded),
471 m_private_state_broadcaster(nullptr,
472 "lldb.process.internal_state_broadcaster"),
473 m_private_state_control_broadcaster(
474 nullptr, "lldb.process.internal_state_control_broadcaster"),
475 m_private_state_listener_sp(
476 Listener::MakeListener("lldb.process.internal_state_listener")),
477 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
478 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
479 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
480 m_thread_list(this), m_extended_thread_list(this),
481 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
482 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000483 m_breakpoint_site_list(), m_dynamic_checkers_up(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
485 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
486 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
487 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
488 m_memory_cache(*this), m_allocated_memory_cache(*this),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000489 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000490 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
492 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
493 m_can_interpret_function_calls(false), m_warnings_issued(),
494 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
495 CheckInWithManager();
496
497 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000498 LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499
500 if (!m_unix_signals_sp)
501 m_unix_signals_sp = std::make_shared<UnixSignals>();
502
503 SetEventName(eBroadcastBitStateChanged, "state-changed");
504 SetEventName(eBroadcastBitInterrupt, "interrupt");
505 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
506 SetEventName(eBroadcastBitSTDERR, "stderr-available");
507 SetEventName(eBroadcastBitProfileData, "profile-data-available");
508 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
509
510 m_private_state_control_broadcaster.SetEventName(
511 eBroadcastInternalStateControlStop, "control-stop");
512 m_private_state_control_broadcaster.SetEventName(
513 eBroadcastInternalStateControlPause, "control-pause");
514 m_private_state_control_broadcaster.SetEventName(
515 eBroadcastInternalStateControlResume, "control-resume");
516
517 m_listener_sp->StartListeningForEvents(
518 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
519 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
520 eBroadcastBitProfileData | eBroadcastBitStructuredData);
521
522 m_private_state_listener_sp->StartListeningForEvents(
523 &m_private_state_broadcaster,
524 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
525
526 m_private_state_listener_sp->StartListeningForEvents(
527 &m_private_state_control_broadcaster,
528 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
529 eBroadcastInternalStateControlResume);
530 // We need something valid here, even if just the default UnixSignalsSP.
531 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
532
533 // Allow the platform to override the default cache line size
534 OptionValueSP value_sp =
535 m_collection_sp
536 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
537 ->GetValue();
538 uint32_t platform_cache_line_size =
539 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
540 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
541 value_sp->SetUInt64Value(platform_cache_line_size);
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100542
543 RegisterAssertFrameRecognizer(this);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544}
545
546Process::~Process() {
547 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000548 LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549 StopPrivateStateThread();
550
551 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000552 // explicitly clear the thread list here to ensure that the mutex is not
553 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 m_thread_list.Clear();
555}
556
557const ProcessPropertiesSP &Process::GetGlobalProperties() {
558 // NOTE: intentional leak so we don't crash if global destructor chain gets
559 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000560 static ProcessPropertiesSP *g_settings_sp_ptr =
561 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 return *g_settings_sp_ptr;
563}
564
565void Process::Finalize() {
566 m_finalizing = true;
567
568 // Destroy this process if needed
569 switch (GetPrivateState()) {
570 case eStateConnected:
571 case eStateAttaching:
572 case eStateLaunching:
573 case eStateStopped:
574 case eStateRunning:
575 case eStateStepping:
576 case eStateCrashed:
577 case eStateSuspended:
578 Destroy(false);
579 break;
580
581 case eStateInvalid:
582 case eStateUnloaded:
583 case eStateDetached:
584 case eStateExited:
585 break;
586 }
587
588 // Clear our broadcaster before we proceed with destroying
589 Broadcaster::Clear();
590
Adrian Prantl05097242018-04-30 16:49:04 +0000591 // Do any cleanup needed prior to being destructed... Subclasses that
592 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000593
594 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000595 // destroyed since it is very likely that undoing the loader will require
596 // access to the real process.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000597 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000598 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000599 m_os_up.reset();
600 m_system_runtime_up.reset();
601 m_dyld_up.reset();
602 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603 m_thread_list_real.Destroy();
604 m_thread_list.Destroy();
605 m_extended_thread_list.Destroy();
606 m_queue_list.Clear();
607 m_queue_list_stop_id = 0;
608 std::vector<Notifications> empty_notifications;
609 m_notifications.swap(empty_notifications);
610 m_image_tokens.clear();
611 m_memory_cache.Clear();
612 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +0000613 {
614 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
615 m_language_runtimes.clear();
616 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 m_instrumentation_runtimes.clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000618 m_next_event_action_up.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000619 // Clear the last natural stop ID since it has a strong reference to this
620 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000621 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
622 //#ifdef LLDB_CONFIGURATION_DEBUG
623 // StreamFile s(stdout, false);
624 // EventSP event_sp;
625 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
626 // {
627 // event_sp->Dump (&s);
628 // s.EOL();
629 // }
630 //#endif
631 // We have to be very careful here as the m_private_state_listener might
632 // contain events that have ProcessSP values in them which can keep this
633 // process around forever. These events need to be cleared out.
634 m_private_state_listener_sp->Clear();
635 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
636 m_public_run_lock.SetStopped();
637 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
638 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000639 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000640 m_finalize_called = true;
641}
642
643void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
644 m_notifications.push_back(callbacks);
645 if (callbacks.initialize != nullptr)
646 callbacks.initialize(callbacks.baton, this);
647}
648
649bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
650 std::vector<Notifications>::iterator pos, end = m_notifications.end();
651 for (pos = m_notifications.begin(); pos != end; ++pos) {
652 if (pos->baton == callbacks.baton &&
653 pos->initialize == callbacks.initialize &&
654 pos->process_state_changed == callbacks.process_state_changed) {
655 m_notifications.erase(pos);
656 return true;
657 }
658 }
659 return false;
660}
661
662void Process::SynchronouslyNotifyStateChanged(StateType state) {
663 std::vector<Notifications>::iterator notification_pos,
664 notification_end = m_notifications.end();
665 for (notification_pos = m_notifications.begin();
666 notification_pos != notification_end; ++notification_pos) {
667 if (notification_pos->process_state_changed)
668 notification_pos->process_state_changed(notification_pos->baton, this,
669 state);
670 }
671}
672
673// FIXME: We need to do some work on events before the general Listener sees
674// them.
675// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000676// we do the little "insert real insn, step & stop" trick. But we can't do
677// that when the event is delivered by the broadcaster - since that is done on
678// the thread that is waiting for new events, so if we needed more than one
679// event for our handling, we would stall. So instead we do it when we fetch
680// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000681//
682
Kate Stoneb9c1b512016-09-06 20:57:50 +0000683StateType Process::GetNextEvent(EventSP &event_sp) {
684 StateType state = eStateInvalid;
685
Pavel Labathd35031e12016-11-30 10:41:42 +0000686 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
687 std::chrono::seconds(0)) &&
688 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
690
691 return state;
692}
693
Pavel Labath3879fe02018-05-09 14:29:30 +0000694void Process::SyncIOHandler(uint32_t iohandler_id,
695 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 // don't sync (potentially context switch) in case where there is no process
697 // IO
698 if (!m_process_input_reader)
699 return;
700
Pavel Labath3879fe02018-05-09 14:29:30 +0000701 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702
703 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000704 if (Result) {
705 LLDB_LOG(
706 log,
707 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
708 iohandler_id, *Result);
709 } else {
710 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
711 iohandler_id);
712 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000713}
714
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000715StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
716 EventSP *event_sp_ptr, bool wait_always,
717 ListenerSP hijack_listener_sp,
718 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000720 // have restarted the target. We have to actually check each event, and in
721 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 if (event_sp_ptr)
723 event_sp_ptr->reset();
724 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000725 // If we are exited or detached, we won't ever get back to any other valid
726 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000728 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000731 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000732
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 if (!wait_always && StateIsStoppedState(state, true) &&
734 StateIsStoppedState(GetPrivateState(), true)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000735 LLDB_LOGF(log,
736 "Process::%s returning without waiting for events; process "
737 "private and public states are already 'stopped'.",
738 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 // We need to toggle the run lock as this won't get done in
740 // SetPublicState() if the process is hijacked.
741 if (hijack_listener_sp && use_run_lock)
742 m_public_run_lock.SetStopped();
743 return state;
744 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000745
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 while (state != eStateInvalid) {
747 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000748 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749 if (event_sp_ptr && event_sp)
750 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +0000751
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
753 Process::HandleProcessStateChangedEvent(event_sp, stream,
754 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +0000755
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 switch (state) {
757 case eStateCrashed:
758 case eStateDetached:
759 case eStateExited:
760 case eStateUnloaded:
761 // We need to toggle the run lock as this won't get done in
762 // SetPublicState() if the process is hijacked.
763 if (hijack_listener_sp && use_run_lock)
764 m_public_run_lock.SetStopped();
765 return state;
766 case eStateStopped:
767 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
768 continue;
769 else {
Pavel Labath78521ef2015-03-06 10:52:47 +0000770 // We need to toggle the run lock as this won't get done in
771 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +0000772 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000773 m_public_run_lock.SetStopped();
774 return state;
775 }
776 default:
777 continue;
778 }
779 }
780 return state;
781}
782
783bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
784 Stream *stream,
785 bool &pop_process_io_handler) {
786 const bool handle_pop = pop_process_io_handler;
787
788 pop_process_io_handler = false;
789 ProcessSP process_sp =
790 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
791
792 if (!process_sp)
793 return false;
794
795 StateType event_state =
796 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
797 if (event_state == eStateInvalid)
798 return false;
799
800 switch (event_state) {
801 case eStateInvalid:
802 case eStateUnloaded:
803 case eStateAttaching:
804 case eStateLaunching:
805 case eStateStepping:
806 case eStateDetached:
807 if (stream)
808 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
809 StateAsCString(event_state));
810 if (event_state == eStateDetached)
811 pop_process_io_handler = true;
812 break;
813
814 case eStateConnected:
815 case eStateRunning:
816 // Don't be chatty when we run...
817 break;
818
819 case eStateExited:
820 if (stream)
821 process_sp->GetStatus(*stream);
822 pop_process_io_handler = true;
823 break;
824
825 case eStateStopped:
826 case eStateCrashed:
827 case eStateSuspended:
828 // Make sure the program hasn't been auto-restarted:
829 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
830 if (stream) {
831 size_t num_reasons =
832 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
833 if (num_reasons > 0) {
834 // FIXME: Do we want to report this, or would that just be annoyingly
835 // chatty?
836 if (num_reasons == 1) {
837 const char *reason =
838 Process::ProcessEventData::GetRestartedReasonAtIndex(
839 event_sp.get(), 0);
840 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
841 process_sp->GetID(),
842 reason ? reason : "<UNKNOWN REASON>");
843 } else {
844 stream->Printf("Process %" PRIu64
845 " stopped and restarted, reasons:\n",
846 process_sp->GetID());
847
848 for (size_t i = 0; i < num_reasons; i++) {
849 const char *reason =
850 Process::ProcessEventData::GetRestartedReasonAtIndex(
851 event_sp.get(), i);
852 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
853 }
854 }
855 }
856 }
857 } else {
858 StopInfoSP curr_thread_stop_info_sp;
859 // Lock the thread list so it doesn't change on us, this is the scope for
860 // the locker:
861 {
862 ThreadList &thread_list = process_sp->GetThreadList();
863 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
864
865 ThreadSP curr_thread(thread_list.GetSelectedThread());
866 ThreadSP thread;
867 StopReason curr_thread_stop_reason = eStopReasonInvalid;
868 if (curr_thread) {
869 curr_thread_stop_reason = curr_thread->GetStopReason();
870 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
871 }
872 if (!curr_thread || !curr_thread->IsValid() ||
873 curr_thread_stop_reason == eStopReasonInvalid ||
874 curr_thread_stop_reason == eStopReasonNone) {
875 // Prefer a thread that has just completed its plan over another
876 // thread as current thread.
877 ThreadSP plan_thread;
878 ThreadSP other_thread;
879
880 const size_t num_threads = thread_list.GetSize();
881 size_t i;
882 for (i = 0; i < num_threads; ++i) {
883 thread = thread_list.GetThreadAtIndex(i);
884 StopReason thread_stop_reason = thread->GetStopReason();
885 switch (thread_stop_reason) {
886 case eStopReasonInvalid:
887 case eStopReasonNone:
888 break;
889
890 case eStopReasonSignal: {
891 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +0000892 // that signal. We have to have had another reason for stopping
893 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894 uint64_t signo = thread->GetStopInfo()->GetValue();
895 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
896 if (!other_thread)
897 other_thread = thread;
898 }
899 break;
900 }
901 case eStopReasonTrace:
902 case eStopReasonBreakpoint:
903 case eStopReasonWatchpoint:
904 case eStopReasonException:
905 case eStopReasonExec:
906 case eStopReasonThreadExiting:
907 case eStopReasonInstrumentation:
908 if (!other_thread)
909 other_thread = thread;
910 break;
911 case eStopReasonPlanComplete:
912 if (!plan_thread)
913 plan_thread = thread;
914 break;
915 }
916 }
917 if (plan_thread)
918 thread_list.SetSelectedThreadByID(plan_thread->GetID());
919 else if (other_thread)
920 thread_list.SetSelectedThreadByID(other_thread->GetID());
921 else {
922 if (curr_thread && curr_thread->IsValid())
923 thread = curr_thread;
924 else
925 thread = thread_list.GetThreadAtIndex(0);
926
927 if (thread)
928 thread_list.SetSelectedThreadByID(thread->GetID());
929 }
930 }
931 }
932 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +0000933 // have to run code, e.g. for Data formatters, and if we hold the
934 // ThreadList mutex, then the process is going to have a hard time
935 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000936 if (stream) {
937 Debugger &debugger = process_sp->GetTarget().GetDebugger();
938 if (debugger.GetTargetList().GetSelectedTarget().get() ==
939 &process_sp->GetTarget()) {
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100940 ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
941
942 if (!thread_sp || !thread_sp->IsValid())
943 return false;
944
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 const bool only_threads_with_stop_reason = true;
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100946 const uint32_t start_frame = thread_sp->GetSelectedFrameIndex();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947 const uint32_t num_frames = 1;
948 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +0000949 const bool stop_format = true;
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100950
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 process_sp->GetStatus(*stream);
952 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
953 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000954 num_frames_with_source,
955 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956 if (curr_thread_stop_info_sp) {
957 lldb::addr_t crashing_address;
958 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
959 curr_thread_stop_info_sp, &crashing_address);
960 if (valobj_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 const ValueObject::GetExpressionPathFormat format =
962 ValueObject::GetExpressionPathFormat::
963 eGetExpressionPathFormatHonorPointers;
964 stream->PutCString("Likely cause: ");
Alex Langford3014efe2020-02-02 14:17:02 -0800965 valobj_sp->GetExpressionPath(*stream, format);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
967 }
968 }
969 } else {
970 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
971 process_sp->GetTarget().shared_from_this());
972 if (target_idx != UINT32_MAX)
973 stream->Printf("Target %d: (", target_idx);
974 else
975 stream->Printf("Target <unknown index>: (");
976 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
977 stream->Printf(") stopped.\n");
978 }
979 }
980
981 // Pop the process IO handler
982 pop_process_io_handler = true;
983 }
984 break;
985 }
986
987 if (handle_pop && pop_process_io_handler)
988 process_sp->PopProcessIOHandler();
989
990 return true;
991}
992
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993bool Process::HijackProcessEvents(ListenerSP listener_sp) {
994 if (listener_sp) {
995 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
996 eBroadcastBitInterrupt);
997 } else
998 return false;
999}
Greg Claytondc6224e2014-10-21 01:00:42 +00001000
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001002
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001003StateType Process::GetStateChangedEvents(EventSP &event_sp,
1004 const Timeout<std::micro> &timeout,
1005 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001007 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001008
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 ListenerSP listener_sp = hijack_listener_sp;
1010 if (!listener_sp)
1011 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001012
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001014 if (listener_sp->GetEventForBroadcasterWithType(
1015 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001016 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1018 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001019 else
1020 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001022
Pavel Labathd02b1c82017-02-10 11:49:33 +00001023 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024 return state;
1025}
Greg Claytondc6224e2014-10-21 01:00:42 +00001026
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027Event *Process::PeekAtStateChangedEvents() {
1028 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001029
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001030 LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001031
Kate Stoneb9c1b512016-09-06 20:57:50 +00001032 Event *event_ptr;
1033 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1034 this, eBroadcastBitStateChanged);
1035 if (log) {
1036 if (event_ptr) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001037 LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
1038 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001039 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001040 LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001041 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042 }
1043 return event_ptr;
1044}
Greg Claytondc6224e2014-10-21 01:00:42 +00001045
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001046StateType
1047Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1048 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001050 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051
1052 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001053 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1054 &m_private_state_broadcaster,
1055 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001056 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1058 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1059
Pavel Labathd02b1c82017-02-10 11:49:33 +00001060 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1061 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062 return state;
1063}
1064
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001065bool Process::GetEventsPrivate(EventSP &event_sp,
1066 const Timeout<std::micro> &timeout,
1067 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001069 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070
1071 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001072 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001073 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001075 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076}
1077
1078bool Process::IsRunning() const {
1079 return StateIsRunningState(m_public_state.GetValue());
1080}
1081
1082int Process::GetExitStatus() {
1083 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1084
1085 if (m_public_state.GetValue() == eStateExited)
1086 return m_exit_status;
1087 return -1;
1088}
1089
1090const char *Process::GetExitDescription() {
1091 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1092
1093 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1094 return m_exit_string.c_str();
1095 return nullptr;
1096}
1097
1098bool Process::SetExitStatus(int status, const char *cstr) {
1099 // Use a mutex to protect setting the exit status.
1100 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1101
1102 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1103 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001104 LLDB_LOGF(
1105 log, "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1106 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", cstr ? "\"" : "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001107
1108 // We were already in the exited state
1109 if (m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001110 LLDB_LOGF(log, "Process::SetExitStatus () ignoring exit status because "
1111 "state was already set to eStateExited");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112 return false;
1113 }
1114
1115 m_exit_status = status;
1116 if (cstr)
1117 m_exit_string = cstr;
1118 else
1119 m_exit_string.clear();
1120
Adrian Prantl05097242018-04-30 16:49:04 +00001121 // Clear the last natural stop ID since it has a strong reference to this
1122 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1124
1125 SetPrivateState(eStateExited);
1126
1127 // Allow subclasses to do some cleanup
1128 DidExit();
1129
1130 return true;
1131}
1132
1133bool Process::IsAlive() {
1134 switch (m_private_state.GetValue()) {
1135 case eStateConnected:
1136 case eStateAttaching:
1137 case eStateLaunching:
1138 case eStateStopped:
1139 case eStateRunning:
1140 case eStateStepping:
1141 case eStateCrashed:
1142 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001143 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144 default:
1145 return false;
1146 }
Jason Molendaa814f702015-11-05 23:03:44 +00001147}
1148
Adrian Prantl05097242018-04-30 16:49:04 +00001149// This static callback can be used to watch for local child processes on the
1150// current host. The child process exits, the process will be found in the
1151// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001152// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153bool Process::SetProcessExitStatus(
1154 lldb::pid_t pid, bool exited,
1155 int signo, // Zero for no signal
1156 int exit_status // Exit value of process if signal is zero
1157 ) {
1158 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001159 LLDB_LOGF(log,
1160 "Process::SetProcessExitStatus (pid=%" PRIu64
1161 ", exited=%i, signal=%i, exit_status=%i)\n",
1162 pid, exited, signo, exit_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163
1164 if (exited) {
1165 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1166 if (target_sp) {
1167 ProcessSP process_sp(target_sp->GetProcessSP());
1168 if (process_sp) {
1169 const char *signal_cstr = nullptr;
1170 if (signo)
1171 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1172
1173 process_sp->SetExitStatus(exit_status, signal_cstr);
1174 }
1175 }
1176 return true;
1177 }
1178 return false;
1179}
1180
1181void Process::UpdateThreadListIfNeeded() {
1182 const uint32_t stop_id = GetStopID();
1183 if (m_thread_list.GetSize(false) == 0 ||
1184 stop_id != m_thread_list.GetStopID()) {
1185 const StateType state = GetPrivateState();
1186 if (StateIsStoppedState(state, true)) {
1187 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Adrian Prantl05097242018-04-30 16:49:04 +00001188 // m_thread_list does have its own mutex, but we need to hold onto the
1189 // mutex between the call to UpdateThreadList(...) and the
1190 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001191 ThreadList &old_thread_list = m_thread_list;
1192 ThreadList real_thread_list(this);
1193 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001194 // Always update the thread list with the protocol specific thread list,
1195 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001196 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1197 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001198 // are shutting down, since that may call back into the SBAPI's,
1199 // requiring the API lock which is already held by whoever is shutting
1200 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 OperatingSystem *os = GetOperatingSystem();
1202 if (os && !m_destroy_in_process) {
1203 // Clear any old backing threads where memory threads might have been
1204 // backed by actual threads from the lldb_private::Process subclass
1205 size_t num_old_threads = old_thread_list.GetSize(false);
1206 for (size_t i = 0; i < num_old_threads; ++i)
1207 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1208
1209 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001210 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001211 // dynamic type or not and we need to avoid this. OperatingSystem
1212 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213
1214 Target &target = GetTarget();
1215 const lldb::DynamicValueType saved_prefer_dynamic =
1216 target.GetPreferDynamicValue();
1217 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1218 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1219
1220 // Now let the OperatingSystem plug-in update the thread list
1221
1222 os->UpdateThreadList(
1223 old_thread_list, // Old list full of threads created by OS plug-in
1224 real_thread_list, // The actual thread list full of threads
1225 // created by each lldb_private::Process
1226 // subclass
1227 new_thread_list); // The new thread list that we will show to the
1228 // user that gets filled in
1229
1230 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1231 target.SetPreferDynamicValue(saved_prefer_dynamic);
1232 } else {
1233 // No OS plug-in, the new thread list is the same as the real thread
1234 // list
1235 new_thread_list = real_thread_list;
1236 }
1237
1238 m_thread_list_real.Update(real_thread_list);
1239 m_thread_list.Update(new_thread_list);
1240 m_thread_list.SetStopID(stop_id);
1241
1242 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1243 // Clear any extended threads that we may have accumulated previously
1244 m_extended_thread_list.Clear();
1245 m_extended_thread_stop_id = GetLastNaturalStopID();
1246
1247 m_queue_list.Clear();
1248 m_queue_list_stop_id = GetLastNaturalStopID();
1249 }
1250 }
1251 }
1252 }
1253}
1254
1255void Process::UpdateQueueListIfNeeded() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001256 if (m_system_runtime_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 if (m_queue_list.GetSize() == 0 ||
1258 m_queue_list_stop_id != GetLastNaturalStopID()) {
1259 const StateType state = GetPrivateState();
1260 if (StateIsStoppedState(state, true)) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001261 m_system_runtime_up->PopulateQueueList(m_queue_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 m_queue_list_stop_id = GetLastNaturalStopID();
1263 }
1264 }
1265 }
1266}
1267
1268ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1269 OperatingSystem *os = GetOperatingSystem();
1270 if (os)
1271 return os->CreateThread(tid, context);
1272 return ThreadSP();
1273}
1274
1275uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1276 return AssignIndexIDToThread(thread_id);
1277}
1278
1279bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1280 return (m_thread_id_to_index_id_map.find(thread_id) !=
1281 m_thread_id_to_index_id_map.end());
1282}
1283
1284uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1285 uint32_t result = 0;
1286 std::map<uint64_t, uint32_t>::iterator iterator =
1287 m_thread_id_to_index_id_map.find(thread_id);
1288 if (iterator == m_thread_id_to_index_id_map.end()) {
1289 result = ++m_thread_index_id;
1290 m_thread_id_to_index_id_map[thread_id] = result;
1291 } else {
1292 result = iterator->second;
1293 }
1294
1295 return result;
1296}
1297
1298StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 return m_public_state.GetValue();
1300}
1301
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302void Process::SetPublicState(StateType new_state, bool restarted) {
1303 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1304 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001305 LLDB_LOGF(log, "Process::SetPublicState (state = %s, restarted = %i)",
1306 StateAsCString(new_state), restarted);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307 const StateType old_state = m_public_state.GetValue();
1308 m_public_state.SetValue(new_state);
1309
Adrian Prantl05097242018-04-30 16:49:04 +00001310 // On the transition from Run to Stopped, we unlock the writer end of the run
1311 // lock. The lock gets locked in Resume, which is the public API to tell the
1312 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313 if (!StateChangedIsExternallyHijacked()) {
1314 if (new_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001315 LLDB_LOGF(log,
1316 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1317 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001318 m_public_run_lock.SetStopped();
1319 } else {
1320 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1321 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1322 if ((old_state_is_stopped != new_state_is_stopped)) {
1323 if (new_state_is_stopped && !restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001324 LLDB_LOGF(log, "Process::SetPublicState (%s) -- unlocking run lock",
1325 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326 m_public_run_lock.SetStopped();
1327 }
1328 }
1329 }
1330 }
1331}
1332
Zachary Turner97206d52017-05-12 04:51:55 +00001333Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001334 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1335 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001336 LLDB_LOGF(log, "Process::Resume -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001337 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001338 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001339 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001340 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001341 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001342 Status error = PrivateResume();
1343 if (!error.Success()) {
1344 // Undo running state change
1345 m_public_run_lock.SetStopped();
1346 }
1347 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001348}
1349
Jim Ingham3139fc92019-03-01 18:13:38 +00001350static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1351
Zachary Turner97206d52017-05-12 04:51:55 +00001352Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001353 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1354 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001355 LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001357 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001358 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001359 return error;
1360 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001361
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 ListenerSP listener_sp(
Jim Ingham3139fc92019-03-01 18:13:38 +00001363 Listener::MakeListener(g_resume_sync_name));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001364 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001365
Zachary Turner97206d52017-05-12 04:51:55 +00001366 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001367 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001368 StateType state =
Konrad Kleine248a1302019-05-23 11:14:47 +00001369 WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001370 const bool must_be_alive =
1371 false; // eStateExited is ok, so this must be false
1372 if (!StateIsStoppedState(state, must_be_alive))
1373 error.SetErrorStringWithFormat(
1374 "process not in stopped state after synchronous resume: %s",
1375 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001376 } else {
1377 // Undo running state change
1378 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001379 }
Ed Mastec29693f2013-07-02 16:35:47 +00001380
Kate Stoneb9c1b512016-09-06 20:57:50 +00001381 // Undo the hijacking of process events...
1382 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001383
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384 return error;
1385}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001386
Jim Ingham3139fc92019-03-01 18:13:38 +00001387bool Process::StateChangedIsExternallyHijacked() {
1388 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1389 const char *hijacking_name = GetHijackingListenerName();
1390 if (hijacking_name &&
1391 strcmp(hijacking_name, g_resume_sync_name))
1392 return true;
1393 }
1394 return false;
1395}
1396
1397bool Process::StateChangedIsHijackedForSynchronousResume() {
1398 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1399 const char *hijacking_name = GetHijackingListenerName();
1400 if (hijacking_name &&
1401 strcmp(hijacking_name, g_resume_sync_name) == 0)
1402 return true;
1403 }
1404 return false;
1405}
1406
Kate Stoneb9c1b512016-09-06 20:57:50 +00001407StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001408
Kate Stoneb9c1b512016-09-06 20:57:50 +00001409void Process::SetPrivateState(StateType new_state) {
1410 if (m_finalize_called)
1411 return;
1412
1413 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1414 LIBLLDB_LOG_PROCESS));
1415 bool state_changed = false;
1416
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001417 LLDB_LOGF(log, "Process::SetPrivateState (%s)", StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001418
1419 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1420 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1421
1422 const StateType old_state = m_private_state.GetValueNoLock();
1423 state_changed = old_state != new_state;
1424
1425 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1426 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1427 if (old_state_is_stopped != new_state_is_stopped) {
1428 if (new_state_is_stopped)
1429 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001430 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001431 m_private_run_lock.SetRunning();
1432 }
1433
1434 if (state_changed) {
1435 m_private_state.SetValueNoLock(new_state);
1436 EventSP event_sp(
1437 new Event(eBroadcastBitStateChanged,
1438 new ProcessEventData(shared_from_this(), new_state)));
1439 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001440 // Note, this currently assumes that all threads in the list stop when
1441 // the process stops. In the future we will want to support a debugging
1442 // model where some threads continue to run while others are stopped.
1443 // When that happens we will either need a way for the thread list to
1444 // identify which threads are stopping or create a special thread list
1445 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446 //
Adrian Prantl05097242018-04-30 16:49:04 +00001447 // The process plugin is responsible for managing the actual behavior of
1448 // the threads and should have stopped any threads that are going to stop
1449 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450 m_thread_list.DidStop();
1451
1452 m_mod_id.BumpStopID();
1453 if (!m_mod_id.IsLastResumeForUserExpression())
1454 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1455 m_memory_cache.Clear();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001456 LLDB_LOGF(log, "Process::SetPrivateState (%s) stop_id = %u",
1457 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001458 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001459
Kate Stoneb9c1b512016-09-06 20:57:50 +00001460 // Use our target to get a shared pointer to ourselves...
1461 if (m_finalize_called && !PrivateStateThreadIsValid())
1462 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001463 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464 m_private_state_broadcaster.BroadcastEvent(event_sp);
1465 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001466 LLDB_LOGF(log,
1467 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1468 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001469 }
Jim Ingham22777012010-09-23 02:01:19 +00001470}
1471
Kate Stoneb9c1b512016-09-06 20:57:50 +00001472void Process::SetRunningUserExpression(bool on) {
1473 m_mod_id.SetRunningUserExpression(on);
1474}
1475
Raphael Isemannc01783a2018-08-29 22:50:54 +00001476void Process::SetRunningUtilityFunction(bool on) {
1477 m_mod_id.SetRunningUtilityFunction(on);
1478}
1479
Kate Stoneb9c1b512016-09-06 20:57:50 +00001480addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1481
1482const lldb::ABISP &Process::GetABI() {
1483 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001484 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001485 return m_abi_sp;
1486}
1487
Davide Italianocec82632019-12-03 16:54:04 -08001488std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
Alex Langford03e1a822019-05-29 18:08:22 +00001489 std::vector<LanguageRuntime *> language_runtimes;
1490
1491 if (m_finalizing)
1492 return language_runtimes;
1493
1494 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1495 // Before we pass off a copy of the language runtimes, we must make sure that
1496 // our collection is properly populated. It's possible that some of the
1497 // language runtimes were not loaded yet, either because nobody requested it
1498 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1499 // hadn't been loaded).
1500 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
Davide Italianocec82632019-12-03 16:54:04 -08001501 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
Alex Langford03e1a822019-05-29 18:08:22 +00001502 language_runtimes.emplace_back(runtime);
1503 }
1504
1505 return language_runtimes;
1506}
1507
Davide Italianocec82632019-12-03 16:54:04 -08001508LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001509 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001510 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001511
Alex Langford7d3e97f2019-05-29 21:07:53 +00001512 LanguageRuntime *runtime = nullptr;
1513
Alex Langford74eb76f2019-05-22 23:01:18 +00001514 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001515 LanguageRuntimeCollection::iterator pos;
1516 pos = m_language_runtimes.find(language);
Davide Italianocec82632019-12-03 16:54:04 -08001517 if (pos == m_language_runtimes.end() || !pos->second) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001518 lldb::LanguageRuntimeSP runtime_sp(
1519 LanguageRuntime::FindPlugin(this, language));
1520
1521 m_language_runtimes[language] = runtime_sp;
Alex Langford7d3e97f2019-05-29 21:07:53 +00001522 runtime = runtime_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001523 } else
Alex Langford7d3e97f2019-05-29 21:07:53 +00001524 runtime = pos->second.get();
1525
1526 if (runtime)
1527 // It's possible that a language runtime can support multiple LanguageTypes,
1528 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1529 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1530 // primary language type and make sure that our runtime supports it.
1531 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1532
1533 return runtime;
Jim Ingham22777012010-09-23 02:01:19 +00001534}
1535
Kate Stoneb9c1b512016-09-06 20:57:50 +00001536bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1537 if (m_finalizing)
1538 return false;
1539
1540 if (in_value.IsDynamic())
1541 return false;
1542 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1543
1544 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1545 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1546 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1547 }
1548
Alex Langford41dc5522019-05-30 21:03:53 +00001549 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1550 if (runtime->CouldHaveDynamicValue(in_value))
1551 return true;
1552 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553
Alex Langford41dc5522019-05-30 21:03:53 +00001554 return false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001555}
1556
Kate Stoneb9c1b512016-09-06 20:57:50 +00001557void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001558 m_dynamic_checkers_up.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001559}
1560
Kate Stoneb9c1b512016-09-06 20:57:50 +00001561BreakpointSiteList &Process::GetBreakpointSiteList() {
1562 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001563}
1564
Kate Stoneb9c1b512016-09-06 20:57:50 +00001565const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1566 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001567}
1568
Kate Stoneb9c1b512016-09-06 20:57:50 +00001569void Process::DisableAllBreakpointSites() {
1570 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1571 // bp_site->SetEnabled(true);
1572 DisableBreakpointSite(bp_site);
1573 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001574}
1575
Zachary Turner97206d52017-05-12 04:51:55 +00001576Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1577 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001578
Kate Stoneb9c1b512016-09-06 20:57:50 +00001579 if (error.Success())
1580 m_breakpoint_site_list.Remove(break_id);
1581
1582 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001583}
1584
Zachary Turner97206d52017-05-12 04:51:55 +00001585Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1586 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001587 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1588 if (bp_site_sp) {
1589 if (bp_site_sp->IsEnabled())
1590 error = DisableBreakpointSite(bp_site_sp.get());
1591 } else {
1592 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1593 break_id);
1594 }
1595
1596 return error;
1597}
1598
Zachary Turner97206d52017-05-12 04:51:55 +00001599Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1600 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001601 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1602 if (bp_site_sp) {
1603 if (!bp_site_sp->IsEnabled())
1604 error = EnableBreakpointSite(bp_site_sp.get());
1605 } else {
1606 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1607 break_id);
1608 }
1609 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001610}
1611
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001612lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001613Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1614 bool use_hardware) {
1615 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001616
Kate Stoneb9c1b512016-09-06 20:57:50 +00001617 bool show_error = true;
1618 switch (GetState()) {
1619 case eStateInvalid:
1620 case eStateUnloaded:
1621 case eStateConnected:
1622 case eStateAttaching:
1623 case eStateLaunching:
1624 case eStateDetached:
1625 case eStateExited:
1626 show_error = false;
1627 break;
1628
1629 case eStateStopped:
1630 case eStateRunning:
1631 case eStateStepping:
1632 case eStateCrashed:
1633 case eStateSuspended:
1634 show_error = IsAlive();
1635 break;
1636 }
1637
Adrian Prantl05097242018-04-30 16:49:04 +00001638 // Reset the IsIndirect flag here, in case the location changes from pointing
1639 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001640 owner->SetIsIndirect(false);
1641
1642 if (owner->ShouldResolveIndirectFunctions()) {
1643 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1644 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001645 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646 Address symbol_address = symbol->GetAddress();
1647 load_addr = ResolveIndirectFunction(&symbol_address, error);
1648 if (!error.Success() && show_error) {
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001649 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001650 "warning: failed to resolve indirect function at 0x%" PRIx64
1651 " for breakpoint %i.%i: %s\n",
1652 symbol->GetLoadAddress(&GetTarget()),
1653 owner->GetBreakpoint().GetID(), owner->GetID(),
1654 error.AsCString() ? error.AsCString() : "unknown error");
1655 return LLDB_INVALID_BREAK_ID;
1656 }
1657 Address resolved_address(load_addr);
1658 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1659 owner->SetIsIndirect(true);
1660 } else
1661 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1662 } else
1663 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1664
1665 if (load_addr != LLDB_INVALID_ADDRESS) {
1666 BreakpointSiteSP bp_site_sp;
1667
1668 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001669 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001670
1671 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1672
1673 if (bp_site_sp) {
1674 bp_site_sp->AddOwner(owner);
1675 owner->SetBreakpointSite(bp_site_sp);
1676 return bp_site_sp->GetID();
1677 } else {
1678 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1679 load_addr, use_hardware));
1680 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001681 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001682 if (error.Success()) {
1683 owner->SetBreakpointSite(bp_site_sp);
1684 return m_breakpoint_site_list.Add(bp_site_sp);
1685 } else {
Jonas Devliegheree103ae92018-11-15 01:18:15 +00001686 if (show_error || use_hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001687 // Report error for setting breakpoint...
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001688 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 "warning: failed to set breakpoint site at 0x%" PRIx64
1690 " for breakpoint %i.%i: %s\n",
1691 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1692 error.AsCString() ? error.AsCString() : "unknown error");
1693 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001694 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001695 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001696 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001697 }
1698 // We failed to enable the breakpoint
1699 return LLDB_INVALID_BREAK_ID;
1700}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001701
Kate Stoneb9c1b512016-09-06 20:57:50 +00001702void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1703 lldb::user_id_t owner_loc_id,
1704 BreakpointSiteSP &bp_site_sp) {
1705 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1706 if (num_owners == 0) {
1707 // Don't try to disable the site if we don't have a live process anymore.
1708 if (IsAlive())
1709 DisableBreakpointSite(bp_site_sp.get());
1710 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1711 }
1712}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001713
Kate Stoneb9c1b512016-09-06 20:57:50 +00001714size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1715 uint8_t *buf) const {
1716 size_t bytes_removed = 0;
1717 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001718
Kate Stoneb9c1b512016-09-06 20:57:50 +00001719 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1720 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001721 bp_sites_in_range.ForEach([bp_addr, size,
1722 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001723 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1724 addr_t intersect_addr;
1725 size_t intersect_size;
1726 size_t opcode_offset;
1727 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1728 &intersect_size, &opcode_offset)) {
1729 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1730 assert(bp_addr < intersect_addr + intersect_size &&
1731 intersect_addr + intersect_size <= bp_addr + size);
1732 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1733 size_t buf_offset = intersect_addr - bp_addr;
1734 ::memcpy(buf + buf_offset,
1735 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1736 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001737 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001738 }
1739 });
1740 }
1741 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001742}
1743
Kate Stoneb9c1b512016-09-06 20:57:50 +00001744size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1745 PlatformSP platform_sp(GetTarget().GetPlatform());
1746 if (platform_sp)
1747 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1748 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001749}
1750
Zachary Turner97206d52017-05-12 04:51:55 +00001751Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1752 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001753 assert(bp_site != nullptr);
1754 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1755 const addr_t bp_addr = bp_site->GetLoadAddress();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001756 LLDB_LOGF(
1757 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1758 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001759 if (bp_site->IsEnabled()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001760 LLDB_LOGF(
1761 log,
1762 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1763 " -- already enabled",
1764 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001765 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001766 }
1767
1768 if (bp_addr == LLDB_INVALID_ADDRESS) {
1769 error.SetErrorString("BreakpointSite contains an invalid load address.");
1770 return error;
1771 }
1772 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1773 // trap for the breakpoint site
1774 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1775
1776 if (bp_opcode_size == 0) {
1777 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1778 "returned zero, unable to get breakpoint "
1779 "trap for address 0x%" PRIx64,
1780 bp_addr);
1781 } else {
1782 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1783
1784 if (bp_opcode_bytes == nullptr) {
1785 error.SetErrorString(
1786 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1787 return error;
1788 }
1789
1790 // Save the original opcode by reading it
1791 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1792 error) == bp_opcode_size) {
1793 // Write a software breakpoint in place of the original opcode
1794 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1795 bp_opcode_size) {
1796 uint8_t verify_bp_opcode_bytes[64];
1797 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1798 error) == bp_opcode_size) {
1799 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1800 bp_opcode_size) == 0) {
1801 bp_site->SetEnabled(true);
1802 bp_site->SetType(BreakpointSite::eSoftware);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001803 LLDB_LOGF(log,
1804 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1805 "addr = 0x%" PRIx64 " -- SUCCESS",
1806 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001807 } else
1808 error.SetErrorString(
1809 "failed to verify the breakpoint trap in memory.");
1810 } else
1811 error.SetErrorString(
1812 "Unable to read memory to verify breakpoint trap.");
1813 } else
1814 error.SetErrorString("Unable to write breakpoint trap to memory.");
1815 } else
1816 error.SetErrorString("Unable to read memory at breakpoint address.");
1817 }
1818 if (log && error.Fail())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001819 LLDB_LOGF(
1820 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001821 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1822 " -- FAILED: %s",
1823 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1824 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001825}
1826
Zachary Turner97206d52017-05-12 04:51:55 +00001827Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1828 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001829 assert(bp_site != nullptr);
1830 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1831 addr_t bp_addr = bp_site->GetLoadAddress();
1832 lldb::user_id_t breakID = bp_site->GetID();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001833 LLDB_LOGF(log,
1834 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1835 ") addr = 0x%" PRIx64,
1836 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837
Kate Stoneb9c1b512016-09-06 20:57:50 +00001838 if (bp_site->IsHardware()) {
1839 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1840 } else if (bp_site->IsEnabled()) {
1841 const size_t break_op_size = bp_site->GetByteSize();
1842 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1843 if (break_op_size > 0) {
1844 // Clear a software breakpoint instruction
1845 uint8_t curr_break_op[8];
1846 assert(break_op_size <= sizeof(curr_break_op));
1847 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001848
Kate Stoneb9c1b512016-09-06 20:57:50 +00001849 // Read the breakpoint opcode
1850 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1851 break_op_size) {
1852 bool verify = false;
1853 // Make sure the breakpoint opcode exists at this address
1854 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1855 break_op_found = true;
1856 // We found a valid breakpoint opcode at this address, now restore
1857 // the saved opcode.
1858 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1859 break_op_size, error) == break_op_size) {
1860 verify = true;
1861 } else
1862 error.SetErrorString(
1863 "Memory write failed when restoring original opcode.");
1864 } else {
1865 error.SetErrorString(
1866 "Original breakpoint trap is no longer in memory.");
1867 // Set verify to true and so we can check if the original opcode has
1868 // already been restored
1869 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001870 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001871
Kate Stoneb9c1b512016-09-06 20:57:50 +00001872 if (verify) {
1873 uint8_t verify_opcode[8];
1874 assert(break_op_size < sizeof(verify_opcode));
1875 // Verify that our original opcode made it back to the inferior
1876 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1877 break_op_size) {
1878 // compare the memory we just read with the original opcode
1879 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1880 break_op_size) == 0) {
1881 // SUCCESS
1882 bp_site->SetEnabled(false);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001883 LLDB_LOGF(log,
1884 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1885 "addr = 0x%" PRIx64 " -- SUCCESS",
1886 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001887 return error;
1888 } else {
1889 if (break_op_found)
1890 error.SetErrorString("Failed to restore original opcode.");
1891 }
1892 } else
1893 error.SetErrorString("Failed to read memory to verify that "
1894 "breakpoint trap was restored.");
1895 }
1896 } else
1897 error.SetErrorString(
1898 "Unable to read memory that should contain the breakpoint trap.");
1899 }
1900 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001901 LLDB_LOGF(
1902 log,
1903 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1904 " -- already disabled",
1905 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001906 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001907 }
1908
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001909 LLDB_LOGF(
1910 log,
1911 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1912 " -- FAILED: %s",
1913 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001914 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001915}
1916
Adrian Prantl05097242018-04-30 16:49:04 +00001917// Uncomment to verify memory caching works after making changes to caching
1918// code
Greg Clayton58be07b2011-01-07 06:08:19 +00001919//#define VERIFY_MEMORY_READS
1920
Zachary Turner97206d52017-05-12 04:51:55 +00001921size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001922 error.Clear();
1923 if (!GetDisableMemoryCache()) {
1924#if defined(VERIFY_MEMORY_READS)
1925 // Memory caching is enabled, with debug verification
1926
1927 if (buf && size) {
1928 // Uncomment the line below to make sure memory caching is working.
1929 // I ran this through the test suite and got no assertions, so I am
1930 // pretty confident this is working well. If any changes are made to
1931 // memory caching, uncomment the line below and test your changes!
1932
1933 // Verify all memory reads by using the cache first, then redundantly
1934 // reading the same memory from the inferior and comparing to make sure
1935 // everything is exactly the same.
1936 std::string verify_buf(size, '\0');
1937 assert(verify_buf.size() == size);
1938 const size_t cache_bytes_read =
1939 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00001940 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001941 const size_t verify_bytes_read =
1942 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1943 verify_buf.size(), verify_error);
1944 assert(cache_bytes_read == verify_bytes_read);
1945 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1946 assert(verify_error.Success() == error.Success());
1947 return cache_bytes_read;
1948 }
1949 return 0;
1950#else // !defined(VERIFY_MEMORY_READS)
1951 // Memory caching is enabled, without debug verification
1952
1953 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00001954#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 } else {
1956 // Memory caching is disabled
1957
1958 return ReadMemoryFromInferior(addr, buf, size, error);
1959 }
Greg Clayton58be07b2011-01-07 06:08:19 +00001960}
Kate Stoneb9c1b512016-09-06 20:57:50 +00001961
1962size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00001963 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001964 char buf[256];
1965 out_str.clear();
1966 addr_t curr_addr = addr;
1967 while (true) {
1968 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
1969 if (length == 0)
1970 break;
1971 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00001972 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1973 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00001974 if (length == sizeof(buf) - 1)
1975 curr_addr += length;
1976 else
1977 break;
1978 }
1979 return out_str.size();
1980}
1981
1982size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00001983 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984 size_t total_bytes_read = 0;
1985 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00001986 // Ensure a null terminator independent of the number of bytes that is
1987 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001988 memset(dst, 0, max_bytes);
1989 size_t bytes_left = max_bytes - type_width;
1990
1991 const char terminator[4] = {'\0', '\0', '\0', '\0'};
1992 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
1993 "string with more than 4 bytes "
1994 "per character!");
1995
Greg Clayton4c82d422012-05-18 23:20:01 +00001996 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001997 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1998 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00001999
Kate Stoneb9c1b512016-09-06 20:57:50 +00002000 error.Clear();
2001 while (bytes_left > 0 && error.Success()) {
2002 addr_t cache_line_bytes_left =
2003 cache_line_size - (curr_addr % cache_line_size);
2004 addr_t bytes_to_read =
2005 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2006 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002007
Kate Stoneb9c1b512016-09-06 20:57:50 +00002008 if (bytes_read == 0)
2009 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002010
Kate Stoneb9c1b512016-09-06 20:57:50 +00002011 // Search for a null terminator of correct size and alignment in
2012 // bytes_read
2013 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2014 for (size_t i = aligned_start;
2015 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2016 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2017 error.Clear();
2018 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002019 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002020
2021 total_bytes_read += bytes_read;
2022 curr_dst += bytes_read;
2023 curr_addr += bytes_read;
2024 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002025 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002026 } else {
2027 if (max_bytes)
2028 error.SetErrorString("invalid arguments");
2029 }
2030 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002031}
2032
Kate Stoneb9c1b512016-09-06 20:57:50 +00002033// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002034// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002035size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002036 size_t dst_max_len,
2037 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002038 size_t total_cstr_len = 0;
2039 if (dst && dst_max_len) {
2040 result_error.Clear();
2041 // NULL out everything just to be safe
2042 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002043 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002044 addr_t curr_addr = addr;
2045 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2046 size_t bytes_left = dst_max_len - 1;
2047 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002048
Kate Stoneb9c1b512016-09-06 20:57:50 +00002049 while (bytes_left > 0) {
2050 addr_t cache_line_bytes_left =
2051 cache_line_size - (curr_addr % cache_line_size);
2052 addr_t bytes_to_read =
2053 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2054 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002055
Kate Stoneb9c1b512016-09-06 20:57:50 +00002056 if (bytes_read == 0) {
2057 result_error = error;
2058 dst[total_cstr_len] = '\0';
2059 break;
2060 }
2061 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002062
Kate Stoneb9c1b512016-09-06 20:57:50 +00002063 total_cstr_len += len;
2064
2065 if (len < bytes_to_read)
2066 break;
2067
2068 curr_dst += bytes_read;
2069 curr_addr += bytes_read;
2070 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002071 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002072 } else {
2073 if (dst == nullptr)
2074 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002075 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002076 result_error.Clear();
2077 }
2078 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002079}
2080
Kate Stoneb9c1b512016-09-06 20:57:50 +00002081size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002082 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002083 if (buf == nullptr || size == 0)
2084 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002085
Kate Stoneb9c1b512016-09-06 20:57:50 +00002086 size_t bytes_read = 0;
2087 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002088
Kate Stoneb9c1b512016-09-06 20:57:50 +00002089 while (bytes_read < size) {
2090 const size_t curr_size = size - bytes_read;
2091 const size_t curr_bytes_read =
2092 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2093 bytes_read += curr_bytes_read;
2094 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2095 break;
2096 }
2097
2098 // Replace any software breakpoint opcodes that fall into this range back
2099 // into "buf" before we return
2100 if (bytes_read > 0)
2101 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2102 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002103}
2104
Kate Stoneb9c1b512016-09-06 20:57:50 +00002105uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2106 size_t integer_byte_size,
2107 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002108 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 Scalar scalar;
2110 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2111 error))
2112 return scalar.ULongLong(fail_value);
2113 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002114}
2115
Kate Stoneb9c1b512016-09-06 20:57:50 +00002116int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2117 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002118 int64_t fail_value,
2119 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002120 Scalar scalar;
2121 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2122 error))
2123 return scalar.SLongLong(fail_value);
2124 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002125}
2126
Zachary Turner97206d52017-05-12 04:51:55 +00002127addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128 Scalar scalar;
2129 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2130 error))
2131 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2132 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002133}
2134
Kate Stoneb9c1b512016-09-06 20:57:50 +00002135bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002136 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002137 Scalar scalar;
2138 const uint32_t addr_byte_size = GetAddressByteSize();
2139 if (addr_byte_size <= 4)
2140 scalar = (uint32_t)ptr_value;
2141 else
2142 scalar = ptr_value;
2143 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2144 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002145}
2146
Kate Stoneb9c1b512016-09-06 20:57:50 +00002147size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002148 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002149 size_t bytes_written = 0;
2150 const uint8_t *bytes = (const uint8_t *)buf;
2151
2152 while (bytes_written < size) {
2153 const size_t curr_size = size - bytes_written;
2154 const size_t curr_bytes_written = DoWriteMemory(
2155 addr + bytes_written, bytes + bytes_written, curr_size, error);
2156 bytes_written += curr_bytes_written;
2157 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2158 break;
2159 }
2160 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002161}
2162
Kate Stoneb9c1b512016-09-06 20:57:50 +00002163size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002164 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002165#if defined(ENABLE_MEMORY_CACHING)
2166 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002167#endif
2168
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 if (buf == nullptr || size == 0)
2170 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002171
Kate Stoneb9c1b512016-09-06 20:57:50 +00002172 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002173
Kate Stoneb9c1b512016-09-06 20:57:50 +00002174 // We need to write any data that would go where any current software traps
2175 // (enabled software breakpoints) any software traps (breakpoints) that we
2176 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002177
Kate Stoneb9c1b512016-09-06 20:57:50 +00002178 BreakpointSiteList bp_sites_in_range;
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002179 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002180 return WriteMemoryPrivate(addr, buf, size, error);
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002181
2182 // No breakpoint sites overlap
2183 if (bp_sites_in_range.IsEmpty())
2184 return WriteMemoryPrivate(addr, buf, size, error);
2185
2186 const uint8_t *ubuf = (const uint8_t *)buf;
2187 uint64_t bytes_written = 0;
2188
2189 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2190 &error](BreakpointSite *bp) -> void {
2191 if (error.Fail())
2192 return;
2193
2194 addr_t intersect_addr;
2195 size_t intersect_size;
2196 size_t opcode_offset;
2197 const bool intersects = bp->IntersectsRange(
2198 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2199 UNUSED_IF_ASSERT_DISABLED(intersects);
2200 assert(intersects);
2201 assert(addr <= intersect_addr && intersect_addr < addr + size);
2202 assert(addr < intersect_addr + intersect_size &&
2203 intersect_addr + intersect_size <= addr + size);
2204 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2205
2206 // Check for bytes before this breakpoint
2207 const addr_t curr_addr = addr + bytes_written;
2208 if (intersect_addr > curr_addr) {
2209 // There are some bytes before this breakpoint that we need to just
2210 // write to memory
2211 size_t curr_size = intersect_addr - curr_addr;
2212 size_t curr_bytes_written =
2213 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2214 bytes_written += curr_bytes_written;
2215 if (curr_bytes_written != curr_size) {
2216 // We weren't able to write all of the requested bytes, we are
2217 // done looping and will return the number of bytes that we have
2218 // written so far.
2219 if (error.Success())
2220 error.SetErrorToGenericError();
2221 }
2222 }
2223 // Now write any bytes that would cover up any software breakpoints
2224 // directly into the breakpoint opcode buffer
2225 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2226 intersect_size);
2227 bytes_written += intersect_size;
2228 });
Kate Stoneb9c1b512016-09-06 20:57:50 +00002229
2230 // Write any remaining bytes after the last breakpoint if we have any left
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002231 if (bytes_written < size)
2232 bytes_written +=
2233 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2234 size - bytes_written, error);
2235
2236 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002237}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002238
Kate Stoneb9c1b512016-09-06 20:57:50 +00002239size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002240 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002241 if (byte_size == UINT32_MAX)
2242 byte_size = scalar.GetByteSize();
2243 if (byte_size > 0) {
2244 uint8_t buf[32];
2245 const size_t mem_size =
2246 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2247 if (mem_size > 0)
2248 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002249 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002250 error.SetErrorString("failed to get scalar as memory data");
2251 } else {
2252 error.SetErrorString("invalid scalar value");
2253 }
2254 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002255}
2256
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2258 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002259 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002260 uint64_t uval = 0;
2261 if (byte_size == 0) {
2262 error.SetErrorString("byte size is zero");
2263 } else if (byte_size & (byte_size - 1)) {
2264 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2265 byte_size);
2266 } else if (byte_size <= sizeof(uval)) {
2267 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2268 if (bytes_read == byte_size) {
2269 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2270 GetAddressByteSize());
2271 lldb::offset_t offset = 0;
2272 if (byte_size <= 4)
2273 scalar = data.GetMaxU32(&offset, byte_size);
2274 else
2275 scalar = data.GetMaxU64(&offset, byte_size);
2276 if (is_signed)
2277 scalar.SignExtend(byte_size * 8);
2278 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002279 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002280 } else {
2281 error.SetErrorStringWithFormat(
2282 "byte size of %u is too large for integer scalar type", byte_size);
2283 }
2284 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002285}
2286
Pavel Labath16064d32018-03-20 11:56:24 +00002287Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2288 Status error;
2289 for (const auto &Entry : entries) {
2290 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2291 error);
2292 if (!error.Success())
2293 break;
2294 }
2295 return error;
2296}
2297
Greg Claytond495c532011-05-17 03:37:42 +00002298#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002299addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002300 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002301 if (GetPrivateState() != eStateStopped) {
2302 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002303 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002304 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002305
2306#if defined(USE_ALLOCATE_MEMORY_CACHE)
2307 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002308#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002309 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2310 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002311 LLDB_LOGF(log,
2312 "Process::AllocateMemory(size=%" PRIu64
2313 ", permissions=%s) => 0x%16.16" PRIx64
2314 " (m_stop_id = %u m_memory_id = %u)",
2315 (uint64_t)size, GetPermissionsAsCString(permissions),
2316 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2317 m_mod_id.GetMemoryID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002318 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002319#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002320}
2321
Kate Stoneb9c1b512016-09-06 20:57:50 +00002322addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002323 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324 addr_t return_addr = AllocateMemory(size, permissions, error);
2325 if (error.Success()) {
2326 std::string buffer(size, 0);
2327 WriteMemory(return_addr, buffer.c_str(), size, error);
2328 }
2329 return return_addr;
2330}
2331
2332bool Process::CanJIT() {
2333 if (m_can_jit == eCanJITDontKnow) {
2334 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002335 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002336
2337 uint64_t allocated_memory = AllocateMemory(
2338 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2339 err);
2340
2341 if (err.Success()) {
2342 m_can_jit = eCanJITYes;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002343 LLDB_LOGF(log,
2344 "Process::%s pid %" PRIu64
2345 " allocation test passed, CanJIT () is true",
2346 __FUNCTION__, GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002347 } else {
2348 m_can_jit = eCanJITNo;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002349 LLDB_LOGF(log,
2350 "Process::%s pid %" PRIu64
2351 " allocation test failed, CanJIT () is false: %s",
2352 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002353 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002354
2355 DeallocateMemory(allocated_memory);
2356 }
2357
2358 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002359}
2360
Kate Stoneb9c1b512016-09-06 20:57:50 +00002361void Process::SetCanJIT(bool can_jit) {
2362 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002363}
2364
Kate Stoneb9c1b512016-09-06 20:57:50 +00002365void Process::SetCanRunCode(bool can_run_code) {
2366 SetCanJIT(can_run_code);
2367 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002368}
2369
Zachary Turner97206d52017-05-12 04:51:55 +00002370Status Process::DeallocateMemory(addr_t ptr) {
2371 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002372#if defined(USE_ALLOCATE_MEMORY_CACHE)
2373 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2374 error.SetErrorStringWithFormat(
2375 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2376 }
Greg Claytond495c532011-05-17 03:37:42 +00002377#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002378 error = DoDeallocateMemory(ptr);
2379
2380 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002381 LLDB_LOGF(log,
2382 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2383 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2384 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2385 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002386#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002387 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002388}
2389
Kate Stoneb9c1b512016-09-06 20:57:50 +00002390ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2391 lldb::addr_t header_addr,
2392 size_t size_to_read) {
2393 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2394 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002395 LLDB_LOGF(log,
2396 "Process::ReadModuleFromMemory reading %s binary from memory",
2397 file_spec.GetPath().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002398 }
2399 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2400 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002401 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2403 shared_from_this(), header_addr, error, size_to_read);
2404 if (objfile)
2405 return module_sp;
2406 }
2407 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002408}
2409
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2411 uint32_t &permissions) {
2412 MemoryRegionInfo range_info;
2413 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002414 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002415 if (!error.Success())
2416 return false;
2417 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2418 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2419 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2420 return false;
2421 }
2422
2423 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2424 permissions |= lldb::ePermissionsReadable;
2425
2426 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2427 permissions |= lldb::ePermissionsWritable;
2428
2429 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2430 permissions |= lldb::ePermissionsExecutable;
2431
2432 return true;
2433}
2434
Zachary Turner97206d52017-05-12 04:51:55 +00002435Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2436 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002437 error.SetErrorString("watchpoints are not supported");
2438 return error;
2439}
2440
Zachary Turner97206d52017-05-12 04:51:55 +00002441Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2442 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002443 error.SetErrorString("watchpoints are not supported");
2444 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002445}
2446
2447StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002448Process::WaitForProcessStopPrivate(EventSP &event_sp,
2449 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002450 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002451
Kate Stoneb9c1b512016-09-06 20:57:50 +00002452 while (true) {
2453 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002454 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002455
Kate Stoneb9c1b512016-09-06 20:57:50 +00002456 if (StateIsStoppedState(state, false))
2457 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002458
Kate Stoneb9c1b512016-09-06 20:57:50 +00002459 // If state is invalid, then we timed out
2460 if (state == eStateInvalid)
2461 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002462
Kate Stoneb9c1b512016-09-06 20:57:50 +00002463 if (event_sp)
2464 HandlePrivateEvent(event_sp);
2465 }
2466 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002467}
2468
Kate Stoneb9c1b512016-09-06 20:57:50 +00002469void Process::LoadOperatingSystemPlugin(bool flush) {
2470 if (flush)
2471 m_thread_list.Clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002472 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002473 if (flush)
2474 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002475}
2476
Zachary Turner97206d52017-05-12 04:51:55 +00002477Status Process::Launch(ProcessLaunchInfo &launch_info) {
2478 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002479 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002480 m_dyld_up.reset();
2481 m_jit_loaders_up.reset();
2482 m_system_runtime_up.reset();
2483 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002484 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002485
Kate Stoneb9c1b512016-09-06 20:57:50 +00002486 Module *exe_module = GetTarget().GetExecutableModulePointer();
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002487 if (!exe_module) {
2488 error.SetErrorString("executable module does not exist");
2489 return error;
2490 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002491
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002492 char local_exec_file_path[PATH_MAX];
2493 char platform_exec_file_path[PATH_MAX];
2494 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2495 sizeof(local_exec_file_path));
2496 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2497 sizeof(platform_exec_file_path));
2498 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2499 // Install anything that might need to be installed prior to launching.
2500 // For host systems, this will do nothing, but if we are connected to a
2501 // remote platform it will install any needed binaries
2502 error = GetTarget().Install(&launch_info);
2503 if (error.Fail())
2504 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002505
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002506 if (PrivateStateThreadIsValid())
2507 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002508
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002509 error = WillLaunch(exe_module);
2510 if (error.Success()) {
2511 const bool restarted = false;
2512 SetPublicState(eStateLaunching, restarted);
2513 m_should_detach = false;
2514
2515 if (m_public_run_lock.TrySetRunning()) {
2516 // Now launch using these arguments.
2517 error = DoLaunch(exe_module, launch_info);
2518 } else {
2519 // This shouldn't happen
2520 error.SetErrorString("failed to acquire process run lock");
2521 }
2522
2523 if (error.Fail()) {
2524 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2525 SetID(LLDB_INVALID_PROCESS_ID);
2526 const char *error_string = error.AsCString();
2527 if (error_string == nullptr)
2528 error_string = "launch failed";
2529 SetExitStatus(-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002530 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002531 } else {
2532 EventSP event_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002533
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002534 // Now wait for the process to launch and return control to us, and then
2535 // call DidLaunch:
2536 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Stella Stamenova36d457c2018-06-01 19:14:53 +00002537
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002538 if (state == eStateInvalid || !event_sp) {
2539 // We were able to launch the process, but we failed to catch the
2540 // initial stop.
2541 error.SetErrorString("failed to catch stop after launch");
2542 SetExitStatus(0, "failed to catch stop after launch");
2543 Destroy(false);
2544 } else if (state == eStateStopped || state == eStateCrashed) {
2545 DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002546
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002547 DynamicLoader *dyld = GetDynamicLoader();
2548 if (dyld)
2549 dyld->DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002550
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002551 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002552
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002553 SystemRuntime *system_runtime = GetSystemRuntime();
2554 if (system_runtime)
2555 system_runtime->DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002556
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002557 if (!m_os_up)
2558 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002559
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002560 // We successfully launched the process and stopped, now it the
2561 // right time to set up signal filters before resuming.
2562 UpdateAutomaticSignalFiltering();
Greg Clayton35824e32015-02-20 20:59:47 +00002563
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002564 // Note, the stop event was consumed above, but not handled. This
2565 // was done to give DidLaunch a chance to run. The target is either
2566 // stopped or crashed. Directly set the state. This is done to
2567 // prevent a stop message with a bunch of spurious output on thread
2568 // status, as well as not pop a ProcessIOHandler.
2569 SetPublicState(state, false);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002570
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002571 if (PrivateStateThreadIsValid())
2572 ResumePrivateStateThread();
2573 else
2574 StartPrivateStateThread();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002575
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002576 // Target was stopped at entry as was intended. Need to notify the
2577 // listeners about it.
2578 if (state == eStateStopped &&
2579 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002580 HandlePrivateEvent(event_sp);
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002581 } else if (state == eStateExited) {
2582 // We exited while trying to launch somehow. Don't call DidLaunch
2583 // as that's not likely to work, and return an invalid pid.
2584 HandlePrivateEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002585 }
2586 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002587 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002588 } else {
2589 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2590 local_exec_file_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002591 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002592
Kate Stoneb9c1b512016-09-06 20:57:50 +00002593 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002594}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002595
Zachary Turner97206d52017-05-12 04:51:55 +00002596Status Process::LoadCore() {
2597 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002598 if (error.Success()) {
2599 ListenerSP listener_sp(
2600 Listener::MakeListener("lldb.process.load_core_listener"));
2601 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002602
Kate Stoneb9c1b512016-09-06 20:57:50 +00002603 if (PrivateStateThreadIsValid())
2604 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002605 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002606 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002607
Kate Stoneb9c1b512016-09-06 20:57:50 +00002608 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002609 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002610 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002611
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002612 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002613
Kate Stoneb9c1b512016-09-06 20:57:50 +00002614 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002615 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002616 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002617
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002618 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00002619 LoadOperatingSystemPlugin(false);
2620
Kate Stoneb9c1b512016-09-06 20:57:50 +00002621 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002622 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002623 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002624
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002625 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002626 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002627 StateType state =
Pavel Labath7ada1c52019-06-25 07:14:29 +00002628 WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002629
2630 if (!StateIsStoppedState(state, false)) {
2631 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002632 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2633 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002634 error.SetErrorString(
2635 "Did not get stopped event after loading the core file.");
2636 }
2637 RestoreProcessEvents();
2638 }
2639 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002640}
2641
Kate Stoneb9c1b512016-09-06 20:57:50 +00002642DynamicLoader *Process::GetDynamicLoader() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002643 if (!m_dyld_up)
2644 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2645 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002646}
2647
Antonio Afonso943faef2019-06-11 20:16:13 +00002648DataExtractor Process::GetAuxvData() { return DataExtractor(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002649
2650JITLoaderList &Process::GetJITLoaders() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002651 if (!m_jit_loaders_up) {
2652 m_jit_loaders_up.reset(new JITLoaderList());
2653 JITLoader::LoadPlugins(this, *m_jit_loaders_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002654 }
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002655 return *m_jit_loaders_up;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002656}
2657
2658SystemRuntime *Process::GetSystemRuntime() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002659 if (!m_system_runtime_up)
2660 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2661 return m_system_runtime_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002662}
2663
2664Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2665 uint32_t exec_count)
2666 : NextEventAction(process), m_exec_count(exec_count) {
2667 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002668 LLDB_LOGF(
2669 log,
2670 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2671 __FUNCTION__, static_cast<void *>(process), exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002672}
2673
2674Process::NextEventAction::EventActionResult
2675Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2676 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2677
2678 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002679 LLDB_LOGF(log,
2680 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2681 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002682
2683 switch (state) {
2684 case eStateAttaching:
2685 return eEventActionSuccess;
2686
2687 case eStateRunning:
2688 case eStateConnected:
2689 return eEventActionRetry;
2690
2691 case eStateStopped:
2692 case eStateCrashed:
2693 // During attach, prior to sending the eStateStopped event,
2694 // lldb_private::Process subclasses must set the new process ID.
2695 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002696 // We don't want these events to be reported, so go set the
2697 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002698 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2699
2700 if (m_exec_count > 0) {
2701 --m_exec_count;
2702
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002703 LLDB_LOGF(log,
2704 "Process::AttachCompletionHandler::%s state %s: reduced "
2705 "remaining exec count to %" PRIu32 ", requesting resume",
2706 __FUNCTION__, StateAsCString(state), m_exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002707
2708 RequestResume();
2709 return eEventActionRetry;
2710 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002711 LLDB_LOGF(log,
2712 "Process::AttachCompletionHandler::%s state %s: no more "
2713 "execs expected to start, continuing with attach",
2714 __FUNCTION__, StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002715
2716 m_process->CompleteAttach();
2717 return eEventActionSuccess;
2718 }
2719 break;
2720
2721 default:
2722 case eStateExited:
2723 case eStateInvalid:
2724 break;
2725 }
2726
2727 m_exit_string.assign("No valid Process");
2728 return eEventActionExit;
2729}
2730
2731Process::NextEventAction::EventActionResult
2732Process::AttachCompletionHandler::HandleBeingInterrupted() {
2733 return eEventActionSuccess;
2734}
2735
2736const char *Process::AttachCompletionHandler::GetExitString() {
2737 return m_exit_string.c_str();
2738}
2739
2740ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2741 if (m_listener_sp)
2742 return m_listener_sp;
2743 else
2744 return debugger.GetListener();
2745}
2746
Zachary Turner97206d52017-05-12 04:51:55 +00002747Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748 m_abi_sp.reset();
2749 m_process_input_reader.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002750 m_dyld_up.reset();
2751 m_jit_loaders_up.reset();
2752 m_system_runtime_up.reset();
2753 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002754
2755 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002756 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002757 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2758 char process_name[PATH_MAX];
2759
2760 if (attach_info.GetExecutableFile().GetPath(process_name,
2761 sizeof(process_name))) {
2762 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2763
2764 if (wait_for_launch) {
2765 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2766 if (error.Success()) {
2767 if (m_public_run_lock.TrySetRunning()) {
2768 m_should_detach = true;
2769 const bool restarted = false;
2770 SetPublicState(eStateAttaching, restarted);
2771 // Now attach using these arguments.
2772 error = DoAttachToProcessWithName(process_name, attach_info);
2773 } else {
2774 // This shouldn't happen
2775 error.SetErrorString("failed to acquire process run lock");
2776 }
2777
2778 if (error.Fail()) {
2779 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2780 SetID(LLDB_INVALID_PROCESS_ID);
2781 if (error.AsCString() == nullptr)
2782 error.SetErrorString("attach failed");
2783
2784 SetExitStatus(-1, error.AsCString());
2785 }
2786 } else {
2787 SetNextEventAction(new Process::AttachCompletionHandler(
2788 this, attach_info.GetResumeCount()));
2789 StartPrivateStateThread();
2790 }
2791 return error;
2792 }
2793 } else {
2794 ProcessInstanceInfoList process_infos;
2795 PlatformSP platform_sp(GetTarget().GetPlatform());
2796
2797 if (platform_sp) {
2798 ProcessInstanceInfoMatch match_info;
2799 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00002800 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002801 platform_sp->FindProcesses(match_info, process_infos);
2802 const uint32_t num_matches = process_infos.GetSize();
2803 if (num_matches == 1) {
2804 attach_pid = process_infos.GetProcessIDAtIndex(0);
2805 // Fall through and attach using the above process ID
2806 } else {
2807 match_info.GetProcessInfo().GetExecutableFile().GetPath(
2808 process_name, sizeof(process_name));
2809 if (num_matches > 1) {
2810 StreamString s;
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002811 ProcessInstanceInfo::DumpTableHeader(s, true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002812 for (size_t i = 0; i < num_matches; i++) {
2813 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002814 s, platform_sp->GetUserIDResolver(), true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002815 }
2816 error.SetErrorStringWithFormat(
2817 "more than one process named %s:\n%s", process_name,
2818 s.GetData());
2819 } else
2820 error.SetErrorStringWithFormat(
2821 "could not find a process named %s", process_name);
2822 }
2823 } else {
2824 error.SetErrorString(
2825 "invalid platform, can't find processes by name");
2826 return error;
2827 }
2828 }
2829 } else {
2830 error.SetErrorString("invalid process name");
2831 }
2832 }
2833
2834 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2835 error = WillAttachToProcessWithID(attach_pid);
2836 if (error.Success()) {
2837
2838 if (m_public_run_lock.TrySetRunning()) {
2839 // Now attach using these arguments.
2840 m_should_detach = true;
2841 const bool restarted = false;
2842 SetPublicState(eStateAttaching, restarted);
2843 error = DoAttachToProcessWithID(attach_pid, attach_info);
2844 } else {
2845 // This shouldn't happen
2846 error.SetErrorString("failed to acquire process run lock");
2847 }
2848
2849 if (error.Success()) {
2850 SetNextEventAction(new Process::AttachCompletionHandler(
2851 this, attach_info.GetResumeCount()));
2852 StartPrivateStateThread();
2853 } else {
Greg Clayton71337622011-02-24 22:24:29 +00002854 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002856
Kate Stoneb9c1b512016-09-06 20:57:50 +00002857 const char *error_string = error.AsCString();
2858 if (error_string == nullptr)
2859 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00002860
Kate Stoneb9c1b512016-09-06 20:57:50 +00002861 SetExitStatus(-1, error_string);
2862 }
Greg Claytonb766a732011-02-04 01:58:07 +00002863 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002864 }
2865 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00002866}
2867
Kate Stoneb9c1b512016-09-06 20:57:50 +00002868void Process::CompleteAttach() {
2869 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2870 LIBLLDB_LOG_TARGET));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002871 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002872
2873 // Let the process subclass figure out at much as it can about the process
2874 // before we go looking for a dynamic loader plug-in.
2875 ArchSpec process_arch;
2876 DidAttach(process_arch);
2877
2878 if (process_arch.IsValid()) {
2879 GetTarget().SetArchitecture(process_arch);
2880 if (log) {
2881 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002882 LLDB_LOGF(log,
2883 "Process::%s replacing process architecture with DidAttach() "
2884 "architecture: %s",
2885 __FUNCTION__, triple_str ? triple_str : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002886 }
2887 }
2888
2889 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00002890 // architecture, and if it isn't the same as the one we've already set,
2891 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002892 PlatformSP platform_sp(GetTarget().GetPlatform());
2893 assert(platform_sp);
2894 if (platform_sp) {
2895 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2896 if (target_arch.IsValid() &&
2897 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2898 ArchSpec platform_arch;
2899 platform_sp =
2900 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2901 if (platform_sp) {
2902 GetTarget().SetPlatform(platform_sp);
2903 GetTarget().SetArchitecture(platform_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002904 LLDB_LOGF(log,
2905 "Process::%s switching platform to %s and architecture "
2906 "to %s based on info from attach",
2907 __FUNCTION__, platform_sp->GetName().AsCString(""),
2908 platform_arch.GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002909 }
2910 } else if (!process_arch.IsValid()) {
2911 ProcessInstanceInfo process_info;
2912 GetProcessInfo(process_info);
2913 const ArchSpec &process_arch = process_info.GetArchitecture();
2914 if (process_arch.IsValid() &&
2915 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
2916 GetTarget().SetArchitecture(process_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002917 LLDB_LOGF(log,
2918 "Process::%s switching architecture to %s based on info "
2919 "the platform retrieved for pid %" PRIu64,
2920 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
2921 GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002922 }
2923 }
2924 }
2925
2926 // We have completed the attach, now it is time to find the dynamic loader
2927 // plug-in
2928 DynamicLoader *dyld = GetDynamicLoader();
2929 if (dyld) {
2930 dyld->DidAttach();
2931 if (log) {
2932 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002933 LLDB_LOGF(log,
2934 "Process::%s after DynamicLoader::DidAttach(), target "
2935 "executable is %s (using %s plugin)",
2936 __FUNCTION__,
2937 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2938 : "<none>",
2939 dyld->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002940 }
2941 }
2942
2943 GetJITLoaders().DidAttach();
2944
2945 SystemRuntime *system_runtime = GetSystemRuntime();
2946 if (system_runtime) {
2947 system_runtime->DidAttach();
2948 if (log) {
2949 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002950 LLDB_LOGF(log,
2951 "Process::%s after SystemRuntime::DidAttach(), target "
2952 "executable is %s (using %s plugin)",
2953 __FUNCTION__,
2954 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2955 : "<none>",
2956 system_runtime->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002957 }
2958 }
2959
Jim Ingham8864b432019-06-28 17:57:19 +00002960 if (!m_os_up) {
Greg Clayton29eeea02017-02-09 18:55:41 +00002961 LoadOperatingSystemPlugin(false);
Jim Ingham8864b432019-06-28 17:57:19 +00002962 if (m_os_up) {
2963 // Somebody might have gotten threads before now, but we need to force the
2964 // update after we've loaded the OperatingSystem plugin or it won't get a
2965 // chance to process the threads.
2966 m_thread_list.Clear();
2967 UpdateThreadListIfNeeded();
2968 }
2969 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970 // Figure out which one is the executable, and set that in our target:
2971 const ModuleList &target_modules = GetTarget().GetImages();
2972 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2973 size_t num_modules = target_modules.GetSize();
2974 ModuleSP new_executable_module_sp;
2975
2976 for (size_t i = 0; i < num_modules; i++) {
2977 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
2978 if (module_sp && module_sp->IsExecutable()) {
2979 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
2980 new_executable_module_sp = module_sp;
2981 break;
2982 }
2983 }
2984 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00002985 GetTarget().SetExecutableModule(new_executable_module_sp,
2986 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987 if (log) {
2988 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002989 LLDB_LOGF(
2990 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 "Process::%s after looping through modules, target executable is %s",
2992 __FUNCTION__,
2993 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2994 : "<none>");
2995 }
2996 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002997}
2998
Zachary Turner97206d52017-05-12 04:51:55 +00002999Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003000 m_abi_sp.reset();
3001 m_process_input_reader.reset();
3002
3003 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003004 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003005
Zachary Turner97206d52017-05-12 04:51:55 +00003006 Status error(DoConnectRemote(strm, remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003007 if (error.Success()) {
3008 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3009 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003010 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003011
3012 if (state == eStateStopped || state == eStateCrashed) {
3013 // If we attached and actually have a process on the other end, then
3014 // this ended up being the equivalent of an attach.
3015 CompleteAttach();
3016
3017 // This delays passing the stopped event to listeners till
3018 // CompleteAttach gets a chance to complete...
3019 HandlePrivateEvent(event_sp);
3020 }
3021 }
3022
3023 if (PrivateStateThreadIsValid())
3024 ResumePrivateStateThread();
3025 else
3026 StartPrivateStateThread();
3027 }
3028 return error;
3029}
3030
Zachary Turner97206d52017-05-12 04:51:55 +00003031Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003032 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3033 LIBLLDB_LOG_STEP));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003034 LLDB_LOGF(log,
3035 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3036 "private state: %s",
3037 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3038 StateAsCString(m_private_state.GetValue()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003039
Adrian Prantl05097242018-04-30 16:49:04 +00003040 // If signals handing status changed we might want to update our signal
3041 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003042 UpdateAutomaticSignalFiltering();
3043
Zachary Turner97206d52017-05-12 04:51:55 +00003044 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003045 // Tell the process it is about to resume before the thread list
3046 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003047 // Now let the thread list know we are about to resume so it can let all of
3048 // our threads know that they are about to be resumed. Threads will each be
3049 // called with Thread::WillResume(StateType) where StateType contains the
3050 // state that they are supposed to have when the process is resumed
3051 // (suspended/running/stepping). Threads should also check their resume
3052 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3053 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003054 if (m_thread_list.WillResume()) {
3055 // Last thing, do the PreResumeActions.
3056 if (!RunPreResumeActions()) {
3057 error.SetErrorStringWithFormat(
3058 "Process::PrivateResume PreResumeActions failed, not resuming.");
3059 } else {
3060 m_mod_id.BumpResumeID();
3061 error = DoResume();
3062 if (error.Success()) {
3063 DidResume();
3064 m_thread_list.DidResume();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003065 LLDB_LOGF(log, "Process thinks the process has resumed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003066 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003067 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003068 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003069 }
3070 }
3071 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003072 // Somebody wanted to run without running (e.g. we were faking a step
3073 // from one frame of a set of inlined frames that share the same PC to
3074 // another.) So generate a continue & a stopped event, and let the world
3075 // handle them.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003076 LLDB_LOGF(log,
3077 "Process::PrivateResume() asked to simulate a start & stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003078
3079 SetPrivateState(eStateRunning);
3080 SetPrivateState(eStateStopped);
3081 }
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003082 } else
3083 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3084 error.AsCString("<unknown error>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003085 return error;
3086}
3087
Zachary Turner97206d52017-05-12 04:51:55 +00003088Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003089 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003090 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003091
Adrian Prantl05097242018-04-30 16:49:04 +00003092 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3093 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003094 m_clear_thread_plans_on_stop |= clear_thread_plans;
3095
3096 ListenerSP halt_listener_sp(
3097 Listener::MakeListener("lldb.process.halt_listener"));
3098 HijackProcessEvents(halt_listener_sp);
3099
3100 EventSP event_sp;
3101
3102 SendAsyncInterrupt();
3103
3104 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003105 // Don't hijack and eat the eStateExited as the code that was doing the
3106 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003107 RestoreProcessEvents();
3108 SetExitStatus(SIGKILL, "Cancelled async attach.");
3109 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003110 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003111 }
3112
3113 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003114 StateType state = WaitForProcessToStop(
3115 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003116 RestoreProcessEvents();
3117
3118 if (state == eStateInvalid || !event_sp) {
3119 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003120 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003121 }
3122
3123 BroadcastEvent(event_sp);
3124
Zachary Turner97206d52017-05-12 04:51:55 +00003125 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003126}
3127
Zachary Turner97206d52017-05-12 04:51:55 +00003128Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3129 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003130
3131 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003132 // expression, for instance, then the public state will be stopped, but we
3133 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134 if (m_public_state.GetValue() == eStateRunning ||
3135 m_private_state.GetValue() == eStateRunning) {
3136 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003137 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003138
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 ListenerSP listener_sp(
3140 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3141 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003142
Pavel Labath19da1f12015-12-07 12:36:52 +00003143 SendAsyncInterrupt();
3144
Kate Stoneb9c1b512016-09-06 20:57:50 +00003145 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003146 StateType state =
3147 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003148
Pavel Labath19da1f12015-12-07 12:36:52 +00003149 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003150
Kate Stoneb9c1b512016-09-06 20:57:50 +00003151 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003152 // exited event into the shared pointer passed in and return. Our caller
3153 // doesn't need to do anything else, since they don't have a process
3154 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003155
3156 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003157 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3158 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003159 return error;
3160 } else
3161 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3162
3163 if (state != eStateStopped) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003164 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3165 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003166 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003167 // here, but if the lower levels just bobbled sending the event and we
3168 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003169 StateType private_state = m_private_state.GetValue();
3170 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003171 return Status(
3172 "Attempt to stop the target in order to detach timed out. "
3173 "State = %s",
3174 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003175 }
3176 }
3177 }
3178 return error;
3179}
3180
Zachary Turner97206d52017-05-12 04:51:55 +00003181Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003182 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003183 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003184 m_destroy_in_process = true;
3185
3186 error = WillDetach();
3187
3188 if (error.Success()) {
3189 if (DetachRequiresHalt()) {
3190 error = StopForDestroyOrDetach(exit_event_sp);
3191 if (!error.Success()) {
3192 m_destroy_in_process = false;
3193 return error;
3194 } else if (exit_event_sp) {
3195 // We shouldn't need to do anything else here. There's no process left
3196 // to detach from...
3197 StopPrivateStateThread();
3198 m_destroy_in_process = false;
3199 return error;
3200 }
3201 }
3202
3203 m_thread_list.DiscardThreadPlans();
3204 DisableAllBreakpointSites();
3205
3206 error = DoDetach(keep_stopped);
3207 if (error.Success()) {
3208 DidDetach();
3209 StopPrivateStateThread();
3210 } else {
3211 return error;
3212 }
3213 }
3214 m_destroy_in_process = false;
3215
Adrian Prantl05097242018-04-30 16:49:04 +00003216 // If we exited when we were waiting for a process to stop, then forward the
3217 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003218 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003219 // Directly broadcast our exited event because we shut down our private
3220 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003221 BroadcastEvent(exit_event_sp);
3222 }
3223
3224 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003225 // not end up propagating the last events through the event system, in which
3226 // case we might strand the write lock. Unlock it here so when we do to tear
3227 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003228
3229 m_public_run_lock.SetStopped();
3230 return error;
3231}
3232
Zachary Turner97206d52017-05-12 04:51:55 +00003233Status Process::Destroy(bool force_kill) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003234
3235 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003236 // don't do any unnecessary work that might hinder the destruction. Remember
3237 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003238 // failed and the process stays around for some reason it won't be in a
3239 // confused state.
3240
3241 if (force_kill)
3242 m_should_detach = false;
3243
3244 if (GetShouldDetach()) {
3245 // FIXME: This will have to be a process setting:
3246 bool keep_stopped = false;
3247 Detach(keep_stopped);
3248 }
3249
3250 m_destroy_in_process = true;
3251
Zachary Turner97206d52017-05-12 04:51:55 +00003252 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003253 if (error.Success()) {
3254 EventSP exit_event_sp;
3255 if (DestroyRequiresHalt()) {
3256 error = StopForDestroyOrDetach(exit_event_sp);
3257 }
3258
3259 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003260 // Ditch all thread plans, and remove all our breakpoints: in case we
3261 // have to restart the target to kill it, we don't want it hitting a
3262 // breakpoint... Only do this if we've stopped, however, since if we
3263 // didn't manage to halt it above, then we're not going to have much luck
3264 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003265 m_thread_list.DiscardThreadPlans();
3266 DisableAllBreakpointSites();
3267 }
3268
3269 error = DoDestroy();
3270 if (error.Success()) {
3271 DidDestroy();
3272 StopPrivateStateThread();
3273 }
3274 m_stdio_communication.Disconnect();
3275 m_stdio_communication.StopReadThread();
3276 m_stdin_forward = false;
3277
3278 if (m_process_input_reader) {
3279 m_process_input_reader->SetIsDone(true);
3280 m_process_input_reader->Cancel();
3281 m_process_input_reader.reset();
3282 }
3283
Adrian Prantl05097242018-04-30 16:49:04 +00003284 // If we exited when we were waiting for a process to stop, then forward
3285 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003286 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003287 // Directly broadcast our exited event because we shut down our private
3288 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003289 BroadcastEvent(exit_event_sp);
3290 }
3291
Adrian Prantl05097242018-04-30 16:49:04 +00003292 // If we have been interrupted (to kill us) in the middle of running, we
3293 // may not end up propagating the last events through the event system, in
3294 // which case we might strand the write lock. Unlock it here so when we do
3295 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003296 m_public_run_lock.SetStopped();
3297 }
3298
3299 m_destroy_in_process = false;
3300
3301 return error;
3302}
3303
Zachary Turner97206d52017-05-12 04:51:55 +00003304Status Process::Signal(int signal) {
3305 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003306 if (error.Success()) {
3307 error = DoSignal(signal);
3308 if (error.Success())
3309 DidSignal();
3310 }
3311 return error;
3312}
3313
3314void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3315 assert(signals_sp && "null signals_sp");
3316 m_unix_signals_sp = signals_sp;
3317}
3318
3319const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3320 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3321 return m_unix_signals_sp;
3322}
3323
3324lldb::ByteOrder Process::GetByteOrder() const {
3325 return GetTarget().GetArchitecture().GetByteOrder();
3326}
3327
3328uint32_t Process::GetAddressByteSize() const {
3329 return GetTarget().GetArchitecture().GetAddressByteSize();
3330}
3331
3332bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3333 const StateType state =
3334 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3335 bool return_value = true;
3336 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3337 LIBLLDB_LOG_PROCESS));
3338
3339 switch (state) {
3340 case eStateDetached:
3341 case eStateExited:
3342 case eStateUnloaded:
3343 m_stdio_communication.SynchronizeWithReadThread();
3344 m_stdio_communication.Disconnect();
3345 m_stdio_communication.StopReadThread();
3346 m_stdin_forward = false;
3347
3348 LLVM_FALLTHROUGH;
3349 case eStateConnected:
3350 case eStateAttaching:
3351 case eStateLaunching:
3352 // These events indicate changes in the state of the debugging session,
3353 // always report them.
3354 return_value = true;
3355 break;
3356 case eStateInvalid:
3357 // We stopped for no apparent reason, don't report it.
3358 return_value = false;
3359 break;
3360 case eStateRunning:
3361 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003362 // If we've started the target running, we handle the cases where we are
3363 // already running and where there is a transition from stopped to running
3364 // differently. running -> running: Automatically suppress extra running
3365 // events stopped -> running: Report except when there is one or more no
3366 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003367 // and no yes votes.
3368 SynchronouslyNotifyStateChanged(state);
3369 if (m_force_next_event_delivery)
3370 return_value = true;
3371 else {
3372 switch (m_last_broadcast_state) {
3373 case eStateRunning:
3374 case eStateStepping:
3375 // We always suppress multiple runnings with no PUBLIC stop in between.
3376 return_value = false;
3377 break;
3378 default:
3379 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003380 // run if we aren't running so we don't miss any running events. If I
3381 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3382 // and hit the breakpoints on multiple threads, then somehow during the
3383 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003384
3385 // This is a transition from stop to run.
3386 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3387 case eVoteYes:
3388 case eVoteNoOpinion:
3389 return_value = true;
3390 break;
3391 case eVoteNo:
3392 return_value = false;
3393 break;
3394 }
3395 break;
3396 }
3397 }
3398 break;
3399 case eStateStopped:
3400 case eStateCrashed:
3401 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003402 // We've stopped. First see if we're going to restart the target. If we
3403 // are going to stop, then we always broadcast the event. If we aren't
3404 // going to stop, let the thread plans decide if we're going to report this
3405 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003406
3407 m_stdio_communication.SynchronizeWithReadThread();
3408 RefreshStateAfterStop();
3409 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003410 LLDB_LOGF(log,
3411 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3412 "interrupt, state: %s",
3413 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003414 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003415 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003416 m_thread_list.ShouldStop(event_ptr);
3417 return_value = true;
3418 } else {
3419 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3420 bool should_resume = false;
3421
3422 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003423 // restarted... Asking the thread list is also not likely to go well,
3424 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003425
3426 if (!was_restarted)
3427 should_resume = !m_thread_list.ShouldStop(event_ptr);
3428
3429 if (was_restarted || should_resume || m_resume_requested) {
3430 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003431 LLDB_LOGF(log,
3432 "Process::ShouldBroadcastEvent: should_resume: %i state: "
3433 "%s was_restarted: %i stop_vote: %d.",
3434 should_resume, StateAsCString(state), was_restarted,
3435 stop_vote);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003436
3437 switch (stop_vote) {
3438 case eVoteYes:
3439 return_value = true;
3440 break;
3441 case eVoteNoOpinion:
3442 case eVoteNo:
3443 return_value = false;
3444 break;
3445 }
3446
3447 if (!was_restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003448 LLDB_LOGF(log,
3449 "Process::ShouldBroadcastEvent (%p) Restarting process "
3450 "from state: %s",
3451 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003452 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3453 PrivateResume();
3454 }
3455 } else {
3456 return_value = true;
3457 SynchronouslyNotifyStateChanged(state);
3458 }
3459 }
3460 break;
3461 }
3462
3463 // Forcing the next event delivery is a one shot deal. So reset it here.
3464 m_force_next_event_delivery = false;
3465
3466 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003467 // events get coalesced.) But we only coalesce against events we actually
3468 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3469 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3470 // done, because the PublicState reflects the last event pulled off the
3471 // queue, and there may be several events stacked up on the queue unserviced.
3472 // So the PublicState may not reflect the last broadcasted event yet.
3473 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003474
3475 if (return_value)
3476 m_last_broadcast_state = state;
3477
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003478 LLDB_LOGF(log,
3479 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3480 "broadcast state: %s - %s",
3481 static_cast<void *>(event_ptr), StateAsCString(state),
3482 StateAsCString(m_last_broadcast_state),
3483 return_value ? "YES" : "NO");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003484 return return_value;
3485}
3486
3487bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3488 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3489
3490 bool already_running = PrivateStateThreadIsValid();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003491 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
3492 already_running ? " already running"
3493 : " starting private state thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003494
3495 if (!is_secondary_thread && already_running)
3496 return true;
3497
Adrian Prantl05097242018-04-30 16:49:04 +00003498 // Create a thread that watches our internal state and controls which events
3499 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003500 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003501 uint32_t max_len = llvm::get_max_thread_name_length();
3502 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003503 // On platforms with abbreviated thread name lengths, choose thread names
3504 // that fit within the limit.
3505 if (already_running)
3506 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3507 else
3508 snprintf(thread_name, sizeof(thread_name), "intern-state");
3509 } else {
3510 if (already_running)
3511 snprintf(thread_name, sizeof(thread_name),
3512 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3513 GetID());
3514 else
3515 snprintf(thread_name, sizeof(thread_name),
3516 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3517 }
3518
3519 // Create the private state thread, and start it running.
3520 PrivateStateThreadArgs *args_ptr =
3521 new PrivateStateThreadArgs(this, is_secondary_thread);
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003522 llvm::Expected<HostThread> private_state_thread =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003523 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003524 (void *)args_ptr, 8 * 1024 * 1024);
3525 if (!private_state_thread) {
3526 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3527 "failed to launch host thread: {}",
3528 llvm::toString(private_state_thread.takeError()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003529 return false;
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003530 }
3531
3532 assert(private_state_thread->IsJoinable());
3533 m_private_state_thread = *private_state_thread;
3534 ResumePrivateStateThread();
3535 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003536}
3537
3538void Process::PausePrivateStateThread() {
3539 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3540}
3541
3542void Process::ResumePrivateStateThread() {
3543 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3544}
3545
3546void Process::StopPrivateStateThread() {
3547 if (m_private_state_thread.IsJoinable())
3548 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3549 else {
3550 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003551 LLDB_LOGF(
3552 log,
3553 "Went to stop the private state thread, but it was already invalid.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003554 }
3555}
3556
3557void Process::ControlPrivateStateThread(uint32_t signal) {
3558 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3559
3560 assert(signal == eBroadcastInternalStateControlStop ||
3561 signal == eBroadcastInternalStateControlPause ||
3562 signal == eBroadcastInternalStateControlResume);
3563
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003564 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003565
3566 // Signal the private state thread
3567 if (m_private_state_thread.IsJoinable()) {
3568 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003569 // It is important to do this outside of the if below, because it's
3570 // possible that the thread state is invalid but that the thread is waiting
3571 // on a control event instead of simply being on its way out (this should
3572 // not happen, but it apparently can).
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003573 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003574 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3575 m_private_state_control_broadcaster.BroadcastEvent(signal,
3576 event_receipt_sp);
3577
3578 // Wait for the event receipt or for the private state thread to exit
3579 bool receipt_received = false;
3580 if (PrivateStateThreadIsValid()) {
3581 while (!receipt_received) {
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003582 // Check for a receipt for n seconds and then check if the private
Adrian Prantl05097242018-04-30 16:49:04 +00003583 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003584 receipt_received =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003585 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003586 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003587 // Check if the private state thread is still around. If it isn't
3588 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003589 if (!PrivateStateThreadIsValid())
3590 break; // Private state thread exited or is exiting, we are done
3591 }
3592 }
3593 }
3594
3595 if (signal == eBroadcastInternalStateControlStop) {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003596 thread_result_t result = {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003597 m_private_state_thread.Join(&result);
3598 m_private_state_thread.Reset();
3599 }
3600 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003601 LLDB_LOGF(
3602 log,
3603 "Private state thread already dead, no need to signal it to stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003604 }
3605}
3606
3607void Process::SendAsyncInterrupt() {
3608 if (PrivateStateThreadIsValid())
3609 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3610 nullptr);
3611 else
3612 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3613}
3614
3615void Process::HandlePrivateEvent(EventSP &event_sp) {
3616 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3617 m_resume_requested = false;
3618
3619 const StateType new_state =
3620 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3621
3622 // First check to see if anybody wants a shot at this event:
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003623 if (m_next_event_action_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003624 NextEventAction::EventActionResult action_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003625 m_next_event_action_up->PerformAction(event_sp);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003626 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003627
3628 switch (action_result) {
3629 case NextEventAction::eEventActionSuccess:
3630 SetNextEventAction(nullptr);
3631 break;
3632
3633 case NextEventAction::eEventActionRetry:
3634 break;
3635
3636 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003637 // Handle Exiting Here. If we already got an exited event, we should
3638 // just propagate it. Otherwise, swallow this event, and set our state
3639 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003640 if (new_state != eStateExited) {
3641 // FIXME: should cons up an exited event, and discard this one.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003642 SetExitStatus(0, m_next_event_action_up->GetExitString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003643 SetNextEventAction(nullptr);
3644 return;
3645 }
3646 SetNextEventAction(nullptr);
3647 break;
3648 }
3649 }
3650
3651 // See if we should broadcast this state to external clients?
3652 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3653
3654 if (should_broadcast) {
3655 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3656 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003657 LLDB_LOGF(log,
3658 "Process::%s (pid = %" PRIu64
3659 ") broadcasting new state %s (old state %s) to %s",
3660 __FUNCTION__, GetID(), StateAsCString(new_state),
3661 StateAsCString(GetState()),
3662 is_hijacked ? "hijacked" : "public");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003663 }
3664 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3665 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003666 // Only push the input handler if we aren't fowarding events, as this
3667 // means the curses GUI is in use... Or don't push it if we are launching
3668 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003669 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3670 new_state != eStateLaunching && new_state != eStateAttaching) {
3671 PushProcessIOHandler();
3672 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3673 eBroadcastAlways);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003674 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
3675 __FUNCTION__, m_iohandler_sync.GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003676 }
3677 } else if (StateIsStoppedState(new_state, false)) {
3678 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003679 // If the lldb_private::Debugger is handling the events, we don't want
3680 // to pop the process IOHandler here, we want to do it when we receive
3681 // the stopped event so we can carefully control when the process
3682 // IOHandler is popped because when we stop we want to display some
3683 // text stating how and why we stopped, then maybe some
3684 // process/thread/frame info, and then we want the "(lldb) " prompt to
3685 // show up. If we pop the process IOHandler here, then we will cause
3686 // the command interpreter to become the top IOHandler after the
3687 // process pops off and it will update its prompt right away... See the
3688 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003689 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3690 // Otherwise we end up getting overlapping "(lldb) " prompts and
3691 // garbled output.
3692 //
3693 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003694 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3695 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003696 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003697 // thread plans, or when commands want to run in synchronous mode and
3698 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003699 // that will hijack the events is a simple expression:
3700 //
3701 // (lldb) expr (int)puts("hello")
3702 //
3703 // This will cause the internal process state thread to resume and halt
3704 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3705 // events) and we do need the IO handler to be pushed and popped
3706 // correctly.
3707
3708 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3709 PopProcessIOHandler();
3710 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003711 }
3712
3713 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003714 } else {
3715 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003716 LLDB_LOGF(
3717 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003718 "Process::%s (pid = %" PRIu64
3719 ") suppressing state %s (old state %s): should_broadcast == false",
3720 __FUNCTION__, GetID(), StateAsCString(new_state),
3721 StateAsCString(GetState()));
3722 }
3723 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003724}
3725
Zachary Turner97206d52017-05-12 04:51:55 +00003726Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003727 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003728 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003729 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003730 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003731
3732 // Ask the process subclass to actually halt our process
3733 bool caused_stop;
3734 error = DoHalt(caused_stop);
3735
3736 DidHalt();
3737 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003738}
3739
Kate Stoneb9c1b512016-09-06 20:57:50 +00003740thread_result_t Process::PrivateStateThread(void *arg) {
3741 std::unique_ptr<PrivateStateThreadArgs> args_up(
3742 static_cast<PrivateStateThreadArgs *>(arg));
3743 thread_result_t result =
3744 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3745 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003746}
3747
Kate Stoneb9c1b512016-09-06 20:57:50 +00003748thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3749 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003750
Kate Stoneb9c1b512016-09-06 20:57:50 +00003751 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003752 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3753 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003754
Kate Stoneb9c1b512016-09-06 20:57:50 +00003755 bool exit_now = false;
3756 bool interrupt_requested = false;
3757 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003758 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003759 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003760 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003761 LLDB_LOGF(log,
3762 "Process::%s (arg = %p, pid = %" PRIu64
3763 ") got a control event: %d",
3764 __FUNCTION__, static_cast<void *>(this), GetID(),
3765 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003766
Kate Stoneb9c1b512016-09-06 20:57:50 +00003767 switch (event_sp->GetType()) {
3768 case eBroadcastInternalStateControlStop:
3769 exit_now = true;
3770 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003771
Kate Stoneb9c1b512016-09-06 20:57:50 +00003772 case eBroadcastInternalStateControlPause:
3773 control_only = true;
3774 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003775
Kate Stoneb9c1b512016-09-06 20:57:50 +00003776 case eBroadcastInternalStateControlResume:
3777 control_only = false;
3778 break;
3779 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003780
Kate Stoneb9c1b512016-09-06 20:57:50 +00003781 continue;
3782 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3783 if (m_public_state.GetValue() == eStateAttaching) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003784 LLDB_LOGF(log,
3785 "Process::%s (arg = %p, pid = %" PRIu64
3786 ") woke up with an interrupt while attaching - "
3787 "forwarding interrupt.",
3788 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003789 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3790 } else if (StateIsRunningState(m_last_broadcast_state)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003791 LLDB_LOGF(log,
3792 "Process::%s (arg = %p, pid = %" PRIu64
3793 ") woke up with an interrupt - Halting.",
3794 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00003795 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003796 if (error.Fail() && log)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003797 LLDB_LOGF(log,
3798 "Process::%s (arg = %p, pid = %" PRIu64
3799 ") failed to halt the process: %s",
3800 __FUNCTION__, static_cast<void *>(this), GetID(),
3801 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00003802 // Halt should generate a stopped event. Make a note of the fact that
3803 // we were doing the interrupt, so we can set the interrupted flag
3804 // after we receive the event. We deliberately set this to true even if
3805 // HaltPrivate failed, so that we can interrupt on the next natural
3806 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003807 interrupt_requested = true;
3808 } else {
3809 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00003810 // running and sends an interrupt request, but the process actually
3811 // stops before we receive it. In that case, we can just ignore the
3812 // request. We use m_last_broadcast_state, because the Stopped event
3813 // may not have been popped of the event queue yet, which is when the
3814 // public state gets updated.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003815 LLDB_LOGF(log,
3816 "Process::%s ignoring interrupt as we have already stopped.",
3817 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003818 }
3819 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003820 }
3821
Kate Stoneb9c1b512016-09-06 20:57:50 +00003822 const StateType internal_state =
3823 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003824
Kate Stoneb9c1b512016-09-06 20:57:50 +00003825 if (internal_state != eStateInvalid) {
3826 if (m_clear_thread_plans_on_stop &&
3827 StateIsStoppedState(internal_state, true)) {
3828 m_clear_thread_plans_on_stop = false;
3829 m_thread_list.DiscardThreadPlans();
3830 }
3831
3832 if (interrupt_requested) {
3833 if (StateIsStoppedState(internal_state, true)) {
3834 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00003835 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00003836 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3837 interrupt_requested = false;
3838 } else if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003839 LLDB_LOGF(log,
3840 "Process::%s interrupt_requested, but a non-stopped "
3841 "state '%s' received.",
3842 __FUNCTION__, StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003843 }
3844 }
3845
3846 HandlePrivateEvent(event_sp);
3847 }
3848
3849 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3850 internal_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003851 LLDB_LOGF(log,
3852 "Process::%s (arg = %p, pid = %" PRIu64
3853 ") about to exit with internal state %s...",
3854 __FUNCTION__, static_cast<void *>(this), GetID(),
3855 StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003856
3857 break;
3858 }
3859 }
3860
3861 // Verify log is still enabled before attempting to write to it...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003862 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3863 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003864
3865 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00003866 // will have already acquired the public_run_lock, and isn't done with what
3867 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003868 if (!is_secondary_thread)
3869 m_public_run_lock.SetStopped();
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003870 return {};
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003871}
3872
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003873// Process Event Data
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003874
Kate Stoneb9c1b512016-09-06 20:57:50 +00003875Process::ProcessEventData::ProcessEventData()
3876 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3877 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003878
Kate Stoneb9c1b512016-09-06 20:57:50 +00003879Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3880 StateType state)
3881 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3882 m_update_state(0), m_interrupted(false) {
3883 if (process_sp)
3884 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003885}
3886
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003887Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003888
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003889ConstString Process::ProcessEventData::GetFlavorString() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003890 static ConstString g_flavor("Process::ProcessEventData");
3891 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003892}
3893
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003894ConstString Process::ProcessEventData::GetFlavor() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003895 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003896}
3897
Kate Stoneb9c1b512016-09-06 20:57:50 +00003898void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
3899 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00003900
Kate Stoneb9c1b512016-09-06 20:57:50 +00003901 if (!process_sp)
3902 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003903
Kate Stoneb9c1b512016-09-06 20:57:50 +00003904 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00003905 // pulled off of the private process event queue, and then any number of
3906 // times, first when it gets pulled off of the public event queue, then other
3907 // times when we're pretending that this is where we stopped at the end of
3908 // expression evaluation. m_update_state is used to distinguish these three
3909 // cases; it is 0 when we're just pulling it off for private handling, and >
3910 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00003911 // command handling then.
3912 if (m_update_state != 1)
3913 return;
3914
3915 process_sp->SetPublicState(
3916 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
3917
Jason Molendab3a3cd12016-12-08 06:27:29 +00003918 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00003919 // Let process subclasses know we are about to do a public stop and do
3920 // anything they might need to in order to speed up register and memory
3921 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00003922 process_sp->WillPublicStop();
3923 }
3924
Kate Stoneb9c1b512016-09-06 20:57:50 +00003925 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00003926 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
3927 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00003928 // end up restarting the process.
3929 if (m_interrupted)
3930 return;
3931
3932 // If we're stopped and haven't restarted, then do the StopInfo actions here:
3933 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003934 ThreadList &curr_thread_list = process_sp->GetThreadList();
3935 uint32_t num_threads = curr_thread_list.GetSize();
3936 uint32_t idx;
3937
3938 // The actions might change one of the thread's stop_info's opinions about
Adrian Prantl05097242018-04-30 16:49:04 +00003939 // whether we should stop the process, so we need to query that as we go.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003940
3941 // One other complication here, is that we try to catch any case where the
Adrian Prantl05097242018-04-30 16:49:04 +00003942 // target has run (except for expressions) and immediately exit, but if we
3943 // get that wrong (which is possible) then the thread list might have
3944 // changed, and that would cause our iteration here to crash. We could
3945 // make a copy of the thread list, but we'd really like to also know if it
3946 // has changed at all, so we make up a vector of the thread ID's and check
3947 // what we get back against this list & bag out if anything differs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003948 std::vector<uint32_t> thread_index_array(num_threads);
3949 for (idx = 0; idx < num_threads; ++idx)
3950 thread_index_array[idx] =
3951 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3952
3953 // Use this to track whether we should continue from here. We will only
Adrian Prantl05097242018-04-30 16:49:04 +00003954 // continue the target running if no thread says we should stop. Of course
3955 // if some thread's PerformAction actually sets the target running, then it
3956 // doesn't matter what the other threads say...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003957
3958 bool still_should_stop = false;
3959
3960 // Sometimes - for instance if we have a bug in the stub we are talking to,
Adrian Prantl05097242018-04-30 16:49:04 +00003961 // we stop but no thread has a valid stop reason. In that case we should
3962 // just stop, because we have no way of telling what the right thing to do
3963 // is, and it's better to let the user decide than continue behind their
3964 // backs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003965
3966 bool does_anybody_have_an_opinion = false;
3967
3968 for (idx = 0; idx < num_threads; ++idx) {
3969 curr_thread_list = process_sp->GetThreadList();
3970 if (curr_thread_list.GetSize() != num_threads) {
3971 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
3972 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003973 LLDB_LOGF(
3974 log,
3975 "Number of threads changed from %u to %u while processing event.",
3976 num_threads, curr_thread_list.GetSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003977 break;
3978 }
3979
3980 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3981
3982 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
3983 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
3984 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003985 LLDB_LOGF(log,
3986 "The thread at position %u changed from %u to %u while "
3987 "processing event.",
3988 idx, thread_index_array[idx], thread_sp->GetIndexID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003989 break;
3990 }
3991
3992 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
3993 if (stop_info_sp && stop_info_sp->IsValid()) {
3994 does_anybody_have_an_opinion = true;
3995 bool this_thread_wants_to_stop;
3996 if (stop_info_sp->GetOverrideShouldStop()) {
3997 this_thread_wants_to_stop =
3998 stop_info_sp->GetOverriddenShouldStopValue();
3999 } else {
4000 stop_info_sp->PerformAction(event_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +00004001 // The stop action might restart the target. If it does, then we
4002 // want to mark that in the event so that whoever is receiving it
4003 // will know to wait for the running event and reflect that state
4004 // appropriately. We also need to stop processing actions, since they
4005 // aren't expecting the target to be running.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004006
4007 // FIXME: we might have run.
4008 if (stop_info_sp->HasTargetRunSinceMe()) {
4009 SetRestarted(true);
4010 break;
4011 }
4012
4013 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004014 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004015
4016 if (!still_should_stop)
4017 still_should_stop = this_thread_wants_to_stop;
4018 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004019 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004020
4021 if (!GetRestarted()) {
4022 if (!still_should_stop && does_anybody_have_an_opinion) {
4023 // We've been asked to continue, so do that here.
4024 SetRestarted(true);
Adrian Prantl05097242018-04-30 16:49:04 +00004025 // Use the public resume method here, since this is just extending a
4026 // public resume.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004027 process_sp->PrivateResume();
4028 } else {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004029 bool hijacked =
4030 process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4031 !process_sp->StateChangedIsHijackedForSynchronousResume();
Jim Ingham3139fc92019-03-01 18:13:38 +00004032
4033 if (!hijacked) {
4034 // If we didn't restart, run the Stop Hooks here.
4035 // Don't do that if state changed events aren't hooked up to the
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004036 // public (or SyncResume) broadcasters. StopHooks are just for
4037 // real public stops. They might also restart the target,
Jim Ingham3139fc92019-03-01 18:13:38 +00004038 // so watch for that.
4039 process_sp->GetTarget().RunStopHooks();
4040 if (process_sp->GetPrivateState() == eStateRunning)
4041 SetRestarted(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004042 }
4043 }
4044 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004045}
Zachary Turner805e7102019-03-04 21:51:03 +00004046}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004047
Kate Stoneb9c1b512016-09-06 20:57:50 +00004048void Process::ProcessEventData::Dump(Stream *s) const {
4049 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004050
Kate Stoneb9c1b512016-09-06 20:57:50 +00004051 if (process_sp)
4052 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4053 static_cast<void *>(process_sp.get()), process_sp->GetID());
4054 else
4055 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004056
Kate Stoneb9c1b512016-09-06 20:57:50 +00004057 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004058}
4059
4060const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004061Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4062 if (event_ptr) {
4063 const EventData *event_data = event_ptr->GetData();
4064 if (event_data &&
4065 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4066 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4067 }
4068 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004069}
4070
4071ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004072Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4073 ProcessSP process_sp;
4074 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4075 if (data)
4076 process_sp = data->GetProcessSP();
4077 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004078}
4079
Kate Stoneb9c1b512016-09-06 20:57:50 +00004080StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4081 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4082 if (data == nullptr)
4083 return eStateInvalid;
4084 else
4085 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004086}
4087
Kate Stoneb9c1b512016-09-06 20:57:50 +00004088bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4089 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4090 if (data == nullptr)
4091 return false;
4092 else
4093 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004094}
4095
Kate Stoneb9c1b512016-09-06 20:57:50 +00004096void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4097 bool new_value) {
4098 ProcessEventData *data =
4099 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4100 if (data != nullptr)
4101 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004102}
4103
Jim Ingham0161b492013-02-09 01:29:05 +00004104size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004105Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4106 ProcessEventData *data =
4107 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4108 if (data != nullptr)
4109 return data->GetNumRestartedReasons();
4110 else
4111 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004112}
4113
4114const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004115Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4116 size_t idx) {
4117 ProcessEventData *data =
4118 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4119 if (data != nullptr)
4120 return data->GetRestartedReasonAtIndex(idx);
4121 else
4122 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004123}
4124
Kate Stoneb9c1b512016-09-06 20:57:50 +00004125void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4126 const char *reason) {
4127 ProcessEventData *data =
4128 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4129 if (data != nullptr)
4130 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004131}
4132
Kate Stoneb9c1b512016-09-06 20:57:50 +00004133bool Process::ProcessEventData::GetInterruptedFromEvent(
4134 const Event *event_ptr) {
4135 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4136 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004137 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004138 else
4139 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004140}
4141
Kate Stoneb9c1b512016-09-06 20:57:50 +00004142void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4143 bool new_value) {
4144 ProcessEventData *data =
4145 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4146 if (data != nullptr)
4147 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004148}
4149
Kate Stoneb9c1b512016-09-06 20:57:50 +00004150bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4151 ProcessEventData *data =
4152 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4153 if (data) {
4154 data->SetUpdateStateOnRemoval();
4155 return true;
4156 }
4157 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004158}
4159
Jim Inghamb87b9e62018-06-26 23:38:58 +00004160lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004161
4162void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4163 exe_ctx.SetTargetPtr(&GetTarget());
4164 exe_ctx.SetProcessPtr(this);
4165 exe_ctx.SetThreadPtr(nullptr);
4166 exe_ctx.SetFramePtr(nullptr);
4167}
4168
4169// uint32_t
4170// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4171// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004172//{
4173// return 0;
4174//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004175//
4176// ArchSpec
4177// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004178//{
4179// return Host::GetArchSpecForExistingProcess (pid);
4180//}
4181//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004182// ArchSpec
4183// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004184//{
4185// return Host::GetArchSpecForExistingProcess (process_name);
4186//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004187
Kate Stoneb9c1b512016-09-06 20:57:50 +00004188void Process::AppendSTDOUT(const char *s, size_t len) {
4189 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4190 m_stdout_data.append(s, len);
4191 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4192 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004193}
4194
Kate Stoneb9c1b512016-09-06 20:57:50 +00004195void Process::AppendSTDERR(const char *s, size_t len) {
4196 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4197 m_stderr_data.append(s, len);
4198 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4199 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004200}
4201
Kate Stoneb9c1b512016-09-06 20:57:50 +00004202void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4203 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4204 m_profile_data.push_back(one_profile_data);
4205 BroadcastEventIfUnique(eBroadcastBitProfileData,
4206 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004207}
4208
Kate Stoneb9c1b512016-09-06 20:57:50 +00004209void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4210 const StructuredDataPluginSP &plugin_sp) {
4211 BroadcastEvent(
4212 eBroadcastBitStructuredData,
4213 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004214}
4215
4216StructuredDataPluginSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004217Process::GetStructuredDataPlugin(ConstString type_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004218 auto find_it = m_structured_data_plugin_map.find(type_name);
4219 if (find_it != m_structured_data_plugin_map.end())
4220 return find_it->second;
4221 else
4222 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004223}
4224
Zachary Turner97206d52017-05-12 04:51:55 +00004225size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004226 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4227 if (m_profile_data.empty())
4228 return 0;
4229
4230 std::string &one_profile_data = m_profile_data.front();
4231 size_t bytes_available = one_profile_data.size();
4232 if (bytes_available > 0) {
4233 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004234 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4235 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004236 if (bytes_available > buf_size) {
4237 memcpy(buf, one_profile_data.c_str(), buf_size);
4238 one_profile_data.erase(0, buf_size);
4239 bytes_available = buf_size;
4240 } else {
4241 memcpy(buf, one_profile_data.c_str(), bytes_available);
4242 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004243 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004244 }
4245 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004246}
4247
Greg Clayton93e86192011-11-13 04:45:22 +00004248// Process STDIO
Greg Clayton93e86192011-11-13 04:45:22 +00004249
Zachary Turner97206d52017-05-12 04:51:55 +00004250size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004251 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4252 size_t bytes_available = m_stdout_data.size();
4253 if (bytes_available > 0) {
4254 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004255 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4256 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004257 if (bytes_available > buf_size) {
4258 memcpy(buf, m_stdout_data.c_str(), buf_size);
4259 m_stdout_data.erase(0, buf_size);
4260 bytes_available = buf_size;
4261 } else {
4262 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4263 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004264 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004265 }
4266 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004267}
4268
Zachary Turner97206d52017-05-12 04:51:55 +00004269size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004270 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4271 size_t bytes_available = m_stderr_data.size();
4272 if (bytes_available > 0) {
4273 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004274 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4275 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004276 if (bytes_available > buf_size) {
4277 memcpy(buf, m_stderr_data.c_str(), buf_size);
4278 m_stderr_data.erase(0, buf_size);
4279 bytes_available = buf_size;
4280 } else {
4281 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4282 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004283 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004284 }
4285 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004286}
4287
Kate Stoneb9c1b512016-09-06 20:57:50 +00004288void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4289 size_t src_len) {
4290 Process *process = (Process *)baton;
4291 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004292}
4293
Kate Stoneb9c1b512016-09-06 20:57:50 +00004294class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004295public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004296 IOHandlerProcessSTDIO(Process *process, int write_fd)
4297 : IOHandler(process->GetTarget().GetDebugger(),
4298 IOHandler::Type::ProcessIO),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004299 m_process(process),
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00004300 m_read_file(GetInputFD(), File::eOpenOptionRead, false),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004301 m_write_file(write_fd, File::eOpenOptionWrite, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004302 m_pipe.CreateNew(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004303 }
4304
4305 ~IOHandlerProcessSTDIO() override = default;
4306
Adrian Prantl05097242018-04-30 16:49:04 +00004307 // Each IOHandler gets to run until it is done. It should read data from the
4308 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004309 void Run() override {
4310 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4311 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4312 SetIsDone(true);
4313 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004314 }
4315
Kate Stoneb9c1b512016-09-06 20:57:50 +00004316 SetIsDone(false);
4317 const int read_fd = m_read_file.GetDescriptor();
4318 TerminalState terminal_state;
4319 terminal_state.Save(read_fd, false);
4320 Terminal terminal(read_fd);
4321 terminal.SetCanonical(false);
4322 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004323// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004324#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004325 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4326 m_is_running = true;
4327 while (!GetIsDone()) {
4328 SelectHelper select_helper;
4329 select_helper.FDSetRead(read_fd);
4330 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004331 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004332
Kate Stoneb9c1b512016-09-06 20:57:50 +00004333 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004334 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004335 } else {
4336 char ch = 0;
4337 size_t n;
4338 if (select_helper.FDIsSetRead(read_fd)) {
4339 n = 1;
4340 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4341 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4342 SetIsDone(true);
4343 } else
4344 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004345 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004346 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4347 size_t bytes_read;
4348 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004349 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004350 if (error.Success()) {
4351 switch (ch) {
4352 case 'q':
4353 SetIsDone(true);
4354 break;
4355 case 'i':
4356 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004357 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004358 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004359 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004360 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004361 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004362 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004363 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004364 m_is_running = false;
4365#endif
4366 terminal_state.Restore();
4367 }
4368
4369 void Cancel() override {
4370 SetIsDone(true);
4371 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004372 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4373 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004374 //
4375 // (lldb) step_process_thousands_of_times
4376 //
4377 // In this case the command interpreter will be in the middle of handling
4378 // the command and if the process pushes and pops the IOHandler thousands
4379 // of times, we can end up writing to m_pipe without ever consuming the
4380 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4381 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4382 if (m_is_running) {
4383 char ch = 'q'; // Send 'q' for quit
4384 size_t bytes_written = 0;
4385 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004386 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004387 }
4388
4389 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004390 // Do only things that are safe to do in an interrupt context (like in a
4391 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004392 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4393 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004394 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004395 if (m_active) {
4396 char ch = 'i'; // Send 'i' for interrupt
4397 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004398 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004399 return result.Success();
4400 } else {
4401 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004402 // currently so do the right thing if we aren't actively watching for
4403 // STDIN by sending the interrupt to the process. Otherwise the write to
4404 // the pipe above would do nothing. This can happen when the command
4405 // interpreter is running and gets a "expression ...". It will be on the
4406 // IOHandler thread and sending the input is complete to the delegate
4407 // which will cause the expression to run, which will push the process IO
4408 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004409
4410 if (StateIsRunningState(m_process->GetState())) {
4411 m_process->SendAsyncInterrupt();
4412 return true;
4413 }
4414 }
4415 return false;
4416 }
4417
4418 void GotEOF() override {}
4419
Greg Clayton44d93782014-01-27 23:43:24 +00004420protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004421 Process *m_process;
Lawrence D'Annaf913fd62019-10-03 04:31:46 +00004422 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
4423 NativeFile m_write_file; // Write to this file (usually the master pty for
4424 // getting io to debuggee)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004425 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004426 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004427};
4428
Kate Stoneb9c1b512016-09-06 20:57:50 +00004429void Process::SetSTDIOFileDescriptor(int fd) {
4430 // First set up the Read Thread for reading/handling process I/O
4431
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004432 std::unique_ptr<ConnectionFileDescriptor> conn_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004433 new ConnectionFileDescriptor(fd, true));
4434
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004435 if (conn_up) {
4436 m_stdio_communication.SetConnection(conn_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004437 if (m_stdio_communication.IsConnected()) {
4438 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4439 STDIOReadThreadBytesReceived, this);
4440 m_stdio_communication.StartReadThread();
4441
4442 // Now read thread is set up, set up input reader.
4443
4444 if (!m_process_input_reader)
Jonas Devlieghere796ac802019-02-11 23:13:08 +00004445 m_process_input_reader =
4446 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004447 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004448 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004449}
4450
Kate Stoneb9c1b512016-09-06 20:57:50 +00004451bool Process::ProcessIOHandlerIsActive() {
4452 IOHandlerSP io_handler_sp(m_process_input_reader);
4453 if (io_handler_sp)
4454 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4455 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004456}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004457bool Process::PushProcessIOHandler() {
4458 IOHandlerSP io_handler_sp(m_process_input_reader);
4459 if (io_handler_sp) {
4460 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004461 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004462
Kate Stoneb9c1b512016-09-06 20:57:50 +00004463 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004464 // If we evaluate an utility function, then we don't cancel the current
4465 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4466 // existing IOHandler that potentially provides the user interface (e.g.
4467 // the IOHandler for Editline).
4468 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004469 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
4470 cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004471 return true;
4472 }
4473 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004474}
4475
Kate Stoneb9c1b512016-09-06 20:57:50 +00004476bool Process::PopProcessIOHandler() {
4477 IOHandlerSP io_handler_sp(m_process_input_reader);
4478 if (io_handler_sp)
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004479 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004480 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004481}
4482
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004483// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004484void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004485
Kate Stoneb9c1b512016-09-06 20:57:50 +00004486void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004487
Kate Stoneb9c1b512016-09-06 20:57:50 +00004488namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004489// RestorePlanState is used to record the "is private", "is master" and "okay
4490// to discard" fields of the plan we are running, and reset it on Clean or on
4491// destruction. It will only reset the state once, so you can call Clean and
4492// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004493
Kate Stoneb9c1b512016-09-06 20:57:50 +00004494class RestorePlanState {
4495public:
4496 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4497 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4498 if (m_thread_plan_sp) {
4499 m_private = m_thread_plan_sp->GetPrivate();
4500 m_is_master = m_thread_plan_sp->IsMasterPlan();
4501 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4502 }
4503 }
4504
4505 ~RestorePlanState() { Clean(); }
4506
4507 void Clean() {
4508 if (!m_already_reset && m_thread_plan_sp) {
4509 m_already_reset = true;
4510 m_thread_plan_sp->SetPrivate(m_private);
4511 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4512 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4513 }
4514 }
4515
4516private:
4517 lldb::ThreadPlanSP m_thread_plan_sp;
4518 bool m_already_reset;
4519 bool m_private;
4520 bool m_is_master;
4521 bool m_okay_to_discard;
4522};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004523} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004524
Pavel Labath2ce22162016-12-01 10:57:30 +00004525static microseconds
4526GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4527 const milliseconds default_one_thread_timeout(250);
4528
4529 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004530 if (!options.GetTimeout()) {
4531 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4532 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004533 }
4534
4535 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004536 if (options.GetOneThreadTimeout())
4537 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004538
4539 // Otherwise use half the total timeout, bounded by the
4540 // default_one_thread_timeout.
4541 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004542 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004543}
4544
4545static Timeout<std::micro>
4546GetExpressionTimeout(const EvaluateExpressionOptions &options,
4547 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004548 // If we are going to run all threads the whole time, or if we are only going
4549 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004550 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004551 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004552
4553 if (before_first_timeout)
4554 return GetOneThreadExpressionTimeout(options);
4555
Pavel Labath43d35412016-12-06 11:24:51 +00004556 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004557 return llvm::None;
4558 else
Pavel Labath43d35412016-12-06 11:24:51 +00004559 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004560}
4561
Pavel Labath45dde232017-05-25 10:50:06 +00004562static llvm::Optional<ExpressionResults>
4563HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4564 RestorePlanState &restorer, const EventSP &event_sp,
4565 EventSP &event_to_broadcast_sp,
4566 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4567 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4568
4569 ThreadPlanSP plan = thread.GetCompletedPlan();
4570 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4571 LLDB_LOG(log, "execution completed successfully");
4572
4573 // Restore the plan state so it will get reported as intended when we are
4574 // done.
4575 restorer.Clean();
4576 return eExpressionCompleted;
4577 }
4578
4579 StopInfoSP stop_info_sp = thread.GetStopInfo();
4580 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4581 stop_info_sp->ShouldNotify(event_sp.get())) {
4582 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4583 if (!options.DoesIgnoreBreakpoints()) {
4584 // Restore the plan state and then force Private to false. We are going
4585 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004586 // it won't report correctly when we continue to its termination later
4587 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004588 restorer.Clean();
4589 thread_plan_sp->SetPrivate(false);
4590 event_to_broadcast_sp = event_sp;
4591 }
4592 return eExpressionHitBreakpoint;
4593 }
4594
4595 if (!handle_interrupts &&
4596 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4597 return llvm::None;
4598
4599 LLDB_LOG(log, "thread plan did not successfully complete");
4600 if (!options.DoesUnwindOnError())
4601 event_to_broadcast_sp = event_sp;
4602 return eExpressionInterrupted;
4603}
4604
Jim Ingham1624a2d2014-05-05 02:26:40 +00004605ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004606Process::RunThreadPlan(ExecutionContext &exe_ctx,
4607 lldb::ThreadPlanSP &thread_plan_sp,
4608 const EvaluateExpressionOptions &options,
4609 DiagnosticManager &diagnostic_manager) {
4610 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004611
Kate Stoneb9c1b512016-09-06 20:57:50 +00004612 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4613
4614 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004615 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004616 eDiagnosticSeverityError,
4617 "RunThreadPlan called with empty thread plan.");
4618 return eExpressionSetupError;
4619 }
4620
4621 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004622 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004623 eDiagnosticSeverityError,
4624 "RunThreadPlan called with an invalid thread plan.");
4625 return eExpressionSetupError;
4626 }
4627
4628 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004629 diagnostic_manager.PutString(eDiagnosticSeverityError,
4630 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004631 return eExpressionSetupError;
4632 }
4633
4634 Thread *thread = exe_ctx.GetThreadPtr();
4635 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004636 diagnostic_manager.PutString(eDiagnosticSeverityError,
4637 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004638 return eExpressionSetupError;
4639 }
4640
4641 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004642 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004643
4644 RestorePlanState thread_plan_restorer(thread_plan_sp);
4645
Adrian Prantl05097242018-04-30 16:49:04 +00004646 // We rely on the thread plan we are running returning "PlanCompleted" if
4647 // when it successfully completes. For that to be true the plan can't be
4648 // private - since private plans suppress themselves in the GetCompletedPlan
4649 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004650
4651 thread_plan_sp->SetPrivate(false);
4652
4653 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004654 // when they are done we will end up asking the plan above us whether we
4655 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004656
4657 thread_plan_sp->SetIsMasterPlan(true);
4658 thread_plan_sp->SetOkayToDiscard(false);
4659
Raphael Isemannc01783a2018-08-29 22:50:54 +00004660 // If we are running some utility expression for LLDB, we now have to mark
4661 // this in the ProcesModID of this process. This RAII takes care of marking
4662 // and reverting the mark it once we are done running the expression.
4663 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4664
Kate Stoneb9c1b512016-09-06 20:57:50 +00004665 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004666 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004667 eDiagnosticSeverityError,
4668 "RunThreadPlan called while the private state was not stopped.");
4669 return eExpressionSetupError;
4670 }
4671
4672 // Save the thread & frame from the exe_ctx for restoration after we run
4673 const uint32_t thread_idx_id = thread->GetIndexID();
4674 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4675 if (!selected_frame_sp) {
4676 thread->SetSelectedFrame(nullptr);
4677 selected_frame_sp = thread->GetSelectedFrame();
4678 if (!selected_frame_sp) {
4679 diagnostic_manager.Printf(
4680 eDiagnosticSeverityError,
4681 "RunThreadPlan called without a selected frame on thread %d",
4682 thread_idx_id);
4683 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004684 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004685 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004686
Adrian Prantl05097242018-04-30 16:49:04 +00004687 // Make sure the timeout values make sense. The one thread timeout needs to
4688 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004689 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4690 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004691 diagnostic_manager.PutString(eDiagnosticSeverityError,
4692 "RunThreadPlan called with one thread "
4693 "timeout greater than total timeout");
4694 return eExpressionSetupError;
4695 }
4696
Kate Stoneb9c1b512016-09-06 20:57:50 +00004697 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004698
Kate Stoneb9c1b512016-09-06 20:57:50 +00004699 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004700 // We don't want to do that either, so we should arrange to reset them as
4701 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004702
Kate Stoneb9c1b512016-09-06 20:57:50 +00004703 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004704
Kate Stoneb9c1b512016-09-06 20:57:50 +00004705 uint32_t selected_tid;
4706 StackID selected_stack_id;
4707 if (selected_thread_sp) {
4708 selected_tid = selected_thread_sp->GetIndexID();
4709 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4710 } else {
4711 selected_tid = LLDB_INVALID_THREAD_ID;
4712 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004713
Kate Stoneb9c1b512016-09-06 20:57:50 +00004714 HostThread backup_private_state_thread;
4715 lldb::StateType old_state = eStateInvalid;
4716 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004717
Kate Stoneb9c1b512016-09-06 20:57:50 +00004718 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4719 LIBLLDB_LOG_PROCESS));
4720 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4721 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004722 // public events on this thread, since we are the thread that is generating
4723 // public events. The simplest thing to do is to spin up a temporary thread
4724 // to handle private state thread events while we are fielding public
4725 // events here.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004726 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4727 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004728
Kate Stoneb9c1b512016-09-06 20:57:50 +00004729 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004730
Kate Stoneb9c1b512016-09-06 20:57:50 +00004731 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004732 // anything it pushes, and then stop, returning control here. But in the
4733 // normal course of things, the plan above us on the stack would be given a
4734 // shot at the stop event before deciding to stop, and we don't want that.
4735 // So we insert a "stopper" base plan on the stack before the plan we want
4736 // to run. Since base plans always stop and return control to the user,
4737 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004738 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4739 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4740 // Have to make sure our public state is stopped, since otherwise the
4741 // reporting logic below doesn't work correctly.
4742 old_state = m_public_state.GetValue();
4743 m_public_state.SetValueNoLock(eStateStopped);
4744
4745 // Now spin up the private state thread:
4746 StartPrivateStateThread(true);
4747 }
4748
4749 thread->QueueThreadPlan(
4750 thread_plan_sp, false); // This used to pass "true" does that make sense?
4751
4752 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004753 // In this case, we aren't actually going to run, we just want to stop
4754 // right away. Flush this thread so we will refetch the stacks and show the
4755 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004756 // FIXME: To make this prettier we should invent some stop reason for this,
4757 // but that
4758 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004759 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004760 thread->Flush();
4761 return eExpressionStoppedForDebug;
4762 }
4763
4764 ListenerSP listener_sp(
4765 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4766
4767 lldb::EventSP event_to_broadcast_sp;
4768
4769 {
4770 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004771 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004772 //
4773 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004774 // exits during execution), then the event is put into
4775 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004776
4777 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4778
4779 if (log) {
4780 StreamString s;
4781 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004782 LLDB_LOGF(log,
4783 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4784 " to run thread plan \"%s\".",
4785 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004786 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004787
4788 bool got_event;
4789 lldb::EventSP event_sp;
4790 lldb::StateType stop_state = lldb::eStateInvalid;
4791
4792 bool before_first_timeout = true; // This is set to false the first time
4793 // that we have to halt the target.
4794 bool do_resume = true;
4795 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004796
4797 // This is just for accounting:
4798 uint32_t num_resumes = 0;
4799
Kate Stoneb9c1b512016-09-06 20:57:50 +00004800 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00004801 // going to run one thread, then we don't need the first timeout. So we
4802 // pretend we are after the first timeout already.
4803 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004804 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00004805
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004806 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4807 options.GetStopOthers(), options.GetTryAllThreads(),
4808 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004809
Adrian Prantl05097242018-04-30 16:49:04 +00004810 // This isn't going to work if there are unfetched events on the queue. Are
4811 // there cases where we might want to run the remaining events here, and
4812 // then try to call the function? That's probably being too tricky for our
4813 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004814
4815 Event *other_events = listener_sp->PeekAtNextEvent();
4816 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004817 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004818 eDiagnosticSeverityError,
4819 "RunThreadPlan called with pending events on the queue.");
4820 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00004821 }
4822
Kate Stoneb9c1b512016-09-06 20:57:50 +00004823 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00004824 // calling a function as part of a thread plan, in which case the last
4825 // delivered event could be the running event, and we don't want event
4826 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004827 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00004828
Kate Stoneb9c1b512016-09-06 20:57:50 +00004829// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00004830// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00004831
Kate Stoneb9c1b512016-09-06 20:57:50 +00004832#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00004833 // It's pretty much impossible to write test cases for things like: One
4834 // thread timeout expires, I go to halt, but the process already stopped on
4835 // the function call stop breakpoint. Turning on this define will make us
4836 // not fetch the first event till after the halt. So if you run a quick
4837 // function, it will have completed, and the completion event will be
4838 // waiting, when you interrupt for halt. The expression evaluation should
4839 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004840 bool miss_first_event = true;
4841#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00004842 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00004843 // We usually want to resume the process if we get to the top of the
4844 // loop. The only exception is if we get two running events with no
4845 // intervening stop, which can happen, we will just wait for then next
4846 // stop event.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004847 LLDB_LOGF(log,
4848 "Top of while loop: do_resume: %i handle_running_event: %i "
4849 "before_first_timeout: %i.",
4850 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00004851
Kate Stoneb9c1b512016-09-06 20:57:50 +00004852 if (do_resume || handle_running_event) {
4853 // Do the initial resume and wait for the running event before going
4854 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00004855
Kate Stoneb9c1b512016-09-06 20:57:50 +00004856 if (do_resume) {
4857 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00004858 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004859 if (!resume_error.Success()) {
4860 diagnostic_manager.Printf(
4861 eDiagnosticSeverityError,
4862 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4863 resume_error.AsCString());
4864 return_value = eExpressionSetupError;
4865 break;
4866 }
Jason Molendaef7d6412015-08-06 03:27:10 +00004867 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004868
Pavel Labathd35031e12016-11-30 10:41:42 +00004869 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00004870 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004871 if (!got_event) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004872 LLDB_LOGF(log,
4873 "Process::RunThreadPlan(): didn't get any event after "
4874 "resume %" PRIu32 ", exiting.",
4875 num_resumes);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004876
4877 diagnostic_manager.Printf(eDiagnosticSeverityError,
4878 "didn't get any event after resume %" PRIu32
4879 ", exiting.",
4880 num_resumes);
4881 return_value = eExpressionSetupError;
4882 break;
4883 }
4884
4885 stop_state =
4886 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4887
4888 if (stop_state != eStateRunning) {
4889 bool restarted = false;
4890
4891 if (stop_state == eStateStopped) {
4892 restarted = Process::ProcessEventData::GetRestartedFromEvent(
4893 event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004894 LLDB_LOGF(
4895 log,
4896 "Process::RunThreadPlan(): didn't get running event after "
4897 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4898 "handle_running_event: %i).",
4899 num_resumes, StateAsCString(stop_state), restarted, do_resume,
4900 handle_running_event);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004901 }
4902
4903 if (restarted) {
4904 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00004905 // should ever get a stopped & restarted event here. But if I do,
4906 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004907 const bool clear_thread_plans = false;
4908 const bool use_run_lock = false;
4909 Halt(clear_thread_plans, use_run_lock);
4910 }
4911
4912 diagnostic_manager.Printf(
4913 eDiagnosticSeverityError,
4914 "didn't get running event after initial resume, got %s instead.",
4915 StateAsCString(stop_state));
4916 return_value = eExpressionSetupError;
4917 break;
4918 }
4919
4920 if (log)
4921 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00004922 // We need to call the function synchronously, so spin waiting for it
4923 // to return. If we get interrupted while executing, we're going to
4924 // lose our context, and won't be able to gather the result at this
4925 // point. We set the timeout AFTER the resume, since the resume takes
4926 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004927 } else {
4928 if (log)
4929 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
4930 }
4931
Kate Stoneb9c1b512016-09-06 20:57:50 +00004932 do_resume = true;
4933 handle_running_event = true;
4934
4935 // Now wait for the process to stop again:
4936 event_sp.reset();
4937
Pavel Labath2ce22162016-12-01 10:57:30 +00004938 Timeout<std::micro> timeout =
4939 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004940 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004941 if (timeout) {
4942 auto now = system_clock::now();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004943 LLDB_LOGF(log,
4944 "Process::RunThreadPlan(): about to wait - now is %s - "
4945 "endpoint is %s",
4946 llvm::to_string(now).c_str(),
4947 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004948 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004949 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00004950 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004951 }
4952
4953#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4954 // See comment above...
4955 if (miss_first_event) {
Pavel Labath3d4f7652019-08-05 08:23:25 +00004956 std::this_thread::sleep_for(std::chrono::milliseconds(1));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004957 miss_first_event = false;
4958 got_event = false;
4959 } else
4960#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00004961 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004962
4963 if (got_event) {
4964 if (event_sp) {
4965 bool keep_going = false;
4966 if (event_sp->GetType() == eBroadcastBitInterrupt) {
4967 const bool clear_thread_plans = false;
4968 const bool use_run_lock = false;
4969 Halt(clear_thread_plans, use_run_lock);
4970 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00004971 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
4972 "execution halted by user interrupt.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004973 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
4974 "eBroadcastBitInterrupted, exiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004975 break;
4976 } else {
4977 stop_state =
4978 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004979 LLDB_LOGF(log,
4980 "Process::RunThreadPlan(): in while loop, got event: %s.",
4981 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004982
4983 switch (stop_state) {
4984 case lldb::eStateStopped: {
4985 // We stopped, figure out what we are going to do now.
4986 ThreadSP thread_sp =
4987 GetThreadList().FindThreadByIndexID(thread_idx_id);
4988 if (!thread_sp) {
4989 // Ooh, our thread has vanished. Unlikely that this was
4990 // successful execution...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004991 LLDB_LOGF(log,
4992 "Process::RunThreadPlan(): execution completed "
4993 "but our thread (index-id=%u) has vanished.",
4994 thread_idx_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004995 return_value = eExpressionInterrupted;
Pavel Labath45dde232017-05-25 10:50:06 +00004996 } else if (Process::ProcessEventData::GetRestartedFromEvent(
4997 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004998 // If we were restarted, we just need to go back up to fetch
4999 // another event.
Pavel Labath45dde232017-05-25 10:50:06 +00005000 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005001 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5002 "restart, so we'll continue waiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005003 }
Pavel Labath45dde232017-05-25 10:50:06 +00005004 keep_going = true;
5005 do_resume = false;
5006 handle_running_event = true;
5007 } else {
5008 const bool handle_interrupts = true;
5009 return_value = *HandleStoppedEvent(
5010 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5011 event_to_broadcast_sp, options, handle_interrupts);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005012 }
5013 } break;
5014
5015 case lldb::eStateRunning:
5016 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005017 // running events without an intervening stop, and in that case
5018 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005019 do_resume = false;
5020 keep_going = true;
5021 handle_running_event = false;
5022 break;
5023
5024 default:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005025 LLDB_LOGF(log,
5026 "Process::RunThreadPlan(): execution stopped with "
5027 "unexpected state: %s.",
5028 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005029
5030 if (stop_state == eStateExited)
5031 event_to_broadcast_sp = event_sp;
5032
Zachary Turnere2411fa2016-11-12 19:12:56 +00005033 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005034 eDiagnosticSeverityError,
5035 "execution stopped with unexpected state.");
5036 return_value = eExpressionInterrupted;
5037 break;
5038 }
5039 }
5040
5041 if (keep_going)
5042 continue;
5043 else
5044 break;
5045 } else {
5046 if (log)
5047 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5048 "the event pointer was null. How odd...");
5049 return_value = eExpressionInterrupted;
5050 break;
5051 }
5052 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005053 // If we didn't get an event that means we've timed out... We will
5054 // interrupt the process here. Depending on what we were asked to do
5055 // we will either exit, or try with all threads running for the same
5056 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005057
5058 if (log) {
5059 if (options.GetTryAllThreads()) {
5060 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005061 LLDB_LOG(log,
5062 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005063 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005064 LLDB_LOG(log, "Restarting function with all threads enabled and "
5065 "timeout: {0} timed out, abandoning execution.",
5066 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005067 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005068 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5069 "abandoning execution.",
5070 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005071 }
5072
5073 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005074 // around to calling Halt the target could have stopped. That's fine,
5075 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005076 // BUT it is also possible that we stopped & restarted (e.g. hit a
5077 // signal with "stop" set to false.) In
5078 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005079 // back to waiting for the Halt's stopped event. That's what this
5080 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005081
5082 bool back_to_top = true;
5083 uint32_t try_halt_again = 0;
5084 bool do_halt = true;
5085 const uint32_t num_retries = 5;
5086 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005087 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005088 if (do_halt) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005089 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005090 const bool clear_thread_plans = false;
5091 const bool use_run_lock = false;
5092 Halt(clear_thread_plans, use_run_lock);
5093 }
5094 if (halt_error.Success()) {
5095 if (log)
5096 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5097
Pavel Labathd35031e12016-11-30 10:41:42 +00005098 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00005099 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005100
5101 if (got_event) {
5102 stop_state =
5103 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5104 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005105 LLDB_LOGF(log,
5106 "Process::RunThreadPlan(): Stopped with event: %s",
5107 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005108 if (stop_state == lldb::eStateStopped &&
5109 Process::ProcessEventData::GetInterruptedFromEvent(
5110 event_sp.get()))
5111 log->PutCString(" Event was the Halt interruption event.");
5112 }
5113
5114 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005115 if (Process::ProcessEventData::GetRestartedFromEvent(
5116 event_sp.get())) {
5117 if (log)
5118 log->PutCString("Process::RunThreadPlan(): Went to halt "
5119 "but got a restarted event, there must be "
5120 "an un-restarted stopped event so try "
5121 "again... "
5122 "Exiting wait loop.");
5123 try_halt_again++;
5124 do_halt = false;
5125 continue;
5126 }
5127
Pavel Labath45dde232017-05-25 10:50:06 +00005128 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005129 // delivered it, the process could have already finished its
5130 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005131 const bool handle_interrupts = false;
5132 if (auto result = HandleStoppedEvent(
5133 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5134 event_to_broadcast_sp, options, handle_interrupts)) {
5135 return_value = *result;
5136 back_to_top = false;
5137 break;
5138 }
5139
Kate Stoneb9c1b512016-09-06 20:57:50 +00005140 if (!options.GetTryAllThreads()) {
5141 if (log)
5142 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5143 "was false, we stopped so now we're "
5144 "quitting.");
5145 return_value = eExpressionInterrupted;
5146 back_to_top = false;
5147 break;
5148 }
5149
5150 if (before_first_timeout) {
5151 // Set all the other threads to run, and return to the top of
5152 // the loop, which will continue;
5153 before_first_timeout = false;
5154 thread_plan_sp->SetStopOthers(false);
5155 if (log)
5156 log->PutCString(
5157 "Process::RunThreadPlan(): about to resume.");
5158
5159 back_to_top = true;
5160 break;
5161 } else {
5162 // Running all threads failed, so return Interrupted.
5163 if (log)
5164 log->PutCString("Process::RunThreadPlan(): running all "
5165 "threads timed out.");
5166 return_value = eExpressionInterrupted;
5167 back_to_top = false;
5168 break;
5169 }
5170 }
5171 } else {
5172 if (log)
5173 log->PutCString("Process::RunThreadPlan(): halt said it "
5174 "succeeded, but I got no event. "
5175 "I'm getting out of here passing Interrupted.");
5176 return_value = eExpressionInterrupted;
5177 back_to_top = false;
5178 break;
5179 }
5180 } else {
5181 try_halt_again++;
5182 continue;
5183 }
5184 }
5185
5186 if (!back_to_top || try_halt_again > num_retries)
5187 break;
5188 else
5189 continue;
5190 }
5191 } // END WAIT LOOP
5192
Adrian Prantl05097242018-04-30 16:49:04 +00005193 // If we had to start up a temporary private state thread to run this
5194 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005195 if (backup_private_state_thread.IsJoinable()) {
5196 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005197 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005198 m_private_state_thread = backup_private_state_thread;
5199 if (stopper_base_plan_sp) {
5200 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5201 }
5202 if (old_state != eStateInvalid)
5203 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005204 }
5205
Kate Stoneb9c1b512016-09-06 20:57:50 +00005206 if (return_value != eExpressionCompleted && log) {
5207 // Print a backtrace into the log so we can figure out where we are:
5208 StreamString s;
5209 s.PutCString("Thread state after unsuccessful completion: \n");
5210 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005211 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005212 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005213 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005214 // There are three cases where this could happen: 1) The execution
5215 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5216 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005217 bool should_unwind = (return_value == eExpressionInterrupted &&
5218 options.DoesUnwindOnError()) ||
5219 (return_value == eExpressionHitBreakpoint &&
5220 options.DoesIgnoreBreakpoints());
5221
5222 if (return_value == eExpressionCompleted || should_unwind) {
5223 thread_plan_sp->RestoreThreadState();
5224 }
5225
5226 // Now do some processing on the results of the run:
5227 if (return_value == eExpressionInterrupted ||
5228 return_value == eExpressionHitBreakpoint) {
5229 if (log) {
5230 StreamString s;
5231 if (event_sp)
5232 event_sp->Dump(&s);
5233 else {
5234 log->PutCString("Process::RunThreadPlan(): Stop event that "
5235 "interrupted us is NULL.");
5236 }
5237
5238 StreamString ts;
5239
5240 const char *event_explanation = nullptr;
5241
5242 do {
5243 if (!event_sp) {
5244 event_explanation = "<no event>";
5245 break;
5246 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5247 event_explanation = "<user interrupt>";
5248 break;
5249 } else {
5250 const Process::ProcessEventData *event_data =
5251 Process::ProcessEventData::GetEventDataFromEvent(
5252 event_sp.get());
5253
5254 if (!event_data) {
5255 event_explanation = "<no event data>";
5256 break;
5257 }
5258
5259 Process *process = event_data->GetProcessSP().get();
5260
5261 if (!process) {
5262 event_explanation = "<no process>";
5263 break;
5264 }
5265
5266 ThreadList &thread_list = process->GetThreadList();
5267
5268 uint32_t num_threads = thread_list.GetSize();
5269 uint32_t thread_index;
5270
5271 ts.Printf("<%u threads> ", num_threads);
5272
5273 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5274 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5275
5276 if (!thread) {
5277 ts.Printf("<?> ");
5278 continue;
5279 }
5280
5281 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5282 RegisterContext *register_context =
5283 thread->GetRegisterContext().get();
5284
5285 if (register_context)
5286 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5287 else
5288 ts.Printf("[ip unknown] ");
5289
5290 // Show the private stop info here, the public stop info will be
5291 // from the last natural stop.
5292 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5293 if (stop_info_sp) {
5294 const char *stop_desc = stop_info_sp->GetDescription();
5295 if (stop_desc)
5296 ts.PutCString(stop_desc);
5297 }
5298 ts.Printf(">");
5299 }
5300
5301 event_explanation = ts.GetData();
5302 }
Jonas Devlieghere09ad8c82019-05-24 00:44:33 +00005303 } while (false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005304
5305 if (event_explanation)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005306 LLDB_LOGF(log,
5307 "Process::RunThreadPlan(): execution interrupted: %s %s",
5308 s.GetData(), event_explanation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005309 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005310 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
5311 s.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005312 }
5313
5314 if (should_unwind) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005315 LLDB_LOGF(log,
5316 "Process::RunThreadPlan: ExecutionInterrupted - "
5317 "discarding thread plans up to %p.",
5318 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005319 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5320 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005321 LLDB_LOGF(log,
5322 "Process::RunThreadPlan: ExecutionInterrupted - for "
5323 "plan: %p not discarding.",
5324 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005325 }
5326 } else if (return_value == eExpressionSetupError) {
5327 if (log)
5328 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5329
5330 if (options.DoesUnwindOnError()) {
5331 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5332 }
5333 } else {
5334 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5335 if (log)
5336 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5337 return_value = eExpressionCompleted;
5338 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5339 if (log)
5340 log->PutCString(
5341 "Process::RunThreadPlan(): thread plan was discarded");
5342 return_value = eExpressionDiscarded;
5343 } else {
5344 if (log)
5345 log->PutCString(
5346 "Process::RunThreadPlan(): thread plan stopped in mid course");
5347 if (options.DoesUnwindOnError() && thread_plan_sp) {
5348 if (log)
5349 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5350 "'cause unwind_on_error is set.");
5351 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5352 }
5353 }
5354 }
5355
5356 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005357 // target Check that it's still there, and if it is put it back in the
5358 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005359 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5360 if (thread) {
5361 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5362 }
5363
5364 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005365 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005366
5367 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5368 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5369 selected_stack_id.IsValid()) {
5370 // We were able to restore the selected thread, now restore the frame:
5371 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5372 StackFrameSP old_frame_sp =
5373 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5374 selected_stack_id);
5375 if (old_frame_sp)
5376 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5377 old_frame_sp.get());
5378 }
5379 }
5380 }
5381
5382 // If the process exited during the run of the thread plan, notify everyone.
5383
5384 if (event_to_broadcast_sp) {
5385 if (log)
5386 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5387 BroadcastEvent(event_to_broadcast_sp);
5388 }
5389
5390 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005391}
5392
Kate Stoneb9c1b512016-09-06 20:57:50 +00005393const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5394 const char *result_name;
5395
5396 switch (result) {
5397 case eExpressionCompleted:
5398 result_name = "eExpressionCompleted";
5399 break;
5400 case eExpressionDiscarded:
5401 result_name = "eExpressionDiscarded";
5402 break;
5403 case eExpressionInterrupted:
5404 result_name = "eExpressionInterrupted";
5405 break;
5406 case eExpressionHitBreakpoint:
5407 result_name = "eExpressionHitBreakpoint";
5408 break;
5409 case eExpressionSetupError:
5410 result_name = "eExpressionSetupError";
5411 break;
5412 case eExpressionParseError:
5413 result_name = "eExpressionParseError";
5414 break;
5415 case eExpressionResultUnavailable:
5416 result_name = "eExpressionResultUnavailable";
5417 break;
5418 case eExpressionTimedOut:
5419 result_name = "eExpressionTimedOut";
5420 break;
5421 case eExpressionStoppedForDebug:
5422 result_name = "eExpressionStoppedForDebug";
5423 break;
5424 }
5425 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005426}
5427
Kate Stoneb9c1b512016-09-06 20:57:50 +00005428void Process::GetStatus(Stream &strm) {
5429 const StateType state = GetState();
5430 if (StateIsStoppedState(state, false)) {
5431 if (state == eStateExited) {
5432 int exit_status = GetExitStatus();
5433 const char *exit_description = GetExitDescription();
5434 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5435 GetID(), exit_status, exit_status,
5436 exit_description ? exit_description : "");
5437 } else {
5438 if (state == eStateConnected)
5439 strm.Printf("Connected to remote target.\n");
5440 else
5441 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5442 }
5443 } else {
5444 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5445 }
Pavel Labatha933d512016-04-05 13:07:16 +00005446}
5447
Kate Stoneb9c1b512016-09-06 20:57:50 +00005448size_t Process::GetThreadStatus(Stream &strm,
5449 bool only_threads_with_stop_reason,
5450 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005451 uint32_t num_frames_with_source,
5452 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005453 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005454
Kate Stoneb9c1b512016-09-06 20:57:50 +00005455 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005456 // very well might run code (e.g. if we need it to get return values or
5457 // arguments.) For that to work the process has to be able to acquire it.
5458 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005459
5460 uint32_t num_threads;
5461 std::vector<lldb::tid_t> thread_id_array;
5462 // Scope for thread list locker;
5463 {
5464 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5465 ThreadList &curr_thread_list = GetThreadList();
5466 num_threads = curr_thread_list.GetSize();
5467 uint32_t idx;
5468 thread_id_array.resize(num_threads);
5469 for (idx = 0; idx < num_threads; ++idx)
5470 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5471 }
5472
5473 for (uint32_t i = 0; i < num_threads; i++) {
5474 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5475 if (thread_sp) {
5476 if (only_threads_with_stop_reason) {
5477 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5478 if (!stop_info_sp || !stop_info_sp->IsValid())
5479 continue;
5480 }
5481 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005482 num_frames_with_source,
5483 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005484 ++num_thread_infos_dumped;
5485 } else {
5486 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005487 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
5488 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005489 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005490 }
5491 return num_thread_infos_dumped;
5492}
5493
5494void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5495 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5496}
5497
5498bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5499 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5500 region.GetByteSize());
5501}
5502
5503void Process::AddPreResumeAction(PreResumeActionCallback callback,
5504 void *baton) {
5505 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5506}
5507
5508bool Process::RunPreResumeActions() {
5509 bool result = true;
5510 while (!m_pre_resume_actions.empty()) {
5511 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5512 m_pre_resume_actions.pop_back();
5513 bool this_result = action.callback(action.baton);
5514 if (result)
5515 result = this_result;
5516 }
5517 return result;
5518}
5519
5520void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5521
Jim Inghamffd91752016-10-20 22:50:00 +00005522void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5523{
5524 PreResumeCallbackAndBaton element(callback, baton);
5525 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5526 if (found_iter != m_pre_resume_actions.end())
5527 {
5528 m_pre_resume_actions.erase(found_iter);
5529 }
5530}
5531
Kate Stoneb9c1b512016-09-06 20:57:50 +00005532ProcessRunLock &Process::GetRunLock() {
5533 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5534 return m_private_run_lock;
5535 else
5536 return m_public_run_lock;
5537}
5538
Jim Ingham58c3235e2019-10-01 00:47:25 +00005539bool Process::CurrentThreadIsPrivateStateThread()
5540{
5541 return m_private_state_thread.EqualsThread(Host::GetCurrentThread());
5542}
5543
5544
Kate Stoneb9c1b512016-09-06 20:57:50 +00005545void Process::Flush() {
5546 m_thread_list.Flush();
5547 m_extended_thread_list.Flush();
5548 m_extended_thread_stop_id = 0;
5549 m_queue_list.Clear();
5550 m_queue_list_stop_id = 0;
5551}
5552
5553void Process::DidExec() {
5554 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005555 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005556
5557 Target &target = GetTarget();
5558 target.CleanupProcess();
5559 target.ClearModules(false);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005560 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005561 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005562 m_system_runtime_up.reset();
5563 m_os_up.reset();
5564 m_dyld_up.reset();
5565 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005566 m_image_tokens.clear();
5567 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +00005568 {
5569 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5570 m_language_runtimes.clear();
5571 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005572 m_instrumentation_runtimes.clear();
5573 m_thread_list.DiscardThreadPlans();
5574 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005575 DoDidExec();
5576 CompleteAttach();
5577 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005578 // CompleteAttach() in case the dynamic loader loaded things in new
5579 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005580 Flush();
5581
Adrian Prantl05097242018-04-30 16:49:04 +00005582 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5583 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005584 target.DidExec();
5585}
5586
Zachary Turner97206d52017-05-12 04:51:55 +00005587addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005588 if (address == nullptr) {
5589 error.SetErrorString("Invalid address argument");
5590 return LLDB_INVALID_ADDRESS;
5591 }
5592
5593 addr_t function_addr = LLDB_INVALID_ADDRESS;
5594
5595 addr_t addr = address->GetLoadAddress(&GetTarget());
5596 std::map<addr_t, addr_t>::const_iterator iter =
5597 m_resolved_indirect_addresses.find(addr);
5598 if (iter != m_resolved_indirect_addresses.end()) {
5599 function_addr = (*iter).second;
5600 } else {
Alex Langford5b2b38e2019-09-13 00:02:05 +00005601 if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005602 Symbol *symbol = address->CalculateSymbolContextSymbol();
5603 error.SetErrorStringWithFormat(
5604 "Unable to call resolver for indirect function %s",
5605 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5606 function_addr = LLDB_INVALID_ADDRESS;
5607 } else {
5608 m_resolved_indirect_addresses.insert(
5609 std::pair<addr_t, addr_t>(addr, function_addr));
5610 }
5611 }
5612 return function_addr;
5613}
5614
5615void Process::ModulesDidLoad(ModuleList &module_list) {
5616 SystemRuntime *sys_runtime = GetSystemRuntime();
5617 if (sys_runtime) {
5618 sys_runtime->ModulesDidLoad(module_list);
5619 }
5620
5621 GetJITLoaders().ModulesDidLoad(module_list);
5622
5623 // Give runtimes a chance to be created.
5624 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5625 m_instrumentation_runtimes);
5626
5627 // Tell runtimes about new modules.
5628 for (auto pos = m_instrumentation_runtimes.begin();
5629 pos != m_instrumentation_runtimes.end(); ++pos) {
5630 InstrumentationRuntimeSP runtime = pos->second;
5631 runtime->ModulesDidLoad(module_list);
5632 }
5633
Adrian Prantl05097242018-04-30 16:49:04 +00005634 // Let any language runtimes we have already created know about the modules
5635 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005636
Adrian Prantl05097242018-04-30 16:49:04 +00005637 // Iterate over a copy of this language runtime list in case the language
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005638 // runtime ModulesDidLoad somehow causes the language runtime to be
Adrian Prantl05097242018-04-30 16:49:04 +00005639 // unloaded.
Alex Langford74eb76f2019-05-22 23:01:18 +00005640 {
5641 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5642 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5643 for (const auto &pair : language_runtimes) {
5644 // We must check language_runtime_sp to make sure it is not nullptr as we
5645 // might cache the fact that we didn't have a language runtime for a
5646 // language.
5647 LanguageRuntimeSP language_runtime_sp = pair.second;
5648 if (language_runtime_sp)
5649 language_runtime_sp->ModulesDidLoad(module_list);
5650 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005651 }
5652
5653 // If we don't have an operating system plug-in, try to load one since
5654 // loading shared libraries might cause a new one to try and load
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005655 if (!m_os_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005656 LoadOperatingSystemPlugin(false);
5657
5658 // Give structured-data plugins a chance to see the modified modules.
5659 for (auto pair : m_structured_data_plugin_map) {
5660 if (pair.second)
5661 pair.second->ModulesDidLoad(*this, module_list);
5662 }
5663}
5664
5665void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5666 const char *fmt, ...) {
5667 bool print_warning = true;
5668
5669 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5670 if (!stream_sp)
5671 return;
5672 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5673 return;
5674 }
5675
5676 if (repeat_key != nullptr) {
5677 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5678 if (it == m_warnings_issued.end()) {
5679 m_warnings_issued[warning_type] = WarningsPointerSet();
5680 m_warnings_issued[warning_type].insert(repeat_key);
5681 } else {
5682 if (it->second.find(repeat_key) != it->second.end()) {
5683 print_warning = false;
5684 } else {
5685 it->second.insert(repeat_key);
5686 }
5687 }
5688 }
5689
5690 if (print_warning) {
5691 va_list args;
5692 va_start(args, fmt);
5693 stream_sp->PrintfVarArg(fmt, args);
5694 va_end(args);
5695 }
5696}
5697
5698void Process::PrintWarningOptimization(const SymbolContext &sc) {
5699 if (GetWarningsOptimization() && sc.module_sp &&
5700 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5701 sc.function->GetIsOptimized()) {
5702 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5703 "%s was compiled with optimization - stepping may behave "
5704 "oddly; variables may not be available.\n",
5705 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5706 }
5707}
5708
5709bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5710 info.Clear();
5711
5712 PlatformSP platform_sp = GetTarget().GetPlatform();
5713 if (!platform_sp)
5714 return false;
5715
5716 return platform_sp->GetProcessInfo(GetID(), info);
5717}
5718
5719ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5720 ThreadCollectionSP threads;
5721
5722 const MemoryHistorySP &memory_history =
5723 MemoryHistory::FindPlugin(shared_from_this());
5724
5725 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005726 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005727 }
5728
Jonas Devlieghere796ac802019-02-11 23:13:08 +00005729 threads = std::make_shared<ThreadCollection>(
5730 memory_history->GetHistoryThreads(addr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005731
5732 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005733}
Kuba Brecka63927542014-10-11 01:59:32 +00005734
5735InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005736Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5737 InstrumentationRuntimeCollection::iterator pos;
5738 pos = m_instrumentation_runtimes.find(type);
5739 if (pos == m_instrumentation_runtimes.end()) {
5740 return InstrumentationRuntimeSP();
5741 } else
5742 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005743}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005744
Kate Stoneb9c1b512016-09-06 20:57:50 +00005745bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5746 const ArchSpec &arch, ModuleSpec &module_spec) {
5747 module_spec.Clear();
5748 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005749}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005750
Kate Stoneb9c1b512016-09-06 20:57:50 +00005751size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5752 m_image_tokens.push_back(image_ptr);
5753 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005754}
5755
Kate Stoneb9c1b512016-09-06 20:57:50 +00005756lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5757 if (token < m_image_tokens.size())
5758 return m_image_tokens[token];
5759 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005760}
5761
Kate Stoneb9c1b512016-09-06 20:57:50 +00005762void Process::ResetImageToken(size_t token) {
5763 if (token < m_image_tokens.size())
5764 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005765}
Jason Molendafd4cea52016-01-08 21:40:11 +00005766
5767Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005768Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5769 AddressRange range_bounds) {
5770 Target &target = GetTarget();
5771 DisassemblerSP disassembler_sp;
5772 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005773
Kate Stoneb9c1b512016-09-06 20:57:50 +00005774 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005775
Kate Stoneb9c1b512016-09-06 20:57:50 +00005776 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005777 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005778 if (!default_stop_addr.IsValid())
5779 return retval;
5780
5781 ExecutionContext exe_ctx(this);
5782 const char *plugin_name = nullptr;
5783 const char *flavor = nullptr;
5784 const bool prefer_file_cache = true;
5785 disassembler_sp = Disassembler::DisassembleRange(
5786 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
5787 prefer_file_cache);
5788 if (disassembler_sp)
5789 insn_list = &disassembler_sp->GetInstructionList();
5790
5791 if (insn_list == nullptr) {
5792 return retval;
5793 }
5794
5795 size_t insn_offset =
5796 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5797 if (insn_offset == UINT32_MAX) {
5798 return retval;
5799 }
5800
5801 uint32_t branch_index =
Greg Claytondf225762019-05-09 20:39:34 +00005802 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target,
Jim Ingham434905b2019-12-16 17:38:13 -08005803 false /* ignore_calls*/,
5804 nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005805 if (branch_index == UINT32_MAX) {
5806 return retval;
5807 }
5808
5809 if (branch_index > insn_offset) {
5810 Address next_branch_insn_address =
5811 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5812 if (next_branch_insn_address.IsValid() &&
5813 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5814 retval = next_branch_insn_address;
5815 }
5816 }
5817
5818 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00005819}
Howard Hellyerad007562016-07-07 08:21:28 +00005820
Zachary Turner97206d52017-05-12 04:51:55 +00005821Status
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005822Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00005823
Zachary Turner97206d52017-05-12 04:51:55 +00005824 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00005825
Kate Stoneb9c1b512016-09-06 20:57:50 +00005826 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00005827
Kate Stoneb9c1b512016-09-06 20:57:50 +00005828 region_list.clear();
5829 do {
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005830 lldb_private::MemoryRegionInfo region_info;
5831 error = GetMemoryRegionInfo(range_end, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005832 // GetMemoryRegionInfo should only return an error if it is unimplemented.
5833 if (error.Fail()) {
5834 region_list.clear();
5835 break;
Todd Fiala75930012016-08-19 04:21:48 +00005836 }
5837
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005838 range_end = region_info.GetRange().GetRangeEnd();
5839 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5840 region_list.push_back(std::move(region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005841 }
5842 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00005843
Kate Stoneb9c1b512016-09-06 20:57:50 +00005844 return error;
5845}
5846
Zachary Turner97206d52017-05-12 04:51:55 +00005847Status
Adrian Prantl0e4c4822019-03-06 21:22:25 +00005848Process::ConfigureStructuredData(ConstString type_name,
Zachary Turner97206d52017-05-12 04:51:55 +00005849 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005850 // If you get this, the Process-derived class needs to implement a method to
5851 // enable an already-reported asynchronous structured data feature. See
5852 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00005853 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005854}
5855
5856void Process::MapSupportedStructuredDataPlugins(
5857 const StructuredData::Array &supported_type_names) {
5858 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5859
5860 // Bail out early if there are no type names to map.
5861 if (supported_type_names.GetSize() == 0) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005862 LLDB_LOGF(log, "Process::%s(): no structured data types supported",
5863 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005864 return;
5865 }
Todd Fiala75930012016-08-19 04:21:48 +00005866
Kate Stoneb9c1b512016-09-06 20:57:50 +00005867 // Convert StructuredData type names to ConstString instances.
5868 std::set<ConstString> const_type_names;
5869
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005870 LLDB_LOGF(log,
5871 "Process::%s(): the process supports the following async "
5872 "structured data types:",
5873 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005874
5875 supported_type_names.ForEach(
5876 [&const_type_names, &log](StructuredData::Object *object) {
5877 if (!object) {
5878 // Invalid - shouldn't be null objects in the array.
5879 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005880 }
5881
5882 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005883 if (!type_name) {
5884 // Invalid format - all type names should be strings.
5885 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005886 }
5887
5888 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00005889 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00005890 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005891 });
Todd Fiala75930012016-08-19 04:21:48 +00005892
Adrian Prantl05097242018-04-30 16:49:04 +00005893 // For each StructuredDataPlugin, if the plugin handles any of the types in
5894 // the supported_type_names, map that type name to that plugin. Stop when
5895 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005896 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00005897 // supports?
5898 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
5899 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00005900 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
5901 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00005902 if (!create_instance)
5903 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005904
Kate Stoneb9c1b512016-09-06 20:57:50 +00005905 // Create the plugin.
5906 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
5907 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005908 // This plugin doesn't think it can work with the process. Move on to the
5909 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005910 continue;
Todd Fiala75930012016-08-19 04:21:48 +00005911 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005912
Adrian Prantl05097242018-04-30 16:49:04 +00005913 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005914 std::vector<ConstString> names_to_remove;
5915 for (auto &type_name : const_type_names) {
5916 if (plugin_sp->SupportsStructuredDataType(type_name)) {
5917 m_structured_data_plugin_map.insert(
5918 std::make_pair(type_name, plugin_sp));
5919 names_to_remove.push_back(type_name);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005920 LLDB_LOGF(log,
5921 "Process::%s(): using plugin %s for type name "
5922 "%s",
5923 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
5924 type_name.GetCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005925 }
5926 }
5927
5928 // Remove the type names that were consumed by this plugin.
5929 for (auto &type_name : names_to_remove)
5930 const_type_names.erase(type_name);
5931 }
Todd Fiala75930012016-08-19 04:21:48 +00005932}
5933
Kate Stoneb9c1b512016-09-06 20:57:50 +00005934bool Process::RouteAsyncStructuredData(
5935 const StructuredData::ObjectSP object_sp) {
5936 // Nothing to do if there's no data.
5937 if (!object_sp)
5938 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005939
Adrian Prantl05097242018-04-30 16:49:04 +00005940 // The contract is this must be a dictionary, so we can look up the routing
5941 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005942 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
5943 if (!dictionary)
5944 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005945
Kate Stoneb9c1b512016-09-06 20:57:50 +00005946 // Grab the async structured type name (i.e. the feature/plugin name).
5947 ConstString type_name;
5948 if (!dictionary->GetValueForKeyAsString("type", type_name))
5949 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005950
Kate Stoneb9c1b512016-09-06 20:57:50 +00005951 // Check if there's a plugin registered for this type name.
5952 auto find_it = m_structured_data_plugin_map.find(type_name);
5953 if (find_it == m_structured_data_plugin_map.end()) {
5954 // We don't have a mapping for this structured data type.
5955 return false;
5956 }
Todd Fiala75930012016-08-19 04:21:48 +00005957
Kate Stoneb9c1b512016-09-06 20:57:50 +00005958 // Route the structured data to the plugin.
5959 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
5960 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00005961}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005962
Zachary Turner97206d52017-05-12 04:51:55 +00005963Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005964 // Default implementation does nothign.
5965 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00005966 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005967}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005968
Frederic Rissd10d3792018-05-11 18:21:11 +00005969UtilityFunction *Process::GetLoadImageUtilityFunction(
5970 Platform *platform,
5971 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005972 if (platform != GetTarget().GetPlatform().get())
5973 return nullptr;
Michal Gorny3276fff2019-09-03 12:31:24 +00005974 llvm::call_once(m_dlopen_utility_func_flag_once,
5975 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005976 return m_dlopen_utility_func_up.get();
5977}
Alex Langford5b2b38e2019-09-13 00:02:05 +00005978
5979bool Process::CallVoidArgVoidPtrReturn(const Address *address,
5980 addr_t &returned_func,
5981 bool trap_exceptions) {
5982 Thread *thread = GetThreadList().GetExpressionExecutionThread().get();
5983 if (thread == nullptr || address == nullptr)
5984 return false;
5985
5986 EvaluateExpressionOptions options;
5987 options.SetStopOthers(true);
5988 options.SetUnwindOnError(true);
5989 options.SetIgnoreBreakpoints(true);
5990 options.SetTryAllThreads(true);
5991 options.SetDebug(false);
5992 options.SetTimeout(GetUtilityExpressionTimeout());
5993 options.SetTrapExceptions(trap_exceptions);
5994
5995 auto type_system_or_err =
5996 GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC);
5997 if (!type_system_or_err) {
5998 llvm::consumeError(type_system_or_err.takeError());
5999 return false;
6000 }
6001 CompilerType void_ptr_type =
6002 type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
6003 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction(
6004 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
6005 if (call_plan_sp) {
6006 DiagnosticManager diagnostics;
6007
6008 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6009 if (frame) {
6010 ExecutionContext exe_ctx;
6011 frame->CalculateExecutionContext(exe_ctx);
6012 ExpressionResults result =
6013 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
6014 if (result == eExpressionCompleted) {
6015 returned_func =
6016 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6017 LLDB_INVALID_ADDRESS);
6018
6019 if (GetAddressByteSize() == 4) {
6020 if (returned_func == UINT32_MAX)
6021 return false;
6022 } else if (GetAddressByteSize() == 8) {
6023 if (returned_func == UINT64_MAX)
6024 return false;
6025 }
6026 return true;
6027 }
6028 }
6029 }
6030
6031 return false;
6032}