blob: aa9cd31fec502167016cec4b427033d95857a79e [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
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"
Greg Clayton8f343b02010-11-04 01:54:29 +000041#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000042#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000043#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000044#include "lldb/Target/JITLoaderList.h"
Alex Langford03e1a822019-05-29 18:08:22 +000045#include "lldb/Target/Language.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000046#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000047#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000048#include "lldb/Target/MemoryRegionInfo.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000049#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000050#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000051#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000052#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000053#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000054#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000055#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056#include "lldb/Target/Target.h"
57#include "lldb/Target/TargetList.h"
58#include "lldb/Target/Thread.h"
59#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000060#include "lldb/Target/ThreadPlanBase.h"
Alex Langford5b2b38e2019-09-13 00:02:05 +000061#include "lldb/Target/ThreadPlanCallFunction.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000062#include "lldb/Target/UnixSignals.h"
Pavel Labath181b8232018-12-14 15:59:49 +000063#include "lldb/Utility/Event.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000064#include "lldb/Utility/Log.h"
Zachary Turner50232572015-03-18 21:31:45 +000065#include "lldb/Utility/NameMatches.h"
Zachary Turner805e7102019-03-04 21:51:03 +000066#include "lldb/Utility/ProcessInfo.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000067#include "lldb/Utility/SelectHelper.h"
Pavel Labathd821c992018-08-07 11:07:21 +000068#include "lldb/Utility/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000069
70using namespace lldb;
71using namespace lldb_private;
Pavel Labathe3e21cf2016-11-30 11:56:32 +000072using namespace std::chrono;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073
Kate Stoneb9c1b512016-09-06 20:57:50 +000074// Comment out line below to disable memory caching, overriding the process
Pavel Labath43d35412016-12-06 11:24:51 +000075// setting target.process.disable-memory-cache
Greg Clayton67cc0632012-08-22 17:17:09 +000076#define ENABLE_MEMORY_CACHING
77
78#ifdef ENABLE_MEMORY_CACHING
79#define DISABLE_MEM_CACHE_DEFAULT false
80#else
81#define DISABLE_MEM_CACHE_DEFAULT true
82#endif
83
Kate Stoneb9c1b512016-09-06 20:57:50 +000084class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000085public:
Adrian Prantl0e4c4822019-03-06 21:22:25 +000086 ProcessOptionValueProperties(ConstString name)
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 : OptionValueProperties(name) {}
88
Adrian Prantl05097242018-04-30 16:49:04 +000089 // This constructor is used when creating ProcessOptionValueProperties when
90 // it is part of a new lldb_private::Process instance. It will copy all
91 // current global property values as needed
Kate Stoneb9c1b512016-09-06 20:57:50 +000092 ProcessOptionValueProperties(ProcessProperties *global_properties)
93 : OptionValueProperties(*global_properties->GetValueProperties()) {}
94
95 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
96 bool will_modify,
97 uint32_t idx) const override {
Adrian Prantl05097242018-04-30 16:49:04 +000098 // When getting the value for a key from the process options, we will
99 // always try and grab the setting from the current process if there is
100 // one. Else we just use the one from this instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101 if (exe_ctx) {
102 Process *process = exe_ctx->GetProcessPtr();
103 if (process) {
104 ProcessOptionValueProperties *instance_properties =
105 static_cast<ProcessOptionValueProperties *>(
106 process->GetValueProperties().get());
107 if (this != instance_properties)
108 return instance_properties->ProtectedGetPropertyAtIndex(idx);
109 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000110 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111 return ProtectedGetPropertyAtIndex(idx);
112 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000113};
114
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000115#define LLDB_PROPERTIES_process
Jordan Rupprecht6a253d32019-07-29 17:22:10 +0000116#include "TargetProperties.inc"
Greg Clayton67cc0632012-08-22 17:17:09 +0000117
118enum {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000119#define LLDB_PROPERTIES_process
Jordan Rupprecht6a253d32019-07-29 17:22:10 +0000120#include "TargetPropertiesEnum.inc"
Greg Clayton67cc0632012-08-22 17:17:09 +0000121};
122
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123ProcessProperties::ProcessProperties(lldb_private::Process *process)
124 : Properties(),
125 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000126{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127 if (process == nullptr) {
128 // Global process properties, set them up one time
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000129 m_collection_sp =
130 std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000131 m_collection_sp->Initialize(g_process_properties);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 m_collection_sp->AppendProperty(
133 ConstString("thread"), ConstString("Settings specific to threads."),
134 true, Thread::GetGlobalProperties()->GetValueProperties());
135 } else {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000136 m_collection_sp = std::make_shared<ProcessOptionValueProperties>(
137 Process::GetGlobalProperties().get());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138 m_collection_sp->SetValueChangedCallback(
139 ePropertyPythonOSPluginPath,
Pavel Labath5c4661b2020-01-09 14:14:54 +0100140 [this] { m_process->LoadOperatingSystemPlugin(true); });
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000142}
143
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000144ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146bool ProcessProperties::GetDisableMemoryCache() const {
147 const uint32_t idx = ePropertyDisableMemCache;
148 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000149 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000150}
151
Kate Stoneb9c1b512016-09-06 20:57:50 +0000152uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
153 const uint32_t idx = ePropertyMemCacheLineSize;
154 return m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000155 nullptr, idx, g_process_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000156}
157
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158Args ProcessProperties::GetExtraStartupCommands() const {
159 Args args;
160 const uint32_t idx = ePropertyExtraStartCommand;
161 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
162 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000163}
164
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165void ProcessProperties::SetExtraStartupCommands(const Args &args) {
166 const uint32_t idx = ePropertyExtraStartCommand;
167 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000168}
169
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170FileSpec ProcessProperties::GetPythonOSPluginPath() const {
171 const uint32_t idx = ePropertyPythonOSPluginPath;
172 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000173}
174
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
176 const uint32_t idx = ePropertyPythonOSPluginPath;
177 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000178}
179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
181 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
182 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000183 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000184}
185
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
187 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
188 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000189}
190
Kate Stoneb9c1b512016-09-06 20:57:50 +0000191bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
192 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
193 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000194 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000195}
196
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
198 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
199 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000200}
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
203 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
204 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000205 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000206}
207
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
209 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
210 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
211}
212
213bool ProcessProperties::GetDetachKeepsStopped() const {
214 const uint32_t idx = ePropertyDetachKeepsStopped;
215 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000216 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217}
218
219void ProcessProperties::SetDetachKeepsStopped(bool stop) {
220 const uint32_t idx = ePropertyDetachKeepsStopped;
221 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
222}
223
224bool ProcessProperties::GetWarningsOptimization() const {
225 const uint32_t idx = ePropertyWarningOptimization;
226 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000227 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228}
229
Jim Inghamba205c12017-12-05 02:50:45 +0000230bool ProcessProperties::GetStopOnExec() const {
231 const uint32_t idx = ePropertyStopOnExec;
232 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000233 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Inghamba205c12017-12-05 02:50:45 +0000234}
235
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000236std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
237 const uint32_t idx = ePropertyUtilityExpressionTimeout;
238 uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000239 nullptr, idx, g_process_properties[idx].default_uint_value);
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000240 return std::chrono::seconds(value);
241}
242
Zachary Turner97206d52017-05-12 04:51:55 +0000243Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000244 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000246 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247 const int short_option = m_getopt_table[option_idx].val;
248
249 switch (short_option) {
250 case 's': // Stop at program entry point
251 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
252 break;
253
254 case 'i': // STDIN for read only
255 {
256 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000257 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258 launch_info.AppendFileAction(action);
259 break;
260 }
261
262 case 'o': // Open STDOUT for write only
263 {
264 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000265 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000266 launch_info.AppendFileAction(action);
267 break;
268 }
269
270 case 'e': // STDERR for write only
271 {
272 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000273 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274 launch_info.AppendFileAction(action);
275 break;
276 }
277
278 case 'p': // Process plug-in name
279 launch_info.SetProcessPluginName(option_arg);
280 break;
281
282 case 'n': // Disable STDIO
283 {
284 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000285 const FileSpec dev_null(FileSystem::DEV_NULL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286 if (action.Open(STDIN_FILENO, dev_null, true, false))
287 launch_info.AppendFileAction(action);
288 if (action.Open(STDOUT_FILENO, dev_null, false, true))
289 launch_info.AppendFileAction(action);
290 if (action.Open(STDERR_FILENO, dev_null, false, true))
291 launch_info.AppendFileAction(action);
292 break;
293 }
294
295 case 'w':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000296 launch_info.SetWorkingDirectory(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 break;
298
299 case 't': // Open process in new terminal window
300 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
301 break;
302
303 case 'a': {
304 TargetSP target_sp =
305 execution_context ? execution_context->GetTargetSP() : TargetSP();
306 PlatformSP platform_sp =
307 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000308 launch_info.GetArchitecture() =
309 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000310 } break;
311
312 case 'A': // Disable ASLR.
313 {
314 bool success;
315 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000316 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317 if (success)
318 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000319 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 error.SetErrorStringWithFormat(
321 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000322 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 break;
324 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000325
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 case 'X': // shell expand args.
327 {
328 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000329 const bool expand_args =
330 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 if (success)
332 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000333 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000334 error.SetErrorStringWithFormat(
335 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000336 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 break;
338 }
339
340 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000341 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000342 launch_info.SetShell(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 else
344 launch_info.SetShell(HostInfo::GetDefaultShell());
345 break;
346
347 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000348 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 break;
350
351 default:
352 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
353 short_option);
354 break;
355 }
356 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000357}
358
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000359static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000361 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 "Stop at the entry point of the program when launching a process."},
363 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000364 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 "Set whether to disable address space layout randomization when launching "
366 "a process."},
367 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000368 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 "Name of the process plugin you want to use."},
370 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000371 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 eArgTypeDirectoryName,
373 "Set the current working directory to <path> when running the inferior."},
374 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000375 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376 "Set the architecture for the process to launch when ambiguous."},
377 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000378 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 "Specify an environment variable name/value string (--environment "
380 "NAME=VALUE). Can be specified multiple times for subsequent environment "
381 "entries."},
382 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000383 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000385
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000387 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 "Redirect stdin for the process to <filename>."},
389 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000390 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391 "Redirect stdout for the process to <filename>."},
392 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000393 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000395
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000397 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000401 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 "Do not set up for terminal I/O to go to running process."},
403 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000404 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000406};
407
408llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000409 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000410}
Greg Clayton32e0a752011-03-30 18:16:51 +0000411
Zachary Turner31659452016-11-17 21:15:14 +0000412ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
413 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 ListenerSP listener_sp,
415 const FileSpec *crash_file_path) {
416 static uint32_t g_process_unique_id = 0;
417
418 ProcessSP process_sp;
419 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000420 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 ConstString const_plugin_name(plugin_name);
422 create_callback =
423 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
424 if (create_callback) {
425 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
426 if (process_sp) {
427 if (process_sp->CanDebug(target_sp, true)) {
428 process_sp->m_process_unique_id = ++g_process_unique_id;
429 } else
430 process_sp.reset();
431 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000432 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 } else {
434 for (uint32_t idx = 0;
435 (create_callback =
436 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
437 ++idx) {
438 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
439 if (process_sp) {
440 if (process_sp->CanDebug(target_sp, false)) {
441 process_sp->m_process_unique_id = ++g_process_unique_id;
442 break;
443 } else
444 process_sp.reset();
445 }
446 }
447 }
448 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000449}
450
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451ConstString &Process::GetStaticBroadcasterClass() {
452 static ConstString class_name("lldb.process");
453 return class_name;
454}
455
456Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
457 : Process(target_sp, listener_sp,
458 UnixSignals::Create(HostInfo::GetArchitecture())) {
459 // This constructor just delegates to the full Process constructor,
460 // defaulting to using the Host's UnixSignals.
461}
462
463Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
464 const UnixSignalsSP &unix_signals_sp)
465 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
466 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
467 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000468 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 m_private_state(eStateUnloaded),
470 m_private_state_broadcaster(nullptr,
471 "lldb.process.internal_state_broadcaster"),
472 m_private_state_control_broadcaster(
473 nullptr, "lldb.process.internal_state_control_broadcaster"),
474 m_private_state_listener_sp(
475 Listener::MakeListener("lldb.process.internal_state_listener")),
476 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
477 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
478 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
479 m_thread_list(this), m_extended_thread_list(this),
480 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
481 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000482 m_breakpoint_site_list(), m_dynamic_checkers_up(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000483 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
484 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
485 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
486 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
487 m_memory_cache(*this), m_allocated_memory_cache(*this),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000488 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000489 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
491 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
492 m_can_interpret_function_calls(false), m_warnings_issued(),
493 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
494 CheckInWithManager();
495
496 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000497 LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498
499 if (!m_unix_signals_sp)
500 m_unix_signals_sp = std::make_shared<UnixSignals>();
501
502 SetEventName(eBroadcastBitStateChanged, "state-changed");
503 SetEventName(eBroadcastBitInterrupt, "interrupt");
504 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
505 SetEventName(eBroadcastBitSTDERR, "stderr-available");
506 SetEventName(eBroadcastBitProfileData, "profile-data-available");
507 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
508
509 m_private_state_control_broadcaster.SetEventName(
510 eBroadcastInternalStateControlStop, "control-stop");
511 m_private_state_control_broadcaster.SetEventName(
512 eBroadcastInternalStateControlPause, "control-pause");
513 m_private_state_control_broadcaster.SetEventName(
514 eBroadcastInternalStateControlResume, "control-resume");
515
516 m_listener_sp->StartListeningForEvents(
517 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
518 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
519 eBroadcastBitProfileData | eBroadcastBitStructuredData);
520
521 m_private_state_listener_sp->StartListeningForEvents(
522 &m_private_state_broadcaster,
523 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
524
525 m_private_state_listener_sp->StartListeningForEvents(
526 &m_private_state_control_broadcaster,
527 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
528 eBroadcastInternalStateControlResume);
529 // We need something valid here, even if just the default UnixSignalsSP.
530 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
531
532 // Allow the platform to override the default cache line size
533 OptionValueSP value_sp =
534 m_collection_sp
535 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
536 ->GetValue();
537 uint32_t platform_cache_line_size =
538 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
539 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
540 value_sp->SetUInt64Value(platform_cache_line_size);
541}
542
543Process::~Process() {
544 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000545 LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 StopPrivateStateThread();
547
548 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000549 // explicitly clear the thread list here to ensure that the mutex is not
550 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 m_thread_list.Clear();
552}
553
554const ProcessPropertiesSP &Process::GetGlobalProperties() {
555 // NOTE: intentional leak so we don't crash if global destructor chain gets
556 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000557 static ProcessPropertiesSP *g_settings_sp_ptr =
558 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 return *g_settings_sp_ptr;
560}
561
562void Process::Finalize() {
563 m_finalizing = true;
564
565 // Destroy this process if needed
566 switch (GetPrivateState()) {
567 case eStateConnected:
568 case eStateAttaching:
569 case eStateLaunching:
570 case eStateStopped:
571 case eStateRunning:
572 case eStateStepping:
573 case eStateCrashed:
574 case eStateSuspended:
575 Destroy(false);
576 break;
577
578 case eStateInvalid:
579 case eStateUnloaded:
580 case eStateDetached:
581 case eStateExited:
582 break;
583 }
584
585 // Clear our broadcaster before we proceed with destroying
586 Broadcaster::Clear();
587
Adrian Prantl05097242018-04-30 16:49:04 +0000588 // Do any cleanup needed prior to being destructed... Subclasses that
589 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590
591 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000592 // destroyed since it is very likely that undoing the loader will require
593 // access to the real process.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000594 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000596 m_os_up.reset();
597 m_system_runtime_up.reset();
598 m_dyld_up.reset();
599 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 m_thread_list_real.Destroy();
601 m_thread_list.Destroy();
602 m_extended_thread_list.Destroy();
603 m_queue_list.Clear();
604 m_queue_list_stop_id = 0;
605 std::vector<Notifications> empty_notifications;
606 m_notifications.swap(empty_notifications);
607 m_image_tokens.clear();
608 m_memory_cache.Clear();
609 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +0000610 {
611 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
612 m_language_runtimes.clear();
613 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 m_instrumentation_runtimes.clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000615 m_next_event_action_up.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000616 // Clear the last natural stop ID since it has a strong reference to this
617 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
619 //#ifdef LLDB_CONFIGURATION_DEBUG
620 // StreamFile s(stdout, false);
621 // EventSP event_sp;
622 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
623 // {
624 // event_sp->Dump (&s);
625 // s.EOL();
626 // }
627 //#endif
628 // We have to be very careful here as the m_private_state_listener might
629 // contain events that have ProcessSP values in them which can keep this
630 // process around forever. These events need to be cleared out.
631 m_private_state_listener_sp->Clear();
632 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
633 m_public_run_lock.SetStopped();
634 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
635 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000636 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637 m_finalize_called = true;
638}
639
640void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
641 m_notifications.push_back(callbacks);
642 if (callbacks.initialize != nullptr)
643 callbacks.initialize(callbacks.baton, this);
644}
645
646bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
647 std::vector<Notifications>::iterator pos, end = m_notifications.end();
648 for (pos = m_notifications.begin(); pos != end; ++pos) {
649 if (pos->baton == callbacks.baton &&
650 pos->initialize == callbacks.initialize &&
651 pos->process_state_changed == callbacks.process_state_changed) {
652 m_notifications.erase(pos);
653 return true;
654 }
655 }
656 return false;
657}
658
659void Process::SynchronouslyNotifyStateChanged(StateType state) {
660 std::vector<Notifications>::iterator notification_pos,
661 notification_end = m_notifications.end();
662 for (notification_pos = m_notifications.begin();
663 notification_pos != notification_end; ++notification_pos) {
664 if (notification_pos->process_state_changed)
665 notification_pos->process_state_changed(notification_pos->baton, this,
666 state);
667 }
668}
669
670// FIXME: We need to do some work on events before the general Listener sees
671// them.
672// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000673// we do the little "insert real insn, step & stop" trick. But we can't do
674// that when the event is delivered by the broadcaster - since that is done on
675// the thread that is waiting for new events, so if we needed more than one
676// event for our handling, we would stall. So instead we do it when we fetch
677// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000678//
679
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680StateType Process::GetNextEvent(EventSP &event_sp) {
681 StateType state = eStateInvalid;
682
Pavel Labathd35031e12016-11-30 10:41:42 +0000683 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
684 std::chrono::seconds(0)) &&
685 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000686 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
687
688 return state;
689}
690
Pavel Labath3879fe02018-05-09 14:29:30 +0000691void Process::SyncIOHandler(uint32_t iohandler_id,
692 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 // don't sync (potentially context switch) in case where there is no process
694 // IO
695 if (!m_process_input_reader)
696 return;
697
Pavel Labath3879fe02018-05-09 14:29:30 +0000698 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699
700 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000701 if (Result) {
702 LLDB_LOG(
703 log,
704 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
705 iohandler_id, *Result);
706 } else {
707 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
708 iohandler_id);
709 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710}
711
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000712StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
713 EventSP *event_sp_ptr, bool wait_always,
714 ListenerSP hijack_listener_sp,
715 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000717 // have restarted the target. We have to actually check each event, and in
718 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 if (event_sp_ptr)
720 event_sp_ptr->reset();
721 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000722 // If we are exited or detached, we won't ever get back to any other valid
723 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000725 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000728 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000729
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 if (!wait_always && StateIsStoppedState(state, true) &&
731 StateIsStoppedState(GetPrivateState(), true)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000732 LLDB_LOGF(log,
733 "Process::%s returning without waiting for events; process "
734 "private and public states are already 'stopped'.",
735 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736 // We need to toggle the run lock as this won't get done in
737 // SetPublicState() if the process is hijacked.
738 if (hijack_listener_sp && use_run_lock)
739 m_public_run_lock.SetStopped();
740 return state;
741 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 while (state != eStateInvalid) {
744 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000745 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 if (event_sp_ptr && event_sp)
747 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +0000748
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
750 Process::HandleProcessStateChangedEvent(event_sp, stream,
751 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +0000752
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 switch (state) {
754 case eStateCrashed:
755 case eStateDetached:
756 case eStateExited:
757 case eStateUnloaded:
758 // We need to toggle the run lock as this won't get done in
759 // SetPublicState() if the process is hijacked.
760 if (hijack_listener_sp && use_run_lock)
761 m_public_run_lock.SetStopped();
762 return state;
763 case eStateStopped:
764 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
765 continue;
766 else {
Pavel Labath78521ef2015-03-06 10:52:47 +0000767 // We need to toggle the run lock as this won't get done in
768 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +0000769 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770 m_public_run_lock.SetStopped();
771 return state;
772 }
773 default:
774 continue;
775 }
776 }
777 return state;
778}
779
780bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
781 Stream *stream,
782 bool &pop_process_io_handler) {
783 const bool handle_pop = pop_process_io_handler;
784
785 pop_process_io_handler = false;
786 ProcessSP process_sp =
787 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
788
789 if (!process_sp)
790 return false;
791
792 StateType event_state =
793 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
794 if (event_state == eStateInvalid)
795 return false;
796
797 switch (event_state) {
798 case eStateInvalid:
799 case eStateUnloaded:
800 case eStateAttaching:
801 case eStateLaunching:
802 case eStateStepping:
803 case eStateDetached:
804 if (stream)
805 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
806 StateAsCString(event_state));
807 if (event_state == eStateDetached)
808 pop_process_io_handler = true;
809 break;
810
811 case eStateConnected:
812 case eStateRunning:
813 // Don't be chatty when we run...
814 break;
815
816 case eStateExited:
817 if (stream)
818 process_sp->GetStatus(*stream);
819 pop_process_io_handler = true;
820 break;
821
822 case eStateStopped:
823 case eStateCrashed:
824 case eStateSuspended:
825 // Make sure the program hasn't been auto-restarted:
826 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
827 if (stream) {
828 size_t num_reasons =
829 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
830 if (num_reasons > 0) {
831 // FIXME: Do we want to report this, or would that just be annoyingly
832 // chatty?
833 if (num_reasons == 1) {
834 const char *reason =
835 Process::ProcessEventData::GetRestartedReasonAtIndex(
836 event_sp.get(), 0);
837 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
838 process_sp->GetID(),
839 reason ? reason : "<UNKNOWN REASON>");
840 } else {
841 stream->Printf("Process %" PRIu64
842 " stopped and restarted, reasons:\n",
843 process_sp->GetID());
844
845 for (size_t i = 0; i < num_reasons; i++) {
846 const char *reason =
847 Process::ProcessEventData::GetRestartedReasonAtIndex(
848 event_sp.get(), i);
849 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
850 }
851 }
852 }
853 }
854 } else {
855 StopInfoSP curr_thread_stop_info_sp;
856 // Lock the thread list so it doesn't change on us, this is the scope for
857 // the locker:
858 {
859 ThreadList &thread_list = process_sp->GetThreadList();
860 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
861
862 ThreadSP curr_thread(thread_list.GetSelectedThread());
863 ThreadSP thread;
864 StopReason curr_thread_stop_reason = eStopReasonInvalid;
865 if (curr_thread) {
866 curr_thread_stop_reason = curr_thread->GetStopReason();
867 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
868 }
869 if (!curr_thread || !curr_thread->IsValid() ||
870 curr_thread_stop_reason == eStopReasonInvalid ||
871 curr_thread_stop_reason == eStopReasonNone) {
872 // Prefer a thread that has just completed its plan over another
873 // thread as current thread.
874 ThreadSP plan_thread;
875 ThreadSP other_thread;
876
877 const size_t num_threads = thread_list.GetSize();
878 size_t i;
879 for (i = 0; i < num_threads; ++i) {
880 thread = thread_list.GetThreadAtIndex(i);
881 StopReason thread_stop_reason = thread->GetStopReason();
882 switch (thread_stop_reason) {
883 case eStopReasonInvalid:
884 case eStopReasonNone:
885 break;
886
887 case eStopReasonSignal: {
888 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +0000889 // that signal. We have to have had another reason for stopping
890 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000891 uint64_t signo = thread->GetStopInfo()->GetValue();
892 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
893 if (!other_thread)
894 other_thread = thread;
895 }
896 break;
897 }
898 case eStopReasonTrace:
899 case eStopReasonBreakpoint:
900 case eStopReasonWatchpoint:
901 case eStopReasonException:
902 case eStopReasonExec:
903 case eStopReasonThreadExiting:
904 case eStopReasonInstrumentation:
905 if (!other_thread)
906 other_thread = thread;
907 break;
908 case eStopReasonPlanComplete:
909 if (!plan_thread)
910 plan_thread = thread;
911 break;
912 }
913 }
914 if (plan_thread)
915 thread_list.SetSelectedThreadByID(plan_thread->GetID());
916 else if (other_thread)
917 thread_list.SetSelectedThreadByID(other_thread->GetID());
918 else {
919 if (curr_thread && curr_thread->IsValid())
920 thread = curr_thread;
921 else
922 thread = thread_list.GetThreadAtIndex(0);
923
924 if (thread)
925 thread_list.SetSelectedThreadByID(thread->GetID());
926 }
927 }
928 }
929 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +0000930 // have to run code, e.g. for Data formatters, and if we hold the
931 // ThreadList mutex, then the process is going to have a hard time
932 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933 if (stream) {
934 Debugger &debugger = process_sp->GetTarget().GetDebugger();
935 if (debugger.GetTargetList().GetSelectedTarget().get() ==
936 &process_sp->GetTarget()) {
937 const bool only_threads_with_stop_reason = true;
938 const uint32_t start_frame = 0;
939 const uint32_t num_frames = 1;
940 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +0000941 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 process_sp->GetStatus(*stream);
943 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
944 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000945 num_frames_with_source,
946 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947 if (curr_thread_stop_info_sp) {
948 lldb::addr_t crashing_address;
949 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
950 curr_thread_stop_info_sp, &crashing_address);
951 if (valobj_sp) {
952 const bool qualify_cxx_base_classes = false;
953
954 const ValueObject::GetExpressionPathFormat format =
955 ValueObject::GetExpressionPathFormat::
956 eGetExpressionPathFormatHonorPointers;
957 stream->PutCString("Likely cause: ");
958 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
959 format);
960 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
961 }
962 }
963 } else {
964 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
965 process_sp->GetTarget().shared_from_this());
966 if (target_idx != UINT32_MAX)
967 stream->Printf("Target %d: (", target_idx);
968 else
969 stream->Printf("Target <unknown index>: (");
970 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
971 stream->Printf(") stopped.\n");
972 }
973 }
974
975 // Pop the process IO handler
976 pop_process_io_handler = true;
977 }
978 break;
979 }
980
981 if (handle_pop && pop_process_io_handler)
982 process_sp->PopProcessIOHandler();
983
984 return true;
985}
986
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987bool Process::HijackProcessEvents(ListenerSP listener_sp) {
988 if (listener_sp) {
989 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
990 eBroadcastBitInterrupt);
991 } else
992 return false;
993}
Greg Claytondc6224e2014-10-21 01:00:42 +0000994
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +0000996
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000997StateType Process::GetStateChangedEvents(EventSP &event_sp,
998 const Timeout<std::micro> &timeout,
999 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001001 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 ListenerSP listener_sp = hijack_listener_sp;
1004 if (!listener_sp)
1005 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001006
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001008 if (listener_sp->GetEventForBroadcasterWithType(
1009 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001010 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1012 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001013 else
1014 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001016
Pavel Labathd02b1c82017-02-10 11:49:33 +00001017 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 return state;
1019}
Greg Claytondc6224e2014-10-21 01:00:42 +00001020
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021Event *Process::PeekAtStateChangedEvents() {
1022 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001023
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001024 LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001025
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026 Event *event_ptr;
1027 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1028 this, eBroadcastBitStateChanged);
1029 if (log) {
1030 if (event_ptr) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001031 LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
1032 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001034 LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001035 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 }
1037 return event_ptr;
1038}
Greg Claytondc6224e2014-10-21 01:00:42 +00001039
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001040StateType
1041Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1042 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001043 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001044 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045
1046 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001047 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1048 &m_private_state_broadcaster,
1049 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001050 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1052 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1053
Pavel Labathd02b1c82017-02-10 11:49:33 +00001054 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1055 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056 return state;
1057}
1058
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001059bool Process::GetEventsPrivate(EventSP &event_sp,
1060 const Timeout<std::micro> &timeout,
1061 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001063 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001064
1065 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001066 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001067 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001069 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070}
1071
1072bool Process::IsRunning() const {
1073 return StateIsRunningState(m_public_state.GetValue());
1074}
1075
1076int Process::GetExitStatus() {
1077 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1078
1079 if (m_public_state.GetValue() == eStateExited)
1080 return m_exit_status;
1081 return -1;
1082}
1083
1084const char *Process::GetExitDescription() {
1085 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1086
1087 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1088 return m_exit_string.c_str();
1089 return nullptr;
1090}
1091
1092bool Process::SetExitStatus(int status, const char *cstr) {
1093 // Use a mutex to protect setting the exit status.
1094 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1095
1096 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1097 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001098 LLDB_LOGF(
1099 log, "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1100 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", cstr ? "\"" : "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101
1102 // We were already in the exited state
1103 if (m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001104 LLDB_LOGF(log, "Process::SetExitStatus () ignoring exit status because "
1105 "state was already set to eStateExited");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 return false;
1107 }
1108
1109 m_exit_status = status;
1110 if (cstr)
1111 m_exit_string = cstr;
1112 else
1113 m_exit_string.clear();
1114
Adrian Prantl05097242018-04-30 16:49:04 +00001115 // Clear the last natural stop ID since it has a strong reference to this
1116 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1118
1119 SetPrivateState(eStateExited);
1120
1121 // Allow subclasses to do some cleanup
1122 DidExit();
1123
1124 return true;
1125}
1126
1127bool Process::IsAlive() {
1128 switch (m_private_state.GetValue()) {
1129 case eStateConnected:
1130 case eStateAttaching:
1131 case eStateLaunching:
1132 case eStateStopped:
1133 case eStateRunning:
1134 case eStateStepping:
1135 case eStateCrashed:
1136 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001137 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138 default:
1139 return false;
1140 }
Jason Molendaa814f702015-11-05 23:03:44 +00001141}
1142
Adrian Prantl05097242018-04-30 16:49:04 +00001143// This static callback can be used to watch for local child processes on the
1144// current host. The child process exits, the process will be found in the
1145// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147bool Process::SetProcessExitStatus(
1148 lldb::pid_t pid, bool exited,
1149 int signo, // Zero for no signal
1150 int exit_status // Exit value of process if signal is zero
1151 ) {
1152 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001153 LLDB_LOGF(log,
1154 "Process::SetProcessExitStatus (pid=%" PRIu64
1155 ", exited=%i, signal=%i, exit_status=%i)\n",
1156 pid, exited, signo, exit_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001157
1158 if (exited) {
1159 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1160 if (target_sp) {
1161 ProcessSP process_sp(target_sp->GetProcessSP());
1162 if (process_sp) {
1163 const char *signal_cstr = nullptr;
1164 if (signo)
1165 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1166
1167 process_sp->SetExitStatus(exit_status, signal_cstr);
1168 }
1169 }
1170 return true;
1171 }
1172 return false;
1173}
1174
1175void Process::UpdateThreadListIfNeeded() {
1176 const uint32_t stop_id = GetStopID();
1177 if (m_thread_list.GetSize(false) == 0 ||
1178 stop_id != m_thread_list.GetStopID()) {
1179 const StateType state = GetPrivateState();
1180 if (StateIsStoppedState(state, true)) {
1181 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Adrian Prantl05097242018-04-30 16:49:04 +00001182 // m_thread_list does have its own mutex, but we need to hold onto the
1183 // mutex between the call to UpdateThreadList(...) and the
1184 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001185 ThreadList &old_thread_list = m_thread_list;
1186 ThreadList real_thread_list(this);
1187 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001188 // Always update the thread list with the protocol specific thread list,
1189 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1191 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001192 // are shutting down, since that may call back into the SBAPI's,
1193 // requiring the API lock which is already held by whoever is shutting
1194 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195 OperatingSystem *os = GetOperatingSystem();
1196 if (os && !m_destroy_in_process) {
1197 // Clear any old backing threads where memory threads might have been
1198 // backed by actual threads from the lldb_private::Process subclass
1199 size_t num_old_threads = old_thread_list.GetSize(false);
1200 for (size_t i = 0; i < num_old_threads; ++i)
1201 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1202
1203 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001204 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001205 // dynamic type or not and we need to avoid this. OperatingSystem
1206 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001207
1208 Target &target = GetTarget();
1209 const lldb::DynamicValueType saved_prefer_dynamic =
1210 target.GetPreferDynamicValue();
1211 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1212 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1213
1214 // Now let the OperatingSystem plug-in update the thread list
1215
1216 os->UpdateThreadList(
1217 old_thread_list, // Old list full of threads created by OS plug-in
1218 real_thread_list, // The actual thread list full of threads
1219 // created by each lldb_private::Process
1220 // subclass
1221 new_thread_list); // The new thread list that we will show to the
1222 // user that gets filled in
1223
1224 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1225 target.SetPreferDynamicValue(saved_prefer_dynamic);
1226 } else {
1227 // No OS plug-in, the new thread list is the same as the real thread
1228 // list
1229 new_thread_list = real_thread_list;
1230 }
1231
1232 m_thread_list_real.Update(real_thread_list);
1233 m_thread_list.Update(new_thread_list);
1234 m_thread_list.SetStopID(stop_id);
1235
1236 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1237 // Clear any extended threads that we may have accumulated previously
1238 m_extended_thread_list.Clear();
1239 m_extended_thread_stop_id = GetLastNaturalStopID();
1240
1241 m_queue_list.Clear();
1242 m_queue_list_stop_id = GetLastNaturalStopID();
1243 }
1244 }
1245 }
1246 }
1247}
1248
1249void Process::UpdateQueueListIfNeeded() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001250 if (m_system_runtime_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001251 if (m_queue_list.GetSize() == 0 ||
1252 m_queue_list_stop_id != GetLastNaturalStopID()) {
1253 const StateType state = GetPrivateState();
1254 if (StateIsStoppedState(state, true)) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001255 m_system_runtime_up->PopulateQueueList(m_queue_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 m_queue_list_stop_id = GetLastNaturalStopID();
1257 }
1258 }
1259 }
1260}
1261
1262ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1263 OperatingSystem *os = GetOperatingSystem();
1264 if (os)
1265 return os->CreateThread(tid, context);
1266 return ThreadSP();
1267}
1268
1269uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1270 return AssignIndexIDToThread(thread_id);
1271}
1272
1273bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1274 return (m_thread_id_to_index_id_map.find(thread_id) !=
1275 m_thread_id_to_index_id_map.end());
1276}
1277
1278uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1279 uint32_t result = 0;
1280 std::map<uint64_t, uint32_t>::iterator iterator =
1281 m_thread_id_to_index_id_map.find(thread_id);
1282 if (iterator == m_thread_id_to_index_id_map.end()) {
1283 result = ++m_thread_index_id;
1284 m_thread_id_to_index_id_map[thread_id] = result;
1285 } else {
1286 result = iterator->second;
1287 }
1288
1289 return result;
1290}
1291
1292StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293 return m_public_state.GetValue();
1294}
1295
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296void Process::SetPublicState(StateType new_state, bool restarted) {
1297 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1298 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001299 LLDB_LOGF(log, "Process::SetPublicState (state = %s, restarted = %i)",
1300 StateAsCString(new_state), restarted);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301 const StateType old_state = m_public_state.GetValue();
1302 m_public_state.SetValue(new_state);
1303
Adrian Prantl05097242018-04-30 16:49:04 +00001304 // On the transition from Run to Stopped, we unlock the writer end of the run
1305 // lock. The lock gets locked in Resume, which is the public API to tell the
1306 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307 if (!StateChangedIsExternallyHijacked()) {
1308 if (new_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001309 LLDB_LOGF(log,
1310 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1311 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312 m_public_run_lock.SetStopped();
1313 } else {
1314 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1315 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1316 if ((old_state_is_stopped != new_state_is_stopped)) {
1317 if (new_state_is_stopped && !restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001318 LLDB_LOGF(log, "Process::SetPublicState (%s) -- unlocking run lock",
1319 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 m_public_run_lock.SetStopped();
1321 }
1322 }
1323 }
1324 }
1325}
1326
Zachary Turner97206d52017-05-12 04:51:55 +00001327Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1329 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001330 LLDB_LOGF(log, "Process::Resume -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001332 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001333 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001334 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001336 Status error = PrivateResume();
1337 if (!error.Success()) {
1338 // Undo running state change
1339 m_public_run_lock.SetStopped();
1340 }
1341 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001342}
1343
Jim Ingham3139fc92019-03-01 18:13:38 +00001344static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1345
Zachary Turner97206d52017-05-12 04:51:55 +00001346Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001347 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1348 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001349 LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001351 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001352 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001353 return error;
1354 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001355
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356 ListenerSP listener_sp(
Jim Ingham3139fc92019-03-01 18:13:38 +00001357 Listener::MakeListener(g_resume_sync_name));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001359
Zachary Turner97206d52017-05-12 04:51:55 +00001360 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001361 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001362 StateType state =
Konrad Kleine248a1302019-05-23 11:14:47 +00001363 WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001364 const bool must_be_alive =
1365 false; // eStateExited is ok, so this must be false
1366 if (!StateIsStoppedState(state, must_be_alive))
1367 error.SetErrorStringWithFormat(
1368 "process not in stopped state after synchronous resume: %s",
1369 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001370 } else {
1371 // Undo running state change
1372 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373 }
Ed Mastec29693f2013-07-02 16:35:47 +00001374
Kate Stoneb9c1b512016-09-06 20:57:50 +00001375 // Undo the hijacking of process events...
1376 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001377
Kate Stoneb9c1b512016-09-06 20:57:50 +00001378 return error;
1379}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001380
Jim Ingham3139fc92019-03-01 18:13:38 +00001381bool Process::StateChangedIsExternallyHijacked() {
1382 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1383 const char *hijacking_name = GetHijackingListenerName();
1384 if (hijacking_name &&
1385 strcmp(hijacking_name, g_resume_sync_name))
1386 return true;
1387 }
1388 return false;
1389}
1390
1391bool Process::StateChangedIsHijackedForSynchronousResume() {
1392 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1393 const char *hijacking_name = GetHijackingListenerName();
1394 if (hijacking_name &&
1395 strcmp(hijacking_name, g_resume_sync_name) == 0)
1396 return true;
1397 }
1398 return false;
1399}
1400
Kate Stoneb9c1b512016-09-06 20:57:50 +00001401StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001402
Kate Stoneb9c1b512016-09-06 20:57:50 +00001403void Process::SetPrivateState(StateType new_state) {
1404 if (m_finalize_called)
1405 return;
1406
1407 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1408 LIBLLDB_LOG_PROCESS));
1409 bool state_changed = false;
1410
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001411 LLDB_LOGF(log, "Process::SetPrivateState (%s)", StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001412
1413 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1414 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1415
1416 const StateType old_state = m_private_state.GetValueNoLock();
1417 state_changed = old_state != new_state;
1418
1419 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1420 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1421 if (old_state_is_stopped != new_state_is_stopped) {
1422 if (new_state_is_stopped)
1423 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001424 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001425 m_private_run_lock.SetRunning();
1426 }
1427
1428 if (state_changed) {
1429 m_private_state.SetValueNoLock(new_state);
1430 EventSP event_sp(
1431 new Event(eBroadcastBitStateChanged,
1432 new ProcessEventData(shared_from_this(), new_state)));
1433 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001434 // Note, this currently assumes that all threads in the list stop when
1435 // the process stops. In the future we will want to support a debugging
1436 // model where some threads continue to run while others are stopped.
1437 // When that happens we will either need a way for the thread list to
1438 // identify which threads are stopping or create a special thread list
1439 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 //
Adrian Prantl05097242018-04-30 16:49:04 +00001441 // The process plugin is responsible for managing the actual behavior of
1442 // the threads and should have stopped any threads that are going to stop
1443 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444 m_thread_list.DidStop();
1445
1446 m_mod_id.BumpStopID();
1447 if (!m_mod_id.IsLastResumeForUserExpression())
1448 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1449 m_memory_cache.Clear();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001450 LLDB_LOGF(log, "Process::SetPrivateState (%s) stop_id = %u",
1451 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001452 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001453
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 // Use our target to get a shared pointer to ourselves...
1455 if (m_finalize_called && !PrivateStateThreadIsValid())
1456 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001457 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001458 m_private_state_broadcaster.BroadcastEvent(event_sp);
1459 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001460 LLDB_LOGF(log,
1461 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1462 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 }
Jim Ingham22777012010-09-23 02:01:19 +00001464}
1465
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466void Process::SetRunningUserExpression(bool on) {
1467 m_mod_id.SetRunningUserExpression(on);
1468}
1469
Raphael Isemannc01783a2018-08-29 22:50:54 +00001470void Process::SetRunningUtilityFunction(bool on) {
1471 m_mod_id.SetRunningUtilityFunction(on);
1472}
1473
Kate Stoneb9c1b512016-09-06 20:57:50 +00001474addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1475
1476const lldb::ABISP &Process::GetABI() {
1477 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001478 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001479 return m_abi_sp;
1480}
1481
Davide Italianocec82632019-12-03 16:54:04 -08001482std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
Alex Langford03e1a822019-05-29 18:08:22 +00001483 std::vector<LanguageRuntime *> language_runtimes;
1484
1485 if (m_finalizing)
1486 return language_runtimes;
1487
1488 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1489 // Before we pass off a copy of the language runtimes, we must make sure that
1490 // our collection is properly populated. It's possible that some of the
1491 // language runtimes were not loaded yet, either because nobody requested it
1492 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1493 // hadn't been loaded).
1494 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
Davide Italianocec82632019-12-03 16:54:04 -08001495 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
Alex Langford03e1a822019-05-29 18:08:22 +00001496 language_runtimes.emplace_back(runtime);
1497 }
1498
1499 return language_runtimes;
1500}
1501
Davide Italianocec82632019-12-03 16:54:04 -08001502LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001503 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001504 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001505
Alex Langford7d3e97f2019-05-29 21:07:53 +00001506 LanguageRuntime *runtime = nullptr;
1507
Alex Langford74eb76f2019-05-22 23:01:18 +00001508 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001509 LanguageRuntimeCollection::iterator pos;
1510 pos = m_language_runtimes.find(language);
Davide Italianocec82632019-12-03 16:54:04 -08001511 if (pos == m_language_runtimes.end() || !pos->second) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001512 lldb::LanguageRuntimeSP runtime_sp(
1513 LanguageRuntime::FindPlugin(this, language));
1514
1515 m_language_runtimes[language] = runtime_sp;
Alex Langford7d3e97f2019-05-29 21:07:53 +00001516 runtime = runtime_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001517 } else
Alex Langford7d3e97f2019-05-29 21:07:53 +00001518 runtime = pos->second.get();
1519
1520 if (runtime)
1521 // It's possible that a language runtime can support multiple LanguageTypes,
1522 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1523 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1524 // primary language type and make sure that our runtime supports it.
1525 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1526
1527 return runtime;
Jim Ingham22777012010-09-23 02:01:19 +00001528}
1529
Kate Stoneb9c1b512016-09-06 20:57:50 +00001530bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1531 if (m_finalizing)
1532 return false;
1533
1534 if (in_value.IsDynamic())
1535 return false;
1536 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1537
1538 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1539 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1540 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1541 }
1542
Alex Langford41dc5522019-05-30 21:03:53 +00001543 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1544 if (runtime->CouldHaveDynamicValue(in_value))
1545 return true;
1546 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001547
Alex Langford41dc5522019-05-30 21:03:53 +00001548 return false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001549}
1550
Kate Stoneb9c1b512016-09-06 20:57:50 +00001551void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001552 m_dynamic_checkers_up.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001553}
1554
Kate Stoneb9c1b512016-09-06 20:57:50 +00001555BreakpointSiteList &Process::GetBreakpointSiteList() {
1556 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001557}
1558
Kate Stoneb9c1b512016-09-06 20:57:50 +00001559const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1560 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001561}
1562
Kate Stoneb9c1b512016-09-06 20:57:50 +00001563void Process::DisableAllBreakpointSites() {
1564 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1565 // bp_site->SetEnabled(true);
1566 DisableBreakpointSite(bp_site);
1567 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001568}
1569
Zachary Turner97206d52017-05-12 04:51:55 +00001570Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1571 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001572
Kate Stoneb9c1b512016-09-06 20:57:50 +00001573 if (error.Success())
1574 m_breakpoint_site_list.Remove(break_id);
1575
1576 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001577}
1578
Zachary Turner97206d52017-05-12 04:51:55 +00001579Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1580 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001581 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1582 if (bp_site_sp) {
1583 if (bp_site_sp->IsEnabled())
1584 error = DisableBreakpointSite(bp_site_sp.get());
1585 } else {
1586 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1587 break_id);
1588 }
1589
1590 return error;
1591}
1592
Zachary Turner97206d52017-05-12 04:51:55 +00001593Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1594 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1596 if (bp_site_sp) {
1597 if (!bp_site_sp->IsEnabled())
1598 error = EnableBreakpointSite(bp_site_sp.get());
1599 } else {
1600 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1601 break_id);
1602 }
1603 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001604}
1605
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001606lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001607Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1608 bool use_hardware) {
1609 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001610
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611 bool show_error = true;
1612 switch (GetState()) {
1613 case eStateInvalid:
1614 case eStateUnloaded:
1615 case eStateConnected:
1616 case eStateAttaching:
1617 case eStateLaunching:
1618 case eStateDetached:
1619 case eStateExited:
1620 show_error = false;
1621 break;
1622
1623 case eStateStopped:
1624 case eStateRunning:
1625 case eStateStepping:
1626 case eStateCrashed:
1627 case eStateSuspended:
1628 show_error = IsAlive();
1629 break;
1630 }
1631
Adrian Prantl05097242018-04-30 16:49:04 +00001632 // Reset the IsIndirect flag here, in case the location changes from pointing
1633 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001634 owner->SetIsIndirect(false);
1635
1636 if (owner->ShouldResolveIndirectFunctions()) {
1637 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1638 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001639 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001640 Address symbol_address = symbol->GetAddress();
1641 load_addr = ResolveIndirectFunction(&symbol_address, error);
1642 if (!error.Success() && show_error) {
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001643 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001644 "warning: failed to resolve indirect function at 0x%" PRIx64
1645 " for breakpoint %i.%i: %s\n",
1646 symbol->GetLoadAddress(&GetTarget()),
1647 owner->GetBreakpoint().GetID(), owner->GetID(),
1648 error.AsCString() ? error.AsCString() : "unknown error");
1649 return LLDB_INVALID_BREAK_ID;
1650 }
1651 Address resolved_address(load_addr);
1652 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1653 owner->SetIsIndirect(true);
1654 } else
1655 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1656 } else
1657 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1658
1659 if (load_addr != LLDB_INVALID_ADDRESS) {
1660 BreakpointSiteSP bp_site_sp;
1661
1662 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001663 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001664
1665 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1666
1667 if (bp_site_sp) {
1668 bp_site_sp->AddOwner(owner);
1669 owner->SetBreakpointSite(bp_site_sp);
1670 return bp_site_sp->GetID();
1671 } else {
1672 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1673 load_addr, use_hardware));
1674 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001675 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001676 if (error.Success()) {
1677 owner->SetBreakpointSite(bp_site_sp);
1678 return m_breakpoint_site_list.Add(bp_site_sp);
1679 } else {
Jonas Devliegheree103ae92018-11-15 01:18:15 +00001680 if (show_error || use_hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001681 // Report error for setting breakpoint...
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001682 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001683 "warning: failed to set breakpoint site at 0x%" PRIx64
1684 " for breakpoint %i.%i: %s\n",
1685 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1686 error.AsCString() ? error.AsCString() : "unknown error");
1687 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001688 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001690 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001691 }
1692 // We failed to enable the breakpoint
1693 return LLDB_INVALID_BREAK_ID;
1694}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001695
Kate Stoneb9c1b512016-09-06 20:57:50 +00001696void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1697 lldb::user_id_t owner_loc_id,
1698 BreakpointSiteSP &bp_site_sp) {
1699 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1700 if (num_owners == 0) {
1701 // Don't try to disable the site if we don't have a live process anymore.
1702 if (IsAlive())
1703 DisableBreakpointSite(bp_site_sp.get());
1704 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1705 }
1706}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001707
Kate Stoneb9c1b512016-09-06 20:57:50 +00001708size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1709 uint8_t *buf) const {
1710 size_t bytes_removed = 0;
1711 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001712
Kate Stoneb9c1b512016-09-06 20:57:50 +00001713 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1714 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001715 bp_sites_in_range.ForEach([bp_addr, size,
1716 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1718 addr_t intersect_addr;
1719 size_t intersect_size;
1720 size_t opcode_offset;
1721 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1722 &intersect_size, &opcode_offset)) {
1723 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1724 assert(bp_addr < intersect_addr + intersect_size &&
1725 intersect_addr + intersect_size <= bp_addr + size);
1726 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1727 size_t buf_offset = intersect_addr - bp_addr;
1728 ::memcpy(buf + buf_offset,
1729 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1730 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001731 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732 }
1733 });
1734 }
1735 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001736}
1737
Kate Stoneb9c1b512016-09-06 20:57:50 +00001738size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1739 PlatformSP platform_sp(GetTarget().GetPlatform());
1740 if (platform_sp)
1741 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1742 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001743}
1744
Zachary Turner97206d52017-05-12 04:51:55 +00001745Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1746 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001747 assert(bp_site != nullptr);
1748 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1749 const addr_t bp_addr = bp_site->GetLoadAddress();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001750 LLDB_LOGF(
1751 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1752 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001753 if (bp_site->IsEnabled()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001754 LLDB_LOGF(
1755 log,
1756 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1757 " -- already enabled",
1758 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001759 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 }
1761
1762 if (bp_addr == LLDB_INVALID_ADDRESS) {
1763 error.SetErrorString("BreakpointSite contains an invalid load address.");
1764 return error;
1765 }
1766 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1767 // trap for the breakpoint site
1768 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1769
1770 if (bp_opcode_size == 0) {
1771 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1772 "returned zero, unable to get breakpoint "
1773 "trap for address 0x%" PRIx64,
1774 bp_addr);
1775 } else {
1776 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1777
1778 if (bp_opcode_bytes == nullptr) {
1779 error.SetErrorString(
1780 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1781 return error;
1782 }
1783
1784 // Save the original opcode by reading it
1785 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1786 error) == bp_opcode_size) {
1787 // Write a software breakpoint in place of the original opcode
1788 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1789 bp_opcode_size) {
1790 uint8_t verify_bp_opcode_bytes[64];
1791 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1792 error) == bp_opcode_size) {
1793 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1794 bp_opcode_size) == 0) {
1795 bp_site->SetEnabled(true);
1796 bp_site->SetType(BreakpointSite::eSoftware);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001797 LLDB_LOGF(log,
1798 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1799 "addr = 0x%" PRIx64 " -- SUCCESS",
1800 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001801 } else
1802 error.SetErrorString(
1803 "failed to verify the breakpoint trap in memory.");
1804 } else
1805 error.SetErrorString(
1806 "Unable to read memory to verify breakpoint trap.");
1807 } else
1808 error.SetErrorString("Unable to write breakpoint trap to memory.");
1809 } else
1810 error.SetErrorString("Unable to read memory at breakpoint address.");
1811 }
1812 if (log && error.Fail())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001813 LLDB_LOGF(
1814 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001815 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1816 " -- FAILED: %s",
1817 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1818 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819}
1820
Zachary Turner97206d52017-05-12 04:51:55 +00001821Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1822 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001823 assert(bp_site != nullptr);
1824 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1825 addr_t bp_addr = bp_site->GetLoadAddress();
1826 lldb::user_id_t breakID = bp_site->GetID();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001827 LLDB_LOGF(log,
1828 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1829 ") addr = 0x%" PRIx64,
1830 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001831
Kate Stoneb9c1b512016-09-06 20:57:50 +00001832 if (bp_site->IsHardware()) {
1833 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1834 } else if (bp_site->IsEnabled()) {
1835 const size_t break_op_size = bp_site->GetByteSize();
1836 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1837 if (break_op_size > 0) {
1838 // Clear a software breakpoint instruction
1839 uint8_t curr_break_op[8];
1840 assert(break_op_size <= sizeof(curr_break_op));
1841 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001842
Kate Stoneb9c1b512016-09-06 20:57:50 +00001843 // Read the breakpoint opcode
1844 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1845 break_op_size) {
1846 bool verify = false;
1847 // Make sure the breakpoint opcode exists at this address
1848 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1849 break_op_found = true;
1850 // We found a valid breakpoint opcode at this address, now restore
1851 // the saved opcode.
1852 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1853 break_op_size, error) == break_op_size) {
1854 verify = true;
1855 } else
1856 error.SetErrorString(
1857 "Memory write failed when restoring original opcode.");
1858 } else {
1859 error.SetErrorString(
1860 "Original breakpoint trap is no longer in memory.");
1861 // Set verify to true and so we can check if the original opcode has
1862 // already been restored
1863 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001865
Kate Stoneb9c1b512016-09-06 20:57:50 +00001866 if (verify) {
1867 uint8_t verify_opcode[8];
1868 assert(break_op_size < sizeof(verify_opcode));
1869 // Verify that our original opcode made it back to the inferior
1870 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1871 break_op_size) {
1872 // compare the memory we just read with the original opcode
1873 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1874 break_op_size) == 0) {
1875 // SUCCESS
1876 bp_site->SetEnabled(false);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001877 LLDB_LOGF(log,
1878 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1879 "addr = 0x%" PRIx64 " -- SUCCESS",
1880 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001881 return error;
1882 } else {
1883 if (break_op_found)
1884 error.SetErrorString("Failed to restore original opcode.");
1885 }
1886 } else
1887 error.SetErrorString("Failed to read memory to verify that "
1888 "breakpoint trap was restored.");
1889 }
1890 } else
1891 error.SetErrorString(
1892 "Unable to read memory that should contain the breakpoint trap.");
1893 }
1894 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001895 LLDB_LOGF(
1896 log,
1897 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1898 " -- already disabled",
1899 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001900 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001901 }
1902
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001903 LLDB_LOGF(
1904 log,
1905 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1906 " -- FAILED: %s",
1907 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001908 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001909}
1910
Adrian Prantl05097242018-04-30 16:49:04 +00001911// Uncomment to verify memory caching works after making changes to caching
1912// code
Greg Clayton58be07b2011-01-07 06:08:19 +00001913//#define VERIFY_MEMORY_READS
1914
Zachary Turner97206d52017-05-12 04:51:55 +00001915size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001916 error.Clear();
1917 if (!GetDisableMemoryCache()) {
1918#if defined(VERIFY_MEMORY_READS)
1919 // Memory caching is enabled, with debug verification
1920
1921 if (buf && size) {
1922 // Uncomment the line below to make sure memory caching is working.
1923 // I ran this through the test suite and got no assertions, so I am
1924 // pretty confident this is working well. If any changes are made to
1925 // memory caching, uncomment the line below and test your changes!
1926
1927 // Verify all memory reads by using the cache first, then redundantly
1928 // reading the same memory from the inferior and comparing to make sure
1929 // everything is exactly the same.
1930 std::string verify_buf(size, '\0');
1931 assert(verify_buf.size() == size);
1932 const size_t cache_bytes_read =
1933 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00001934 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935 const size_t verify_bytes_read =
1936 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1937 verify_buf.size(), verify_error);
1938 assert(cache_bytes_read == verify_bytes_read);
1939 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1940 assert(verify_error.Success() == error.Success());
1941 return cache_bytes_read;
1942 }
1943 return 0;
1944#else // !defined(VERIFY_MEMORY_READS)
1945 // Memory caching is enabled, without debug verification
1946
1947 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00001948#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001949 } else {
1950 // Memory caching is disabled
1951
1952 return ReadMemoryFromInferior(addr, buf, size, error);
1953 }
Greg Clayton58be07b2011-01-07 06:08:19 +00001954}
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955
1956size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00001957 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001958 char buf[256];
1959 out_str.clear();
1960 addr_t curr_addr = addr;
1961 while (true) {
1962 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
1963 if (length == 0)
1964 break;
1965 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00001966 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1967 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00001968 if (length == sizeof(buf) - 1)
1969 curr_addr += length;
1970 else
1971 break;
1972 }
1973 return out_str.size();
1974}
1975
1976size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00001977 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001978 size_t total_bytes_read = 0;
1979 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00001980 // Ensure a null terminator independent of the number of bytes that is
1981 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001982 memset(dst, 0, max_bytes);
1983 size_t bytes_left = max_bytes - type_width;
1984
1985 const char terminator[4] = {'\0', '\0', '\0', '\0'};
1986 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
1987 "string with more than 4 bytes "
1988 "per character!");
1989
Greg Clayton4c82d422012-05-18 23:20:01 +00001990 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001991 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1992 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00001993
Kate Stoneb9c1b512016-09-06 20:57:50 +00001994 error.Clear();
1995 while (bytes_left > 0 && error.Success()) {
1996 addr_t cache_line_bytes_left =
1997 cache_line_size - (curr_addr % cache_line_size);
1998 addr_t bytes_to_read =
1999 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2000 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002001
Kate Stoneb9c1b512016-09-06 20:57:50 +00002002 if (bytes_read == 0)
2003 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002004
Kate Stoneb9c1b512016-09-06 20:57:50 +00002005 // Search for a null terminator of correct size and alignment in
2006 // bytes_read
2007 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2008 for (size_t i = aligned_start;
2009 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2010 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2011 error.Clear();
2012 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002013 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002014
2015 total_bytes_read += bytes_read;
2016 curr_dst += bytes_read;
2017 curr_addr += bytes_read;
2018 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002019 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002020 } else {
2021 if (max_bytes)
2022 error.SetErrorString("invalid arguments");
2023 }
2024 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002025}
2026
Kate Stoneb9c1b512016-09-06 20:57:50 +00002027// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002028// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002029size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002030 size_t dst_max_len,
2031 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002032 size_t total_cstr_len = 0;
2033 if (dst && dst_max_len) {
2034 result_error.Clear();
2035 // NULL out everything just to be safe
2036 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002037 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002038 addr_t curr_addr = addr;
2039 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2040 size_t bytes_left = dst_max_len - 1;
2041 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002042
Kate Stoneb9c1b512016-09-06 20:57:50 +00002043 while (bytes_left > 0) {
2044 addr_t cache_line_bytes_left =
2045 cache_line_size - (curr_addr % cache_line_size);
2046 addr_t bytes_to_read =
2047 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2048 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002049
Kate Stoneb9c1b512016-09-06 20:57:50 +00002050 if (bytes_read == 0) {
2051 result_error = error;
2052 dst[total_cstr_len] = '\0';
2053 break;
2054 }
2055 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002056
Kate Stoneb9c1b512016-09-06 20:57:50 +00002057 total_cstr_len += len;
2058
2059 if (len < bytes_to_read)
2060 break;
2061
2062 curr_dst += bytes_read;
2063 curr_addr += bytes_read;
2064 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002065 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002066 } else {
2067 if (dst == nullptr)
2068 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002069 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002070 result_error.Clear();
2071 }
2072 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002073}
2074
Kate Stoneb9c1b512016-09-06 20:57:50 +00002075size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002076 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002077 if (buf == nullptr || size == 0)
2078 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002079
Kate Stoneb9c1b512016-09-06 20:57:50 +00002080 size_t bytes_read = 0;
2081 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002082
Kate Stoneb9c1b512016-09-06 20:57:50 +00002083 while (bytes_read < size) {
2084 const size_t curr_size = size - bytes_read;
2085 const size_t curr_bytes_read =
2086 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2087 bytes_read += curr_bytes_read;
2088 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2089 break;
2090 }
2091
2092 // Replace any software breakpoint opcodes that fall into this range back
2093 // into "buf" before we return
2094 if (bytes_read > 0)
2095 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2096 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002097}
2098
Kate Stoneb9c1b512016-09-06 20:57:50 +00002099uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2100 size_t integer_byte_size,
2101 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002102 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002103 Scalar scalar;
2104 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2105 error))
2106 return scalar.ULongLong(fail_value);
2107 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002108}
2109
Kate Stoneb9c1b512016-09-06 20:57:50 +00002110int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2111 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002112 int64_t fail_value,
2113 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002114 Scalar scalar;
2115 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2116 error))
2117 return scalar.SLongLong(fail_value);
2118 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002119}
2120
Zachary Turner97206d52017-05-12 04:51:55 +00002121addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002122 Scalar scalar;
2123 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2124 error))
2125 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2126 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002127}
2128
Kate Stoneb9c1b512016-09-06 20:57:50 +00002129bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002130 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002131 Scalar scalar;
2132 const uint32_t addr_byte_size = GetAddressByteSize();
2133 if (addr_byte_size <= 4)
2134 scalar = (uint32_t)ptr_value;
2135 else
2136 scalar = ptr_value;
2137 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2138 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002139}
2140
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002142 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143 size_t bytes_written = 0;
2144 const uint8_t *bytes = (const uint8_t *)buf;
2145
2146 while (bytes_written < size) {
2147 const size_t curr_size = size - bytes_written;
2148 const size_t curr_bytes_written = DoWriteMemory(
2149 addr + bytes_written, bytes + bytes_written, curr_size, error);
2150 bytes_written += curr_bytes_written;
2151 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2152 break;
2153 }
2154 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002155}
2156
Kate Stoneb9c1b512016-09-06 20:57:50 +00002157size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002158 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002159#if defined(ENABLE_MEMORY_CACHING)
2160 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002161#endif
2162
Kate Stoneb9c1b512016-09-06 20:57:50 +00002163 if (buf == nullptr || size == 0)
2164 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002165
Kate Stoneb9c1b512016-09-06 20:57:50 +00002166 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002167
Kate Stoneb9c1b512016-09-06 20:57:50 +00002168 // We need to write any data that would go where any current software traps
2169 // (enabled software breakpoints) any software traps (breakpoints) that we
2170 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002171
Kate Stoneb9c1b512016-09-06 20:57:50 +00002172 BreakpointSiteList bp_sites_in_range;
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002173 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002174 return WriteMemoryPrivate(addr, buf, size, error);
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002175
2176 // No breakpoint sites overlap
2177 if (bp_sites_in_range.IsEmpty())
2178 return WriteMemoryPrivate(addr, buf, size, error);
2179
2180 const uint8_t *ubuf = (const uint8_t *)buf;
2181 uint64_t bytes_written = 0;
2182
2183 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2184 &error](BreakpointSite *bp) -> void {
2185 if (error.Fail())
2186 return;
2187
2188 addr_t intersect_addr;
2189 size_t intersect_size;
2190 size_t opcode_offset;
2191 const bool intersects = bp->IntersectsRange(
2192 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2193 UNUSED_IF_ASSERT_DISABLED(intersects);
2194 assert(intersects);
2195 assert(addr <= intersect_addr && intersect_addr < addr + size);
2196 assert(addr < intersect_addr + intersect_size &&
2197 intersect_addr + intersect_size <= addr + size);
2198 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2199
2200 // Check for bytes before this breakpoint
2201 const addr_t curr_addr = addr + bytes_written;
2202 if (intersect_addr > curr_addr) {
2203 // There are some bytes before this breakpoint that we need to just
2204 // write to memory
2205 size_t curr_size = intersect_addr - curr_addr;
2206 size_t curr_bytes_written =
2207 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2208 bytes_written += curr_bytes_written;
2209 if (curr_bytes_written != curr_size) {
2210 // We weren't able to write all of the requested bytes, we are
2211 // done looping and will return the number of bytes that we have
2212 // written so far.
2213 if (error.Success())
2214 error.SetErrorToGenericError();
2215 }
2216 }
2217 // Now write any bytes that would cover up any software breakpoints
2218 // directly into the breakpoint opcode buffer
2219 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2220 intersect_size);
2221 bytes_written += intersect_size;
2222 });
Kate Stoneb9c1b512016-09-06 20:57:50 +00002223
2224 // Write any remaining bytes after the last breakpoint if we have any left
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002225 if (bytes_written < size)
2226 bytes_written +=
2227 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2228 size - bytes_written, error);
2229
2230 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002231}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002232
Kate Stoneb9c1b512016-09-06 20:57:50 +00002233size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002234 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 if (byte_size == UINT32_MAX)
2236 byte_size = scalar.GetByteSize();
2237 if (byte_size > 0) {
2238 uint8_t buf[32];
2239 const size_t mem_size =
2240 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2241 if (mem_size > 0)
2242 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002243 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002244 error.SetErrorString("failed to get scalar as memory data");
2245 } else {
2246 error.SetErrorString("invalid scalar value");
2247 }
2248 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002249}
2250
Kate Stoneb9c1b512016-09-06 20:57:50 +00002251size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2252 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002253 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002254 uint64_t uval = 0;
2255 if (byte_size == 0) {
2256 error.SetErrorString("byte size is zero");
2257 } else if (byte_size & (byte_size - 1)) {
2258 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2259 byte_size);
2260 } else if (byte_size <= sizeof(uval)) {
2261 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2262 if (bytes_read == byte_size) {
2263 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2264 GetAddressByteSize());
2265 lldb::offset_t offset = 0;
2266 if (byte_size <= 4)
2267 scalar = data.GetMaxU32(&offset, byte_size);
2268 else
2269 scalar = data.GetMaxU64(&offset, byte_size);
2270 if (is_signed)
2271 scalar.SignExtend(byte_size * 8);
2272 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002273 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002274 } else {
2275 error.SetErrorStringWithFormat(
2276 "byte size of %u is too large for integer scalar type", byte_size);
2277 }
2278 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002279}
2280
Pavel Labath16064d32018-03-20 11:56:24 +00002281Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2282 Status error;
2283 for (const auto &Entry : entries) {
2284 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2285 error);
2286 if (!error.Success())
2287 break;
2288 }
2289 return error;
2290}
2291
Greg Claytond495c532011-05-17 03:37:42 +00002292#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002293addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002294 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002295 if (GetPrivateState() != eStateStopped) {
2296 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002297 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002298 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002299
2300#if defined(USE_ALLOCATE_MEMORY_CACHE)
2301 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002302#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002303 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2304 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002305 LLDB_LOGF(log,
2306 "Process::AllocateMemory(size=%" PRIu64
2307 ", permissions=%s) => 0x%16.16" PRIx64
2308 " (m_stop_id = %u m_memory_id = %u)",
2309 (uint64_t)size, GetPermissionsAsCString(permissions),
2310 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2311 m_mod_id.GetMemoryID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002312 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002313#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002314}
2315
Kate Stoneb9c1b512016-09-06 20:57:50 +00002316addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002317 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002318 addr_t return_addr = AllocateMemory(size, permissions, error);
2319 if (error.Success()) {
2320 std::string buffer(size, 0);
2321 WriteMemory(return_addr, buffer.c_str(), size, error);
2322 }
2323 return return_addr;
2324}
2325
2326bool Process::CanJIT() {
2327 if (m_can_jit == eCanJITDontKnow) {
2328 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002329 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002330
2331 uint64_t allocated_memory = AllocateMemory(
2332 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2333 err);
2334
2335 if (err.Success()) {
2336 m_can_jit = eCanJITYes;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002337 LLDB_LOGF(log,
2338 "Process::%s pid %" PRIu64
2339 " allocation test passed, CanJIT () is true",
2340 __FUNCTION__, GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341 } else {
2342 m_can_jit = eCanJITNo;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002343 LLDB_LOGF(log,
2344 "Process::%s pid %" PRIu64
2345 " allocation test failed, CanJIT () is false: %s",
2346 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002347 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002348
2349 DeallocateMemory(allocated_memory);
2350 }
2351
2352 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002353}
2354
Kate Stoneb9c1b512016-09-06 20:57:50 +00002355void Process::SetCanJIT(bool can_jit) {
2356 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002357}
2358
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359void Process::SetCanRunCode(bool can_run_code) {
2360 SetCanJIT(can_run_code);
2361 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002362}
2363
Zachary Turner97206d52017-05-12 04:51:55 +00002364Status Process::DeallocateMemory(addr_t ptr) {
2365 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002366#if defined(USE_ALLOCATE_MEMORY_CACHE)
2367 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2368 error.SetErrorStringWithFormat(
2369 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2370 }
Greg Claytond495c532011-05-17 03:37:42 +00002371#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002372 error = DoDeallocateMemory(ptr);
2373
2374 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002375 LLDB_LOGF(log,
2376 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2377 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2378 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2379 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002380#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002381 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002382}
2383
Kate Stoneb9c1b512016-09-06 20:57:50 +00002384ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2385 lldb::addr_t header_addr,
2386 size_t size_to_read) {
2387 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2388 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002389 LLDB_LOGF(log,
2390 "Process::ReadModuleFromMemory reading %s binary from memory",
2391 file_spec.GetPath().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002392 }
2393 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2394 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002395 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002396 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2397 shared_from_this(), header_addr, error, size_to_read);
2398 if (objfile)
2399 return module_sp;
2400 }
2401 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402}
2403
Kate Stoneb9c1b512016-09-06 20:57:50 +00002404bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2405 uint32_t &permissions) {
2406 MemoryRegionInfo range_info;
2407 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002408 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002409 if (!error.Success())
2410 return false;
2411 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2412 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2413 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2414 return false;
2415 }
2416
2417 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2418 permissions |= lldb::ePermissionsReadable;
2419
2420 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2421 permissions |= lldb::ePermissionsWritable;
2422
2423 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2424 permissions |= lldb::ePermissionsExecutable;
2425
2426 return true;
2427}
2428
Zachary Turner97206d52017-05-12 04:51:55 +00002429Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2430 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002431 error.SetErrorString("watchpoints are not supported");
2432 return error;
2433}
2434
Zachary Turner97206d52017-05-12 04:51:55 +00002435Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2436 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002437 error.SetErrorString("watchpoints are not supported");
2438 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002439}
2440
2441StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002442Process::WaitForProcessStopPrivate(EventSP &event_sp,
2443 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002444 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002445
Kate Stoneb9c1b512016-09-06 20:57:50 +00002446 while (true) {
2447 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002448 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002449
Kate Stoneb9c1b512016-09-06 20:57:50 +00002450 if (StateIsStoppedState(state, false))
2451 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002452
Kate Stoneb9c1b512016-09-06 20:57:50 +00002453 // If state is invalid, then we timed out
2454 if (state == eStateInvalid)
2455 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002456
Kate Stoneb9c1b512016-09-06 20:57:50 +00002457 if (event_sp)
2458 HandlePrivateEvent(event_sp);
2459 }
2460 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002461}
2462
Kate Stoneb9c1b512016-09-06 20:57:50 +00002463void Process::LoadOperatingSystemPlugin(bool flush) {
2464 if (flush)
2465 m_thread_list.Clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002466 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002467 if (flush)
2468 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002469}
2470
Zachary Turner97206d52017-05-12 04:51:55 +00002471Status Process::Launch(ProcessLaunchInfo &launch_info) {
2472 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002473 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002474 m_dyld_up.reset();
2475 m_jit_loaders_up.reset();
2476 m_system_runtime_up.reset();
2477 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002478 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002479
Kate Stoneb9c1b512016-09-06 20:57:50 +00002480 Module *exe_module = GetTarget().GetExecutableModulePointer();
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002481 if (!exe_module) {
2482 error.SetErrorString("executable module does not exist");
2483 return error;
2484 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002485
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002486 char local_exec_file_path[PATH_MAX];
2487 char platform_exec_file_path[PATH_MAX];
2488 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2489 sizeof(local_exec_file_path));
2490 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2491 sizeof(platform_exec_file_path));
2492 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2493 // Install anything that might need to be installed prior to launching.
2494 // For host systems, this will do nothing, but if we are connected to a
2495 // remote platform it will install any needed binaries
2496 error = GetTarget().Install(&launch_info);
2497 if (error.Fail())
2498 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002499
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002500 if (PrivateStateThreadIsValid())
2501 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002502
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002503 error = WillLaunch(exe_module);
2504 if (error.Success()) {
2505 const bool restarted = false;
2506 SetPublicState(eStateLaunching, restarted);
2507 m_should_detach = false;
2508
2509 if (m_public_run_lock.TrySetRunning()) {
2510 // Now launch using these arguments.
2511 error = DoLaunch(exe_module, launch_info);
2512 } else {
2513 // This shouldn't happen
2514 error.SetErrorString("failed to acquire process run lock");
2515 }
2516
2517 if (error.Fail()) {
2518 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2519 SetID(LLDB_INVALID_PROCESS_ID);
2520 const char *error_string = error.AsCString();
2521 if (error_string == nullptr)
2522 error_string = "launch failed";
2523 SetExitStatus(-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002524 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002525 } else {
2526 EventSP event_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002527
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002528 // Now wait for the process to launch and return control to us, and then
2529 // call DidLaunch:
2530 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Stella Stamenova36d457c2018-06-01 19:14:53 +00002531
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002532 if (state == eStateInvalid || !event_sp) {
2533 // We were able to launch the process, but we failed to catch the
2534 // initial stop.
2535 error.SetErrorString("failed to catch stop after launch");
2536 SetExitStatus(0, "failed to catch stop after launch");
2537 Destroy(false);
2538 } else if (state == eStateStopped || state == eStateCrashed) {
2539 DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002540
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002541 DynamicLoader *dyld = GetDynamicLoader();
2542 if (dyld)
2543 dyld->DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002544
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002545 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002546
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002547 SystemRuntime *system_runtime = GetSystemRuntime();
2548 if (system_runtime)
2549 system_runtime->DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002550
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002551 if (!m_os_up)
2552 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002553
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002554 // We successfully launched the process and stopped, now it the
2555 // right time to set up signal filters before resuming.
2556 UpdateAutomaticSignalFiltering();
Greg Clayton35824e32015-02-20 20:59:47 +00002557
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002558 // Note, the stop event was consumed above, but not handled. This
2559 // was done to give DidLaunch a chance to run. The target is either
2560 // stopped or crashed. Directly set the state. This is done to
2561 // prevent a stop message with a bunch of spurious output on thread
2562 // status, as well as not pop a ProcessIOHandler.
2563 SetPublicState(state, false);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002564
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002565 if (PrivateStateThreadIsValid())
2566 ResumePrivateStateThread();
2567 else
2568 StartPrivateStateThread();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002569
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002570 // Target was stopped at entry as was intended. Need to notify the
2571 // listeners about it.
2572 if (state == eStateStopped &&
2573 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002574 HandlePrivateEvent(event_sp);
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002575 } else if (state == eStateExited) {
2576 // We exited while trying to launch somehow. Don't call DidLaunch
2577 // as that's not likely to work, and return an invalid pid.
2578 HandlePrivateEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002579 }
2580 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002581 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002582 } else {
2583 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2584 local_exec_file_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002585 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002586
Kate Stoneb9c1b512016-09-06 20:57:50 +00002587 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002588}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002589
Zachary Turner97206d52017-05-12 04:51:55 +00002590Status Process::LoadCore() {
2591 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002592 if (error.Success()) {
2593 ListenerSP listener_sp(
2594 Listener::MakeListener("lldb.process.load_core_listener"));
2595 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002596
Kate Stoneb9c1b512016-09-06 20:57:50 +00002597 if (PrivateStateThreadIsValid())
2598 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002599 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002600 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002601
Kate Stoneb9c1b512016-09-06 20:57:50 +00002602 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002603 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002604 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002605
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002606 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002607
Kate Stoneb9c1b512016-09-06 20:57:50 +00002608 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002609 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002610 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002611
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002612 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00002613 LoadOperatingSystemPlugin(false);
2614
Kate Stoneb9c1b512016-09-06 20:57:50 +00002615 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002616 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002617 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002618
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002619 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002620 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002621 StateType state =
Pavel Labath7ada1c52019-06-25 07:14:29 +00002622 WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002623
2624 if (!StateIsStoppedState(state, false)) {
2625 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002626 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2627 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002628 error.SetErrorString(
2629 "Did not get stopped event after loading the core file.");
2630 }
2631 RestoreProcessEvents();
2632 }
2633 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002634}
2635
Kate Stoneb9c1b512016-09-06 20:57:50 +00002636DynamicLoader *Process::GetDynamicLoader() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002637 if (!m_dyld_up)
2638 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2639 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002640}
2641
Antonio Afonso943faef2019-06-11 20:16:13 +00002642DataExtractor Process::GetAuxvData() { return DataExtractor(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002643
2644JITLoaderList &Process::GetJITLoaders() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002645 if (!m_jit_loaders_up) {
2646 m_jit_loaders_up.reset(new JITLoaderList());
2647 JITLoader::LoadPlugins(this, *m_jit_loaders_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002648 }
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002649 return *m_jit_loaders_up;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002650}
2651
2652SystemRuntime *Process::GetSystemRuntime() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002653 if (!m_system_runtime_up)
2654 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2655 return m_system_runtime_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002656}
2657
2658Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2659 uint32_t exec_count)
2660 : NextEventAction(process), m_exec_count(exec_count) {
2661 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002662 LLDB_LOGF(
2663 log,
2664 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2665 __FUNCTION__, static_cast<void *>(process), exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002666}
2667
2668Process::NextEventAction::EventActionResult
2669Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2670 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2671
2672 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002673 LLDB_LOGF(log,
2674 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2675 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002676
2677 switch (state) {
2678 case eStateAttaching:
2679 return eEventActionSuccess;
2680
2681 case eStateRunning:
2682 case eStateConnected:
2683 return eEventActionRetry;
2684
2685 case eStateStopped:
2686 case eStateCrashed:
2687 // During attach, prior to sending the eStateStopped event,
2688 // lldb_private::Process subclasses must set the new process ID.
2689 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002690 // We don't want these events to be reported, so go set the
2691 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002692 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2693
2694 if (m_exec_count > 0) {
2695 --m_exec_count;
2696
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002697 LLDB_LOGF(log,
2698 "Process::AttachCompletionHandler::%s state %s: reduced "
2699 "remaining exec count to %" PRIu32 ", requesting resume",
2700 __FUNCTION__, StateAsCString(state), m_exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002701
2702 RequestResume();
2703 return eEventActionRetry;
2704 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002705 LLDB_LOGF(log,
2706 "Process::AttachCompletionHandler::%s state %s: no more "
2707 "execs expected to start, continuing with attach",
2708 __FUNCTION__, StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002709
2710 m_process->CompleteAttach();
2711 return eEventActionSuccess;
2712 }
2713 break;
2714
2715 default:
2716 case eStateExited:
2717 case eStateInvalid:
2718 break;
2719 }
2720
2721 m_exit_string.assign("No valid Process");
2722 return eEventActionExit;
2723}
2724
2725Process::NextEventAction::EventActionResult
2726Process::AttachCompletionHandler::HandleBeingInterrupted() {
2727 return eEventActionSuccess;
2728}
2729
2730const char *Process::AttachCompletionHandler::GetExitString() {
2731 return m_exit_string.c_str();
2732}
2733
2734ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2735 if (m_listener_sp)
2736 return m_listener_sp;
2737 else
2738 return debugger.GetListener();
2739}
2740
Zachary Turner97206d52017-05-12 04:51:55 +00002741Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742 m_abi_sp.reset();
2743 m_process_input_reader.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002744 m_dyld_up.reset();
2745 m_jit_loaders_up.reset();
2746 m_system_runtime_up.reset();
2747 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748
2749 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002750 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002751 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2752 char process_name[PATH_MAX];
2753
2754 if (attach_info.GetExecutableFile().GetPath(process_name,
2755 sizeof(process_name))) {
2756 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2757
2758 if (wait_for_launch) {
2759 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2760 if (error.Success()) {
2761 if (m_public_run_lock.TrySetRunning()) {
2762 m_should_detach = true;
2763 const bool restarted = false;
2764 SetPublicState(eStateAttaching, restarted);
2765 // Now attach using these arguments.
2766 error = DoAttachToProcessWithName(process_name, attach_info);
2767 } else {
2768 // This shouldn't happen
2769 error.SetErrorString("failed to acquire process run lock");
2770 }
2771
2772 if (error.Fail()) {
2773 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2774 SetID(LLDB_INVALID_PROCESS_ID);
2775 if (error.AsCString() == nullptr)
2776 error.SetErrorString("attach failed");
2777
2778 SetExitStatus(-1, error.AsCString());
2779 }
2780 } else {
2781 SetNextEventAction(new Process::AttachCompletionHandler(
2782 this, attach_info.GetResumeCount()));
2783 StartPrivateStateThread();
2784 }
2785 return error;
2786 }
2787 } else {
2788 ProcessInstanceInfoList process_infos;
2789 PlatformSP platform_sp(GetTarget().GetPlatform());
2790
2791 if (platform_sp) {
2792 ProcessInstanceInfoMatch match_info;
2793 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00002794 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 platform_sp->FindProcesses(match_info, process_infos);
2796 const uint32_t num_matches = process_infos.GetSize();
2797 if (num_matches == 1) {
2798 attach_pid = process_infos.GetProcessIDAtIndex(0);
2799 // Fall through and attach using the above process ID
2800 } else {
2801 match_info.GetProcessInfo().GetExecutableFile().GetPath(
2802 process_name, sizeof(process_name));
2803 if (num_matches > 1) {
2804 StreamString s;
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002805 ProcessInstanceInfo::DumpTableHeader(s, true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806 for (size_t i = 0; i < num_matches; i++) {
2807 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002808 s, platform_sp->GetUserIDResolver(), true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 }
2810 error.SetErrorStringWithFormat(
2811 "more than one process named %s:\n%s", process_name,
2812 s.GetData());
2813 } else
2814 error.SetErrorStringWithFormat(
2815 "could not find a process named %s", process_name);
2816 }
2817 } else {
2818 error.SetErrorString(
2819 "invalid platform, can't find processes by name");
2820 return error;
2821 }
2822 }
2823 } else {
2824 error.SetErrorString("invalid process name");
2825 }
2826 }
2827
2828 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2829 error = WillAttachToProcessWithID(attach_pid);
2830 if (error.Success()) {
2831
2832 if (m_public_run_lock.TrySetRunning()) {
2833 // Now attach using these arguments.
2834 m_should_detach = true;
2835 const bool restarted = false;
2836 SetPublicState(eStateAttaching, restarted);
2837 error = DoAttachToProcessWithID(attach_pid, attach_info);
2838 } else {
2839 // This shouldn't happen
2840 error.SetErrorString("failed to acquire process run lock");
2841 }
2842
2843 if (error.Success()) {
2844 SetNextEventAction(new Process::AttachCompletionHandler(
2845 this, attach_info.GetResumeCount()));
2846 StartPrivateStateThread();
2847 } else {
Greg Clayton71337622011-02-24 22:24:29 +00002848 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002849 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002850
Kate Stoneb9c1b512016-09-06 20:57:50 +00002851 const char *error_string = error.AsCString();
2852 if (error_string == nullptr)
2853 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00002854
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 SetExitStatus(-1, error_string);
2856 }
Greg Claytonb766a732011-02-04 01:58:07 +00002857 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002858 }
2859 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00002860}
2861
Kate Stoneb9c1b512016-09-06 20:57:50 +00002862void Process::CompleteAttach() {
2863 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2864 LIBLLDB_LOG_TARGET));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002865 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866
2867 // Let the process subclass figure out at much as it can about the process
2868 // before we go looking for a dynamic loader plug-in.
2869 ArchSpec process_arch;
2870 DidAttach(process_arch);
2871
2872 if (process_arch.IsValid()) {
2873 GetTarget().SetArchitecture(process_arch);
2874 if (log) {
2875 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002876 LLDB_LOGF(log,
2877 "Process::%s replacing process architecture with DidAttach() "
2878 "architecture: %s",
2879 __FUNCTION__, triple_str ? triple_str : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002880 }
2881 }
2882
2883 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00002884 // architecture, and if it isn't the same as the one we've already set,
2885 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002886 PlatformSP platform_sp(GetTarget().GetPlatform());
2887 assert(platform_sp);
2888 if (platform_sp) {
2889 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2890 if (target_arch.IsValid() &&
2891 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2892 ArchSpec platform_arch;
2893 platform_sp =
2894 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2895 if (platform_sp) {
2896 GetTarget().SetPlatform(platform_sp);
2897 GetTarget().SetArchitecture(platform_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002898 LLDB_LOGF(log,
2899 "Process::%s switching platform to %s and architecture "
2900 "to %s based on info from attach",
2901 __FUNCTION__, platform_sp->GetName().AsCString(""),
2902 platform_arch.GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 }
2904 } else if (!process_arch.IsValid()) {
2905 ProcessInstanceInfo process_info;
2906 GetProcessInfo(process_info);
2907 const ArchSpec &process_arch = process_info.GetArchitecture();
2908 if (process_arch.IsValid() &&
2909 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
2910 GetTarget().SetArchitecture(process_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002911 LLDB_LOGF(log,
2912 "Process::%s switching architecture to %s based on info "
2913 "the platform retrieved for pid %" PRIu64,
2914 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
2915 GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002916 }
2917 }
2918 }
2919
2920 // We have completed the attach, now it is time to find the dynamic loader
2921 // plug-in
2922 DynamicLoader *dyld = GetDynamicLoader();
2923 if (dyld) {
2924 dyld->DidAttach();
2925 if (log) {
2926 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002927 LLDB_LOGF(log,
2928 "Process::%s after DynamicLoader::DidAttach(), target "
2929 "executable is %s (using %s plugin)",
2930 __FUNCTION__,
2931 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2932 : "<none>",
2933 dyld->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002934 }
2935 }
2936
2937 GetJITLoaders().DidAttach();
2938
2939 SystemRuntime *system_runtime = GetSystemRuntime();
2940 if (system_runtime) {
2941 system_runtime->DidAttach();
2942 if (log) {
2943 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002944 LLDB_LOGF(log,
2945 "Process::%s after SystemRuntime::DidAttach(), target "
2946 "executable is %s (using %s plugin)",
2947 __FUNCTION__,
2948 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2949 : "<none>",
2950 system_runtime->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002951 }
2952 }
2953
Jim Ingham8864b432019-06-28 17:57:19 +00002954 if (!m_os_up) {
Greg Clayton29eeea02017-02-09 18:55:41 +00002955 LoadOperatingSystemPlugin(false);
Jim Ingham8864b432019-06-28 17:57:19 +00002956 if (m_os_up) {
2957 // Somebody might have gotten threads before now, but we need to force the
2958 // update after we've loaded the OperatingSystem plugin or it won't get a
2959 // chance to process the threads.
2960 m_thread_list.Clear();
2961 UpdateThreadListIfNeeded();
2962 }
2963 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 // Figure out which one is the executable, and set that in our target:
2965 const ModuleList &target_modules = GetTarget().GetImages();
2966 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2967 size_t num_modules = target_modules.GetSize();
2968 ModuleSP new_executable_module_sp;
2969
2970 for (size_t i = 0; i < num_modules; i++) {
2971 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
2972 if (module_sp && module_sp->IsExecutable()) {
2973 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
2974 new_executable_module_sp = module_sp;
2975 break;
2976 }
2977 }
2978 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00002979 GetTarget().SetExecutableModule(new_executable_module_sp,
2980 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002981 if (log) {
2982 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002983 LLDB_LOGF(
2984 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002985 "Process::%s after looping through modules, target executable is %s",
2986 __FUNCTION__,
2987 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2988 : "<none>");
2989 }
2990 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991}
2992
Zachary Turner97206d52017-05-12 04:51:55 +00002993Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002994 m_abi_sp.reset();
2995 m_process_input_reader.reset();
2996
2997 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00002998 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002999
Zachary Turner97206d52017-05-12 04:51:55 +00003000 Status error(DoConnectRemote(strm, remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003001 if (error.Success()) {
3002 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3003 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003004 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003005
3006 if (state == eStateStopped || state == eStateCrashed) {
3007 // If we attached and actually have a process on the other end, then
3008 // this ended up being the equivalent of an attach.
3009 CompleteAttach();
3010
3011 // This delays passing the stopped event to listeners till
3012 // CompleteAttach gets a chance to complete...
3013 HandlePrivateEvent(event_sp);
3014 }
3015 }
3016
3017 if (PrivateStateThreadIsValid())
3018 ResumePrivateStateThread();
3019 else
3020 StartPrivateStateThread();
3021 }
3022 return error;
3023}
3024
Zachary Turner97206d52017-05-12 04:51:55 +00003025Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003026 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3027 LIBLLDB_LOG_STEP));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003028 LLDB_LOGF(log,
3029 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3030 "private state: %s",
3031 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3032 StateAsCString(m_private_state.GetValue()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003033
Adrian Prantl05097242018-04-30 16:49:04 +00003034 // If signals handing status changed we might want to update our signal
3035 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003036 UpdateAutomaticSignalFiltering();
3037
Zachary Turner97206d52017-05-12 04:51:55 +00003038 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003039 // Tell the process it is about to resume before the thread list
3040 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003041 // Now let the thread list know we are about to resume so it can let all of
3042 // our threads know that they are about to be resumed. Threads will each be
3043 // called with Thread::WillResume(StateType) where StateType contains the
3044 // state that they are supposed to have when the process is resumed
3045 // (suspended/running/stepping). Threads should also check their resume
3046 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3047 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003048 if (m_thread_list.WillResume()) {
3049 // Last thing, do the PreResumeActions.
3050 if (!RunPreResumeActions()) {
3051 error.SetErrorStringWithFormat(
3052 "Process::PrivateResume PreResumeActions failed, not resuming.");
3053 } else {
3054 m_mod_id.BumpResumeID();
3055 error = DoResume();
3056 if (error.Success()) {
3057 DidResume();
3058 m_thread_list.DidResume();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003059 LLDB_LOGF(log, "Process thinks the process has resumed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003060 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003061 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003062 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003063 }
3064 }
3065 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003066 // Somebody wanted to run without running (e.g. we were faking a step
3067 // from one frame of a set of inlined frames that share the same PC to
3068 // another.) So generate a continue & a stopped event, and let the world
3069 // handle them.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003070 LLDB_LOGF(log,
3071 "Process::PrivateResume() asked to simulate a start & stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003072
3073 SetPrivateState(eStateRunning);
3074 SetPrivateState(eStateStopped);
3075 }
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003076 } else
3077 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3078 error.AsCString("<unknown error>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003079 return error;
3080}
3081
Zachary Turner97206d52017-05-12 04:51:55 +00003082Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003083 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003084 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003085
Adrian Prantl05097242018-04-30 16:49:04 +00003086 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3087 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003088 m_clear_thread_plans_on_stop |= clear_thread_plans;
3089
3090 ListenerSP halt_listener_sp(
3091 Listener::MakeListener("lldb.process.halt_listener"));
3092 HijackProcessEvents(halt_listener_sp);
3093
3094 EventSP event_sp;
3095
3096 SendAsyncInterrupt();
3097
3098 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003099 // Don't hijack and eat the eStateExited as the code that was doing the
3100 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003101 RestoreProcessEvents();
3102 SetExitStatus(SIGKILL, "Cancelled async attach.");
3103 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003104 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003105 }
3106
3107 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003108 StateType state = WaitForProcessToStop(
3109 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110 RestoreProcessEvents();
3111
3112 if (state == eStateInvalid || !event_sp) {
3113 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003114 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003115 }
3116
3117 BroadcastEvent(event_sp);
3118
Zachary Turner97206d52017-05-12 04:51:55 +00003119 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120}
3121
Zachary Turner97206d52017-05-12 04:51:55 +00003122Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3123 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003124
3125 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003126 // expression, for instance, then the public state will be stopped, but we
3127 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003128 if (m_public_state.GetValue() == eStateRunning ||
3129 m_private_state.GetValue() == eStateRunning) {
3130 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003131 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003132
Kate Stoneb9c1b512016-09-06 20:57:50 +00003133 ListenerSP listener_sp(
3134 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3135 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003136
Pavel Labath19da1f12015-12-07 12:36:52 +00003137 SendAsyncInterrupt();
3138
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003140 StateType state =
3141 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003142
Pavel Labath19da1f12015-12-07 12:36:52 +00003143 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003144
Kate Stoneb9c1b512016-09-06 20:57:50 +00003145 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003146 // exited event into the shared pointer passed in and return. Our caller
3147 // doesn't need to do anything else, since they don't have a process
3148 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003149
3150 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003151 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3152 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003153 return error;
3154 } else
3155 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3156
3157 if (state != eStateStopped) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003158 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3159 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003160 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003161 // here, but if the lower levels just bobbled sending the event and we
3162 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163 StateType private_state = m_private_state.GetValue();
3164 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003165 return Status(
3166 "Attempt to stop the target in order to detach timed out. "
3167 "State = %s",
3168 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003169 }
3170 }
3171 }
3172 return error;
3173}
3174
Zachary Turner97206d52017-05-12 04:51:55 +00003175Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003176 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003177 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003178 m_destroy_in_process = true;
3179
3180 error = WillDetach();
3181
3182 if (error.Success()) {
3183 if (DetachRequiresHalt()) {
3184 error = StopForDestroyOrDetach(exit_event_sp);
3185 if (!error.Success()) {
3186 m_destroy_in_process = false;
3187 return error;
3188 } else if (exit_event_sp) {
3189 // We shouldn't need to do anything else here. There's no process left
3190 // to detach from...
3191 StopPrivateStateThread();
3192 m_destroy_in_process = false;
3193 return error;
3194 }
3195 }
3196
3197 m_thread_list.DiscardThreadPlans();
3198 DisableAllBreakpointSites();
3199
3200 error = DoDetach(keep_stopped);
3201 if (error.Success()) {
3202 DidDetach();
3203 StopPrivateStateThread();
3204 } else {
3205 return error;
3206 }
3207 }
3208 m_destroy_in_process = false;
3209
Adrian Prantl05097242018-04-30 16:49:04 +00003210 // If we exited when we were waiting for a process to stop, then forward the
3211 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003212 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003213 // Directly broadcast our exited event because we shut down our private
3214 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003215 BroadcastEvent(exit_event_sp);
3216 }
3217
3218 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003219 // not end up propagating the last events through the event system, in which
3220 // case we might strand the write lock. Unlock it here so when we do to tear
3221 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003222
3223 m_public_run_lock.SetStopped();
3224 return error;
3225}
3226
Zachary Turner97206d52017-05-12 04:51:55 +00003227Status Process::Destroy(bool force_kill) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003228
3229 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003230 // don't do any unnecessary work that might hinder the destruction. Remember
3231 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003232 // failed and the process stays around for some reason it won't be in a
3233 // confused state.
3234
3235 if (force_kill)
3236 m_should_detach = false;
3237
3238 if (GetShouldDetach()) {
3239 // FIXME: This will have to be a process setting:
3240 bool keep_stopped = false;
3241 Detach(keep_stopped);
3242 }
3243
3244 m_destroy_in_process = true;
3245
Zachary Turner97206d52017-05-12 04:51:55 +00003246 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003247 if (error.Success()) {
3248 EventSP exit_event_sp;
3249 if (DestroyRequiresHalt()) {
3250 error = StopForDestroyOrDetach(exit_event_sp);
3251 }
3252
3253 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003254 // Ditch all thread plans, and remove all our breakpoints: in case we
3255 // have to restart the target to kill it, we don't want it hitting a
3256 // breakpoint... Only do this if we've stopped, however, since if we
3257 // didn't manage to halt it above, then we're not going to have much luck
3258 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003259 m_thread_list.DiscardThreadPlans();
3260 DisableAllBreakpointSites();
3261 }
3262
3263 error = DoDestroy();
3264 if (error.Success()) {
3265 DidDestroy();
3266 StopPrivateStateThread();
3267 }
3268 m_stdio_communication.Disconnect();
3269 m_stdio_communication.StopReadThread();
3270 m_stdin_forward = false;
3271
3272 if (m_process_input_reader) {
3273 m_process_input_reader->SetIsDone(true);
3274 m_process_input_reader->Cancel();
3275 m_process_input_reader.reset();
3276 }
3277
Adrian Prantl05097242018-04-30 16:49:04 +00003278 // If we exited when we were waiting for a process to stop, then forward
3279 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003280 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003281 // Directly broadcast our exited event because we shut down our private
3282 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003283 BroadcastEvent(exit_event_sp);
3284 }
3285
Adrian Prantl05097242018-04-30 16:49:04 +00003286 // If we have been interrupted (to kill us) in the middle of running, we
3287 // may not end up propagating the last events through the event system, in
3288 // which case we might strand the write lock. Unlock it here so when we do
3289 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003290 m_public_run_lock.SetStopped();
3291 }
3292
3293 m_destroy_in_process = false;
3294
3295 return error;
3296}
3297
Zachary Turner97206d52017-05-12 04:51:55 +00003298Status Process::Signal(int signal) {
3299 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003300 if (error.Success()) {
3301 error = DoSignal(signal);
3302 if (error.Success())
3303 DidSignal();
3304 }
3305 return error;
3306}
3307
3308void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3309 assert(signals_sp && "null signals_sp");
3310 m_unix_signals_sp = signals_sp;
3311}
3312
3313const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3314 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3315 return m_unix_signals_sp;
3316}
3317
3318lldb::ByteOrder Process::GetByteOrder() const {
3319 return GetTarget().GetArchitecture().GetByteOrder();
3320}
3321
3322uint32_t Process::GetAddressByteSize() const {
3323 return GetTarget().GetArchitecture().GetAddressByteSize();
3324}
3325
3326bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3327 const StateType state =
3328 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3329 bool return_value = true;
3330 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3331 LIBLLDB_LOG_PROCESS));
3332
3333 switch (state) {
3334 case eStateDetached:
3335 case eStateExited:
3336 case eStateUnloaded:
3337 m_stdio_communication.SynchronizeWithReadThread();
3338 m_stdio_communication.Disconnect();
3339 m_stdio_communication.StopReadThread();
3340 m_stdin_forward = false;
3341
3342 LLVM_FALLTHROUGH;
3343 case eStateConnected:
3344 case eStateAttaching:
3345 case eStateLaunching:
3346 // These events indicate changes in the state of the debugging session,
3347 // always report them.
3348 return_value = true;
3349 break;
3350 case eStateInvalid:
3351 // We stopped for no apparent reason, don't report it.
3352 return_value = false;
3353 break;
3354 case eStateRunning:
3355 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003356 // If we've started the target running, we handle the cases where we are
3357 // already running and where there is a transition from stopped to running
3358 // differently. running -> running: Automatically suppress extra running
3359 // events stopped -> running: Report except when there is one or more no
3360 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003361 // and no yes votes.
3362 SynchronouslyNotifyStateChanged(state);
3363 if (m_force_next_event_delivery)
3364 return_value = true;
3365 else {
3366 switch (m_last_broadcast_state) {
3367 case eStateRunning:
3368 case eStateStepping:
3369 // We always suppress multiple runnings with no PUBLIC stop in between.
3370 return_value = false;
3371 break;
3372 default:
3373 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003374 // run if we aren't running so we don't miss any running events. If I
3375 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3376 // and hit the breakpoints on multiple threads, then somehow during the
3377 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003378
3379 // This is a transition from stop to run.
3380 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3381 case eVoteYes:
3382 case eVoteNoOpinion:
3383 return_value = true;
3384 break;
3385 case eVoteNo:
3386 return_value = false;
3387 break;
3388 }
3389 break;
3390 }
3391 }
3392 break;
3393 case eStateStopped:
3394 case eStateCrashed:
3395 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003396 // We've stopped. First see if we're going to restart the target. If we
3397 // are going to stop, then we always broadcast the event. If we aren't
3398 // going to stop, let the thread plans decide if we're going to report this
3399 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003400
3401 m_stdio_communication.SynchronizeWithReadThread();
3402 RefreshStateAfterStop();
3403 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003404 LLDB_LOGF(log,
3405 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3406 "interrupt, state: %s",
3407 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003408 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003409 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003410 m_thread_list.ShouldStop(event_ptr);
3411 return_value = true;
3412 } else {
3413 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3414 bool should_resume = false;
3415
3416 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003417 // restarted... Asking the thread list is also not likely to go well,
3418 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003419
3420 if (!was_restarted)
3421 should_resume = !m_thread_list.ShouldStop(event_ptr);
3422
3423 if (was_restarted || should_resume || m_resume_requested) {
3424 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003425 LLDB_LOGF(log,
3426 "Process::ShouldBroadcastEvent: should_resume: %i state: "
3427 "%s was_restarted: %i stop_vote: %d.",
3428 should_resume, StateAsCString(state), was_restarted,
3429 stop_vote);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003430
3431 switch (stop_vote) {
3432 case eVoteYes:
3433 return_value = true;
3434 break;
3435 case eVoteNoOpinion:
3436 case eVoteNo:
3437 return_value = false;
3438 break;
3439 }
3440
3441 if (!was_restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003442 LLDB_LOGF(log,
3443 "Process::ShouldBroadcastEvent (%p) Restarting process "
3444 "from state: %s",
3445 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003446 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3447 PrivateResume();
3448 }
3449 } else {
3450 return_value = true;
3451 SynchronouslyNotifyStateChanged(state);
3452 }
3453 }
3454 break;
3455 }
3456
3457 // Forcing the next event delivery is a one shot deal. So reset it here.
3458 m_force_next_event_delivery = false;
3459
3460 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003461 // events get coalesced.) But we only coalesce against events we actually
3462 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3463 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3464 // done, because the PublicState reflects the last event pulled off the
3465 // queue, and there may be several events stacked up on the queue unserviced.
3466 // So the PublicState may not reflect the last broadcasted event yet.
3467 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003468
3469 if (return_value)
3470 m_last_broadcast_state = state;
3471
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003472 LLDB_LOGF(log,
3473 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3474 "broadcast state: %s - %s",
3475 static_cast<void *>(event_ptr), StateAsCString(state),
3476 StateAsCString(m_last_broadcast_state),
3477 return_value ? "YES" : "NO");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003478 return return_value;
3479}
3480
3481bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3482 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3483
3484 bool already_running = PrivateStateThreadIsValid();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003485 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
3486 already_running ? " already running"
3487 : " starting private state thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003488
3489 if (!is_secondary_thread && already_running)
3490 return true;
3491
Adrian Prantl05097242018-04-30 16:49:04 +00003492 // Create a thread that watches our internal state and controls which events
3493 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003494 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003495 uint32_t max_len = llvm::get_max_thread_name_length();
3496 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003497 // On platforms with abbreviated thread name lengths, choose thread names
3498 // that fit within the limit.
3499 if (already_running)
3500 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3501 else
3502 snprintf(thread_name, sizeof(thread_name), "intern-state");
3503 } else {
3504 if (already_running)
3505 snprintf(thread_name, sizeof(thread_name),
3506 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3507 GetID());
3508 else
3509 snprintf(thread_name, sizeof(thread_name),
3510 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3511 }
3512
3513 // Create the private state thread, and start it running.
3514 PrivateStateThreadArgs *args_ptr =
3515 new PrivateStateThreadArgs(this, is_secondary_thread);
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003516 llvm::Expected<HostThread> private_state_thread =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003517 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003518 (void *)args_ptr, 8 * 1024 * 1024);
3519 if (!private_state_thread) {
3520 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3521 "failed to launch host thread: {}",
3522 llvm::toString(private_state_thread.takeError()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003523 return false;
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003524 }
3525
3526 assert(private_state_thread->IsJoinable());
3527 m_private_state_thread = *private_state_thread;
3528 ResumePrivateStateThread();
3529 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003530}
3531
3532void Process::PausePrivateStateThread() {
3533 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3534}
3535
3536void Process::ResumePrivateStateThread() {
3537 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3538}
3539
3540void Process::StopPrivateStateThread() {
3541 if (m_private_state_thread.IsJoinable())
3542 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3543 else {
3544 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003545 LLDB_LOGF(
3546 log,
3547 "Went to stop the private state thread, but it was already invalid.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003548 }
3549}
3550
3551void Process::ControlPrivateStateThread(uint32_t signal) {
3552 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3553
3554 assert(signal == eBroadcastInternalStateControlStop ||
3555 signal == eBroadcastInternalStateControlPause ||
3556 signal == eBroadcastInternalStateControlResume);
3557
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003558 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003559
3560 // Signal the private state thread
3561 if (m_private_state_thread.IsJoinable()) {
3562 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003563 // It is important to do this outside of the if below, because it's
3564 // possible that the thread state is invalid but that the thread is waiting
3565 // on a control event instead of simply being on its way out (this should
3566 // not happen, but it apparently can).
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003567 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003568 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3569 m_private_state_control_broadcaster.BroadcastEvent(signal,
3570 event_receipt_sp);
3571
3572 // Wait for the event receipt or for the private state thread to exit
3573 bool receipt_received = false;
3574 if (PrivateStateThreadIsValid()) {
3575 while (!receipt_received) {
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003576 // Check for a receipt for n seconds and then check if the private
Adrian Prantl05097242018-04-30 16:49:04 +00003577 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003578 receipt_received =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003579 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003580 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003581 // Check if the private state thread is still around. If it isn't
3582 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003583 if (!PrivateStateThreadIsValid())
3584 break; // Private state thread exited or is exiting, we are done
3585 }
3586 }
3587 }
3588
3589 if (signal == eBroadcastInternalStateControlStop) {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003590 thread_result_t result = {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003591 m_private_state_thread.Join(&result);
3592 m_private_state_thread.Reset();
3593 }
3594 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003595 LLDB_LOGF(
3596 log,
3597 "Private state thread already dead, no need to signal it to stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003598 }
3599}
3600
3601void Process::SendAsyncInterrupt() {
3602 if (PrivateStateThreadIsValid())
3603 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3604 nullptr);
3605 else
3606 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3607}
3608
3609void Process::HandlePrivateEvent(EventSP &event_sp) {
3610 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3611 m_resume_requested = false;
3612
3613 const StateType new_state =
3614 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3615
3616 // First check to see if anybody wants a shot at this event:
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003617 if (m_next_event_action_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003618 NextEventAction::EventActionResult action_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003619 m_next_event_action_up->PerformAction(event_sp);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003620 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003621
3622 switch (action_result) {
3623 case NextEventAction::eEventActionSuccess:
3624 SetNextEventAction(nullptr);
3625 break;
3626
3627 case NextEventAction::eEventActionRetry:
3628 break;
3629
3630 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003631 // Handle Exiting Here. If we already got an exited event, we should
3632 // just propagate it. Otherwise, swallow this event, and set our state
3633 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003634 if (new_state != eStateExited) {
3635 // FIXME: should cons up an exited event, and discard this one.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003636 SetExitStatus(0, m_next_event_action_up->GetExitString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003637 SetNextEventAction(nullptr);
3638 return;
3639 }
3640 SetNextEventAction(nullptr);
3641 break;
3642 }
3643 }
3644
3645 // See if we should broadcast this state to external clients?
3646 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3647
3648 if (should_broadcast) {
3649 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3650 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003651 LLDB_LOGF(log,
3652 "Process::%s (pid = %" PRIu64
3653 ") broadcasting new state %s (old state %s) to %s",
3654 __FUNCTION__, GetID(), StateAsCString(new_state),
3655 StateAsCString(GetState()),
3656 is_hijacked ? "hijacked" : "public");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003657 }
3658 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3659 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003660 // Only push the input handler if we aren't fowarding events, as this
3661 // means the curses GUI is in use... Or don't push it if we are launching
3662 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003663 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3664 new_state != eStateLaunching && new_state != eStateAttaching) {
3665 PushProcessIOHandler();
3666 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3667 eBroadcastAlways);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003668 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
3669 __FUNCTION__, m_iohandler_sync.GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003670 }
3671 } else if (StateIsStoppedState(new_state, false)) {
3672 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003673 // If the lldb_private::Debugger is handling the events, we don't want
3674 // to pop the process IOHandler here, we want to do it when we receive
3675 // the stopped event so we can carefully control when the process
3676 // IOHandler is popped because when we stop we want to display some
3677 // text stating how and why we stopped, then maybe some
3678 // process/thread/frame info, and then we want the "(lldb) " prompt to
3679 // show up. If we pop the process IOHandler here, then we will cause
3680 // the command interpreter to become the top IOHandler after the
3681 // process pops off and it will update its prompt right away... See the
3682 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003683 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3684 // Otherwise we end up getting overlapping "(lldb) " prompts and
3685 // garbled output.
3686 //
3687 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003688 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3689 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003690 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003691 // thread plans, or when commands want to run in synchronous mode and
3692 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003693 // that will hijack the events is a simple expression:
3694 //
3695 // (lldb) expr (int)puts("hello")
3696 //
3697 // This will cause the internal process state thread to resume and halt
3698 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3699 // events) and we do need the IO handler to be pushed and popped
3700 // correctly.
3701
3702 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3703 PopProcessIOHandler();
3704 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003705 }
3706
3707 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003708 } else {
3709 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003710 LLDB_LOGF(
3711 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003712 "Process::%s (pid = %" PRIu64
3713 ") suppressing state %s (old state %s): should_broadcast == false",
3714 __FUNCTION__, GetID(), StateAsCString(new_state),
3715 StateAsCString(GetState()));
3716 }
3717 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003718}
3719
Zachary Turner97206d52017-05-12 04:51:55 +00003720Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003721 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003722 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003723 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003724 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003725
3726 // Ask the process subclass to actually halt our process
3727 bool caused_stop;
3728 error = DoHalt(caused_stop);
3729
3730 DidHalt();
3731 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003732}
3733
Kate Stoneb9c1b512016-09-06 20:57:50 +00003734thread_result_t Process::PrivateStateThread(void *arg) {
3735 std::unique_ptr<PrivateStateThreadArgs> args_up(
3736 static_cast<PrivateStateThreadArgs *>(arg));
3737 thread_result_t result =
3738 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3739 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003740}
3741
Kate Stoneb9c1b512016-09-06 20:57:50 +00003742thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3743 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003744
Kate Stoneb9c1b512016-09-06 20:57:50 +00003745 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003746 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3747 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003748
Kate Stoneb9c1b512016-09-06 20:57:50 +00003749 bool exit_now = false;
3750 bool interrupt_requested = false;
3751 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003752 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003753 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003754 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003755 LLDB_LOGF(log,
3756 "Process::%s (arg = %p, pid = %" PRIu64
3757 ") got a control event: %d",
3758 __FUNCTION__, static_cast<void *>(this), GetID(),
3759 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003760
Kate Stoneb9c1b512016-09-06 20:57:50 +00003761 switch (event_sp->GetType()) {
3762 case eBroadcastInternalStateControlStop:
3763 exit_now = true;
3764 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003765
Kate Stoneb9c1b512016-09-06 20:57:50 +00003766 case eBroadcastInternalStateControlPause:
3767 control_only = true;
3768 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003769
Kate Stoneb9c1b512016-09-06 20:57:50 +00003770 case eBroadcastInternalStateControlResume:
3771 control_only = false;
3772 break;
3773 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003774
Kate Stoneb9c1b512016-09-06 20:57:50 +00003775 continue;
3776 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3777 if (m_public_state.GetValue() == eStateAttaching) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003778 LLDB_LOGF(log,
3779 "Process::%s (arg = %p, pid = %" PRIu64
3780 ") woke up with an interrupt while attaching - "
3781 "forwarding interrupt.",
3782 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003783 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3784 } else if (StateIsRunningState(m_last_broadcast_state)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003785 LLDB_LOGF(log,
3786 "Process::%s (arg = %p, pid = %" PRIu64
3787 ") woke up with an interrupt - Halting.",
3788 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00003789 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003790 if (error.Fail() && log)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003791 LLDB_LOGF(log,
3792 "Process::%s (arg = %p, pid = %" PRIu64
3793 ") failed to halt the process: %s",
3794 __FUNCTION__, static_cast<void *>(this), GetID(),
3795 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00003796 // Halt should generate a stopped event. Make a note of the fact that
3797 // we were doing the interrupt, so we can set the interrupted flag
3798 // after we receive the event. We deliberately set this to true even if
3799 // HaltPrivate failed, so that we can interrupt on the next natural
3800 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003801 interrupt_requested = true;
3802 } else {
3803 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00003804 // running and sends an interrupt request, but the process actually
3805 // stops before we receive it. In that case, we can just ignore the
3806 // request. We use m_last_broadcast_state, because the Stopped event
3807 // may not have been popped of the event queue yet, which is when the
3808 // public state gets updated.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003809 LLDB_LOGF(log,
3810 "Process::%s ignoring interrupt as we have already stopped.",
3811 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003812 }
3813 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003814 }
3815
Kate Stoneb9c1b512016-09-06 20:57:50 +00003816 const StateType internal_state =
3817 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003818
Kate Stoneb9c1b512016-09-06 20:57:50 +00003819 if (internal_state != eStateInvalid) {
3820 if (m_clear_thread_plans_on_stop &&
3821 StateIsStoppedState(internal_state, true)) {
3822 m_clear_thread_plans_on_stop = false;
3823 m_thread_list.DiscardThreadPlans();
3824 }
3825
3826 if (interrupt_requested) {
3827 if (StateIsStoppedState(internal_state, true)) {
3828 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00003829 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00003830 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3831 interrupt_requested = false;
3832 } else if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003833 LLDB_LOGF(log,
3834 "Process::%s interrupt_requested, but a non-stopped "
3835 "state '%s' received.",
3836 __FUNCTION__, StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003837 }
3838 }
3839
3840 HandlePrivateEvent(event_sp);
3841 }
3842
3843 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3844 internal_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003845 LLDB_LOGF(log,
3846 "Process::%s (arg = %p, pid = %" PRIu64
3847 ") about to exit with internal state %s...",
3848 __FUNCTION__, static_cast<void *>(this), GetID(),
3849 StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003850
3851 break;
3852 }
3853 }
3854
3855 // Verify log is still enabled before attempting to write to it...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003856 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3857 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003858
3859 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00003860 // will have already acquired the public_run_lock, and isn't done with what
3861 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003862 if (!is_secondary_thread)
3863 m_public_run_lock.SetStopped();
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003864 return {};
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003865}
3866
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003867// Process Event Data
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003868
Kate Stoneb9c1b512016-09-06 20:57:50 +00003869Process::ProcessEventData::ProcessEventData()
3870 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3871 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003872
Kate Stoneb9c1b512016-09-06 20:57:50 +00003873Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3874 StateType state)
3875 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3876 m_update_state(0), m_interrupted(false) {
3877 if (process_sp)
3878 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003879}
3880
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003881Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003882
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003883ConstString Process::ProcessEventData::GetFlavorString() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003884 static ConstString g_flavor("Process::ProcessEventData");
3885 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003886}
3887
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003888ConstString Process::ProcessEventData::GetFlavor() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003889 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003890}
3891
Kate Stoneb9c1b512016-09-06 20:57:50 +00003892void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
3893 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00003894
Kate Stoneb9c1b512016-09-06 20:57:50 +00003895 if (!process_sp)
3896 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003897
Kate Stoneb9c1b512016-09-06 20:57:50 +00003898 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00003899 // pulled off of the private process event queue, and then any number of
3900 // times, first when it gets pulled off of the public event queue, then other
3901 // times when we're pretending that this is where we stopped at the end of
3902 // expression evaluation. m_update_state is used to distinguish these three
3903 // cases; it is 0 when we're just pulling it off for private handling, and >
3904 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00003905 // command handling then.
3906 if (m_update_state != 1)
3907 return;
3908
3909 process_sp->SetPublicState(
3910 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
3911
Jason Molendab3a3cd12016-12-08 06:27:29 +00003912 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00003913 // Let process subclasses know we are about to do a public stop and do
3914 // anything they might need to in order to speed up register and memory
3915 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00003916 process_sp->WillPublicStop();
3917 }
3918
Kate Stoneb9c1b512016-09-06 20:57:50 +00003919 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00003920 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
3921 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00003922 // end up restarting the process.
3923 if (m_interrupted)
3924 return;
3925
3926 // If we're stopped and haven't restarted, then do the StopInfo actions here:
3927 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003928 ThreadList &curr_thread_list = process_sp->GetThreadList();
3929 uint32_t num_threads = curr_thread_list.GetSize();
3930 uint32_t idx;
3931
3932 // The actions might change one of the thread's stop_info's opinions about
Adrian Prantl05097242018-04-30 16:49:04 +00003933 // whether we should stop the process, so we need to query that as we go.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003934
3935 // One other complication here, is that we try to catch any case where the
Adrian Prantl05097242018-04-30 16:49:04 +00003936 // target has run (except for expressions) and immediately exit, but if we
3937 // get that wrong (which is possible) then the thread list might have
3938 // changed, and that would cause our iteration here to crash. We could
3939 // make a copy of the thread list, but we'd really like to also know if it
3940 // has changed at all, so we make up a vector of the thread ID's and check
3941 // what we get back against this list & bag out if anything differs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003942 std::vector<uint32_t> thread_index_array(num_threads);
3943 for (idx = 0; idx < num_threads; ++idx)
3944 thread_index_array[idx] =
3945 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3946
3947 // Use this to track whether we should continue from here. We will only
Adrian Prantl05097242018-04-30 16:49:04 +00003948 // continue the target running if no thread says we should stop. Of course
3949 // if some thread's PerformAction actually sets the target running, then it
3950 // doesn't matter what the other threads say...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003951
3952 bool still_should_stop = false;
3953
3954 // Sometimes - for instance if we have a bug in the stub we are talking to,
Adrian Prantl05097242018-04-30 16:49:04 +00003955 // we stop but no thread has a valid stop reason. In that case we should
3956 // just stop, because we have no way of telling what the right thing to do
3957 // is, and it's better to let the user decide than continue behind their
3958 // backs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003959
3960 bool does_anybody_have_an_opinion = false;
3961
3962 for (idx = 0; idx < num_threads; ++idx) {
3963 curr_thread_list = process_sp->GetThreadList();
3964 if (curr_thread_list.GetSize() != num_threads) {
3965 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
3966 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003967 LLDB_LOGF(
3968 log,
3969 "Number of threads changed from %u to %u while processing event.",
3970 num_threads, curr_thread_list.GetSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003971 break;
3972 }
3973
3974 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3975
3976 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
3977 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
3978 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003979 LLDB_LOGF(log,
3980 "The thread at position %u changed from %u to %u while "
3981 "processing event.",
3982 idx, thread_index_array[idx], thread_sp->GetIndexID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003983 break;
3984 }
3985
3986 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
3987 if (stop_info_sp && stop_info_sp->IsValid()) {
3988 does_anybody_have_an_opinion = true;
3989 bool this_thread_wants_to_stop;
3990 if (stop_info_sp->GetOverrideShouldStop()) {
3991 this_thread_wants_to_stop =
3992 stop_info_sp->GetOverriddenShouldStopValue();
3993 } else {
3994 stop_info_sp->PerformAction(event_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +00003995 // The stop action might restart the target. If it does, then we
3996 // want to mark that in the event so that whoever is receiving it
3997 // will know to wait for the running event and reflect that state
3998 // appropriately. We also need to stop processing actions, since they
3999 // aren't expecting the target to be running.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004000
4001 // FIXME: we might have run.
4002 if (stop_info_sp->HasTargetRunSinceMe()) {
4003 SetRestarted(true);
4004 break;
4005 }
4006
4007 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004008 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004009
4010 if (!still_should_stop)
4011 still_should_stop = this_thread_wants_to_stop;
4012 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004013 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004014
4015 if (!GetRestarted()) {
4016 if (!still_should_stop && does_anybody_have_an_opinion) {
4017 // We've been asked to continue, so do that here.
4018 SetRestarted(true);
Adrian Prantl05097242018-04-30 16:49:04 +00004019 // Use the public resume method here, since this is just extending a
4020 // public resume.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004021 process_sp->PrivateResume();
4022 } else {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004023 bool hijacked =
4024 process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4025 !process_sp->StateChangedIsHijackedForSynchronousResume();
Jim Ingham3139fc92019-03-01 18:13:38 +00004026
4027 if (!hijacked) {
4028 // If we didn't restart, run the Stop Hooks here.
4029 // Don't do that if state changed events aren't hooked up to the
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004030 // public (or SyncResume) broadcasters. StopHooks are just for
4031 // real public stops. They might also restart the target,
Jim Ingham3139fc92019-03-01 18:13:38 +00004032 // so watch for that.
4033 process_sp->GetTarget().RunStopHooks();
4034 if (process_sp->GetPrivateState() == eStateRunning)
4035 SetRestarted(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004036 }
4037 }
4038 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004039}
Zachary Turner805e7102019-03-04 21:51:03 +00004040}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004041
Kate Stoneb9c1b512016-09-06 20:57:50 +00004042void Process::ProcessEventData::Dump(Stream *s) const {
4043 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004044
Kate Stoneb9c1b512016-09-06 20:57:50 +00004045 if (process_sp)
4046 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4047 static_cast<void *>(process_sp.get()), process_sp->GetID());
4048 else
4049 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004050
Kate Stoneb9c1b512016-09-06 20:57:50 +00004051 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004052}
4053
4054const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004055Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4056 if (event_ptr) {
4057 const EventData *event_data = event_ptr->GetData();
4058 if (event_data &&
4059 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4060 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4061 }
4062 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004063}
4064
4065ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004066Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4067 ProcessSP process_sp;
4068 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4069 if (data)
4070 process_sp = data->GetProcessSP();
4071 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004072}
4073
Kate Stoneb9c1b512016-09-06 20:57:50 +00004074StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4075 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4076 if (data == nullptr)
4077 return eStateInvalid;
4078 else
4079 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004080}
4081
Kate Stoneb9c1b512016-09-06 20:57:50 +00004082bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4083 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4084 if (data == nullptr)
4085 return false;
4086 else
4087 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004088}
4089
Kate Stoneb9c1b512016-09-06 20:57:50 +00004090void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4091 bool new_value) {
4092 ProcessEventData *data =
4093 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4094 if (data != nullptr)
4095 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004096}
4097
Jim Ingham0161b492013-02-09 01:29:05 +00004098size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004099Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4100 ProcessEventData *data =
4101 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4102 if (data != nullptr)
4103 return data->GetNumRestartedReasons();
4104 else
4105 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004106}
4107
4108const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004109Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4110 size_t idx) {
4111 ProcessEventData *data =
4112 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4113 if (data != nullptr)
4114 return data->GetRestartedReasonAtIndex(idx);
4115 else
4116 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004117}
4118
Kate Stoneb9c1b512016-09-06 20:57:50 +00004119void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4120 const char *reason) {
4121 ProcessEventData *data =
4122 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4123 if (data != nullptr)
4124 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004125}
4126
Kate Stoneb9c1b512016-09-06 20:57:50 +00004127bool Process::ProcessEventData::GetInterruptedFromEvent(
4128 const Event *event_ptr) {
4129 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4130 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004131 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004132 else
4133 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004134}
4135
Kate Stoneb9c1b512016-09-06 20:57:50 +00004136void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4137 bool new_value) {
4138 ProcessEventData *data =
4139 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4140 if (data != nullptr)
4141 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004142}
4143
Kate Stoneb9c1b512016-09-06 20:57:50 +00004144bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4145 ProcessEventData *data =
4146 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4147 if (data) {
4148 data->SetUpdateStateOnRemoval();
4149 return true;
4150 }
4151 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004152}
4153
Jim Inghamb87b9e62018-06-26 23:38:58 +00004154lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004155
4156void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4157 exe_ctx.SetTargetPtr(&GetTarget());
4158 exe_ctx.SetProcessPtr(this);
4159 exe_ctx.SetThreadPtr(nullptr);
4160 exe_ctx.SetFramePtr(nullptr);
4161}
4162
4163// uint32_t
4164// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4165// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004166//{
4167// return 0;
4168//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004169//
4170// ArchSpec
4171// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004172//{
4173// return Host::GetArchSpecForExistingProcess (pid);
4174//}
4175//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004176// ArchSpec
4177// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004178//{
4179// return Host::GetArchSpecForExistingProcess (process_name);
4180//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004181
Kate Stoneb9c1b512016-09-06 20:57:50 +00004182void Process::AppendSTDOUT(const char *s, size_t len) {
4183 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4184 m_stdout_data.append(s, len);
4185 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4186 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004187}
4188
Kate Stoneb9c1b512016-09-06 20:57:50 +00004189void Process::AppendSTDERR(const char *s, size_t len) {
4190 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4191 m_stderr_data.append(s, len);
4192 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4193 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004194}
4195
Kate Stoneb9c1b512016-09-06 20:57:50 +00004196void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4197 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4198 m_profile_data.push_back(one_profile_data);
4199 BroadcastEventIfUnique(eBroadcastBitProfileData,
4200 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004201}
4202
Kate Stoneb9c1b512016-09-06 20:57:50 +00004203void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4204 const StructuredDataPluginSP &plugin_sp) {
4205 BroadcastEvent(
4206 eBroadcastBitStructuredData,
4207 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004208}
4209
4210StructuredDataPluginSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004211Process::GetStructuredDataPlugin(ConstString type_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004212 auto find_it = m_structured_data_plugin_map.find(type_name);
4213 if (find_it != m_structured_data_plugin_map.end())
4214 return find_it->second;
4215 else
4216 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004217}
4218
Zachary Turner97206d52017-05-12 04:51:55 +00004219size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004220 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4221 if (m_profile_data.empty())
4222 return 0;
4223
4224 std::string &one_profile_data = m_profile_data.front();
4225 size_t bytes_available = one_profile_data.size();
4226 if (bytes_available > 0) {
4227 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004228 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4229 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004230 if (bytes_available > buf_size) {
4231 memcpy(buf, one_profile_data.c_str(), buf_size);
4232 one_profile_data.erase(0, buf_size);
4233 bytes_available = buf_size;
4234 } else {
4235 memcpy(buf, one_profile_data.c_str(), bytes_available);
4236 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004237 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004238 }
4239 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004240}
4241
Greg Clayton93e86192011-11-13 04:45:22 +00004242// Process STDIO
Greg Clayton93e86192011-11-13 04:45:22 +00004243
Zachary Turner97206d52017-05-12 04:51:55 +00004244size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004245 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4246 size_t bytes_available = m_stdout_data.size();
4247 if (bytes_available > 0) {
4248 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004249 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4250 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004251 if (bytes_available > buf_size) {
4252 memcpy(buf, m_stdout_data.c_str(), buf_size);
4253 m_stdout_data.erase(0, buf_size);
4254 bytes_available = buf_size;
4255 } else {
4256 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4257 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004258 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004259 }
4260 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004261}
4262
Zachary Turner97206d52017-05-12 04:51:55 +00004263size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004264 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4265 size_t bytes_available = m_stderr_data.size();
4266 if (bytes_available > 0) {
4267 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004268 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4269 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004270 if (bytes_available > buf_size) {
4271 memcpy(buf, m_stderr_data.c_str(), buf_size);
4272 m_stderr_data.erase(0, buf_size);
4273 bytes_available = buf_size;
4274 } else {
4275 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4276 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004277 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004278 }
4279 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004280}
4281
Kate Stoneb9c1b512016-09-06 20:57:50 +00004282void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4283 size_t src_len) {
4284 Process *process = (Process *)baton;
4285 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004286}
4287
Kate Stoneb9c1b512016-09-06 20:57:50 +00004288class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004289public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004290 IOHandlerProcessSTDIO(Process *process, int write_fd)
4291 : IOHandler(process->GetTarget().GetDebugger(),
4292 IOHandler::Type::ProcessIO),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004293 m_process(process),
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00004294 m_read_file(GetInputFD(), File::eOpenOptionRead, false),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004295 m_write_file(write_fd, File::eOpenOptionWrite, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004296 m_pipe.CreateNew(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004297 }
4298
4299 ~IOHandlerProcessSTDIO() override = default;
4300
Adrian Prantl05097242018-04-30 16:49:04 +00004301 // Each IOHandler gets to run until it is done. It should read data from the
4302 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004303 void Run() override {
4304 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4305 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4306 SetIsDone(true);
4307 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004308 }
4309
Kate Stoneb9c1b512016-09-06 20:57:50 +00004310 SetIsDone(false);
4311 const int read_fd = m_read_file.GetDescriptor();
4312 TerminalState terminal_state;
4313 terminal_state.Save(read_fd, false);
4314 Terminal terminal(read_fd);
4315 terminal.SetCanonical(false);
4316 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004317// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004318#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004319 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4320 m_is_running = true;
4321 while (!GetIsDone()) {
4322 SelectHelper select_helper;
4323 select_helper.FDSetRead(read_fd);
4324 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004325 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004326
Kate Stoneb9c1b512016-09-06 20:57:50 +00004327 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004328 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004329 } else {
4330 char ch = 0;
4331 size_t n;
4332 if (select_helper.FDIsSetRead(read_fd)) {
4333 n = 1;
4334 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4335 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4336 SetIsDone(true);
4337 } else
4338 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004339 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004340 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4341 size_t bytes_read;
4342 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004343 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004344 if (error.Success()) {
4345 switch (ch) {
4346 case 'q':
4347 SetIsDone(true);
4348 break;
4349 case 'i':
4350 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004351 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004352 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004353 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004354 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004355 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004356 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004357 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004358 m_is_running = false;
4359#endif
4360 terminal_state.Restore();
4361 }
4362
4363 void Cancel() override {
4364 SetIsDone(true);
4365 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004366 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4367 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004368 //
4369 // (lldb) step_process_thousands_of_times
4370 //
4371 // In this case the command interpreter will be in the middle of handling
4372 // the command and if the process pushes and pops the IOHandler thousands
4373 // of times, we can end up writing to m_pipe without ever consuming the
4374 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4375 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4376 if (m_is_running) {
4377 char ch = 'q'; // Send 'q' for quit
4378 size_t bytes_written = 0;
4379 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004380 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004381 }
4382
4383 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004384 // Do only things that are safe to do in an interrupt context (like in a
4385 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004386 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4387 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004388 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004389 if (m_active) {
4390 char ch = 'i'; // Send 'i' for interrupt
4391 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004392 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004393 return result.Success();
4394 } else {
4395 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004396 // currently so do the right thing if we aren't actively watching for
4397 // STDIN by sending the interrupt to the process. Otherwise the write to
4398 // the pipe above would do nothing. This can happen when the command
4399 // interpreter is running and gets a "expression ...". It will be on the
4400 // IOHandler thread and sending the input is complete to the delegate
4401 // which will cause the expression to run, which will push the process IO
4402 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004403
4404 if (StateIsRunningState(m_process->GetState())) {
4405 m_process->SendAsyncInterrupt();
4406 return true;
4407 }
4408 }
4409 return false;
4410 }
4411
4412 void GotEOF() override {}
4413
Greg Clayton44d93782014-01-27 23:43:24 +00004414protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004415 Process *m_process;
Lawrence D'Annaf913fd62019-10-03 04:31:46 +00004416 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
4417 NativeFile m_write_file; // Write to this file (usually the master pty for
4418 // getting io to debuggee)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004419 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004420 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004421};
4422
Kate Stoneb9c1b512016-09-06 20:57:50 +00004423void Process::SetSTDIOFileDescriptor(int fd) {
4424 // First set up the Read Thread for reading/handling process I/O
4425
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004426 std::unique_ptr<ConnectionFileDescriptor> conn_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004427 new ConnectionFileDescriptor(fd, true));
4428
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004429 if (conn_up) {
4430 m_stdio_communication.SetConnection(conn_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004431 if (m_stdio_communication.IsConnected()) {
4432 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4433 STDIOReadThreadBytesReceived, this);
4434 m_stdio_communication.StartReadThread();
4435
4436 // Now read thread is set up, set up input reader.
4437
4438 if (!m_process_input_reader)
Jonas Devlieghere796ac802019-02-11 23:13:08 +00004439 m_process_input_reader =
4440 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004441 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004442 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004443}
4444
Kate Stoneb9c1b512016-09-06 20:57:50 +00004445bool Process::ProcessIOHandlerIsActive() {
4446 IOHandlerSP io_handler_sp(m_process_input_reader);
4447 if (io_handler_sp)
4448 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4449 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004450}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004451bool Process::PushProcessIOHandler() {
4452 IOHandlerSP io_handler_sp(m_process_input_reader);
4453 if (io_handler_sp) {
4454 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004455 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004456
Kate Stoneb9c1b512016-09-06 20:57:50 +00004457 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004458 // If we evaluate an utility function, then we don't cancel the current
4459 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4460 // existing IOHandler that potentially provides the user interface (e.g.
4461 // the IOHandler for Editline).
4462 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004463 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
4464 cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004465 return true;
4466 }
4467 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004468}
4469
Kate Stoneb9c1b512016-09-06 20:57:50 +00004470bool Process::PopProcessIOHandler() {
4471 IOHandlerSP io_handler_sp(m_process_input_reader);
4472 if (io_handler_sp)
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004473 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004474 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004475}
4476
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004477// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004478void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004479
Kate Stoneb9c1b512016-09-06 20:57:50 +00004480void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004481
Kate Stoneb9c1b512016-09-06 20:57:50 +00004482namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004483// RestorePlanState is used to record the "is private", "is master" and "okay
4484// to discard" fields of the plan we are running, and reset it on Clean or on
4485// destruction. It will only reset the state once, so you can call Clean and
4486// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004487
Kate Stoneb9c1b512016-09-06 20:57:50 +00004488class RestorePlanState {
4489public:
4490 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4491 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4492 if (m_thread_plan_sp) {
4493 m_private = m_thread_plan_sp->GetPrivate();
4494 m_is_master = m_thread_plan_sp->IsMasterPlan();
4495 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4496 }
4497 }
4498
4499 ~RestorePlanState() { Clean(); }
4500
4501 void Clean() {
4502 if (!m_already_reset && m_thread_plan_sp) {
4503 m_already_reset = true;
4504 m_thread_plan_sp->SetPrivate(m_private);
4505 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4506 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4507 }
4508 }
4509
4510private:
4511 lldb::ThreadPlanSP m_thread_plan_sp;
4512 bool m_already_reset;
4513 bool m_private;
4514 bool m_is_master;
4515 bool m_okay_to_discard;
4516};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004517} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004518
Pavel Labath2ce22162016-12-01 10:57:30 +00004519static microseconds
4520GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4521 const milliseconds default_one_thread_timeout(250);
4522
4523 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004524 if (!options.GetTimeout()) {
4525 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4526 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004527 }
4528
4529 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004530 if (options.GetOneThreadTimeout())
4531 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004532
4533 // Otherwise use half the total timeout, bounded by the
4534 // default_one_thread_timeout.
4535 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004536 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004537}
4538
4539static Timeout<std::micro>
4540GetExpressionTimeout(const EvaluateExpressionOptions &options,
4541 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004542 // If we are going to run all threads the whole time, or if we are only going
4543 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004544 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004545 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004546
4547 if (before_first_timeout)
4548 return GetOneThreadExpressionTimeout(options);
4549
Pavel Labath43d35412016-12-06 11:24:51 +00004550 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004551 return llvm::None;
4552 else
Pavel Labath43d35412016-12-06 11:24:51 +00004553 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004554}
4555
Pavel Labath45dde232017-05-25 10:50:06 +00004556static llvm::Optional<ExpressionResults>
4557HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4558 RestorePlanState &restorer, const EventSP &event_sp,
4559 EventSP &event_to_broadcast_sp,
4560 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4561 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4562
4563 ThreadPlanSP plan = thread.GetCompletedPlan();
4564 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4565 LLDB_LOG(log, "execution completed successfully");
4566
4567 // Restore the plan state so it will get reported as intended when we are
4568 // done.
4569 restorer.Clean();
4570 return eExpressionCompleted;
4571 }
4572
4573 StopInfoSP stop_info_sp = thread.GetStopInfo();
4574 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4575 stop_info_sp->ShouldNotify(event_sp.get())) {
4576 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4577 if (!options.DoesIgnoreBreakpoints()) {
4578 // Restore the plan state and then force Private to false. We are going
4579 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004580 // it won't report correctly when we continue to its termination later
4581 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004582 restorer.Clean();
4583 thread_plan_sp->SetPrivate(false);
4584 event_to_broadcast_sp = event_sp;
4585 }
4586 return eExpressionHitBreakpoint;
4587 }
4588
4589 if (!handle_interrupts &&
4590 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4591 return llvm::None;
4592
4593 LLDB_LOG(log, "thread plan did not successfully complete");
4594 if (!options.DoesUnwindOnError())
4595 event_to_broadcast_sp = event_sp;
4596 return eExpressionInterrupted;
4597}
4598
Jim Ingham1624a2d2014-05-05 02:26:40 +00004599ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004600Process::RunThreadPlan(ExecutionContext &exe_ctx,
4601 lldb::ThreadPlanSP &thread_plan_sp,
4602 const EvaluateExpressionOptions &options,
4603 DiagnosticManager &diagnostic_manager) {
4604 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004605
Kate Stoneb9c1b512016-09-06 20:57:50 +00004606 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4607
4608 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004609 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004610 eDiagnosticSeverityError,
4611 "RunThreadPlan called with empty thread plan.");
4612 return eExpressionSetupError;
4613 }
4614
4615 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004616 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004617 eDiagnosticSeverityError,
4618 "RunThreadPlan called with an invalid thread plan.");
4619 return eExpressionSetupError;
4620 }
4621
4622 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004623 diagnostic_manager.PutString(eDiagnosticSeverityError,
4624 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004625 return eExpressionSetupError;
4626 }
4627
4628 Thread *thread = exe_ctx.GetThreadPtr();
4629 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004630 diagnostic_manager.PutString(eDiagnosticSeverityError,
4631 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004632 return eExpressionSetupError;
4633 }
4634
4635 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004636 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004637
4638 RestorePlanState thread_plan_restorer(thread_plan_sp);
4639
Adrian Prantl05097242018-04-30 16:49:04 +00004640 // We rely on the thread plan we are running returning "PlanCompleted" if
4641 // when it successfully completes. For that to be true the plan can't be
4642 // private - since private plans suppress themselves in the GetCompletedPlan
4643 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004644
4645 thread_plan_sp->SetPrivate(false);
4646
4647 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004648 // when they are done we will end up asking the plan above us whether we
4649 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004650
4651 thread_plan_sp->SetIsMasterPlan(true);
4652 thread_plan_sp->SetOkayToDiscard(false);
4653
Raphael Isemannc01783a2018-08-29 22:50:54 +00004654 // If we are running some utility expression for LLDB, we now have to mark
4655 // this in the ProcesModID of this process. This RAII takes care of marking
4656 // and reverting the mark it once we are done running the expression.
4657 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4658
Kate Stoneb9c1b512016-09-06 20:57:50 +00004659 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004660 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004661 eDiagnosticSeverityError,
4662 "RunThreadPlan called while the private state was not stopped.");
4663 return eExpressionSetupError;
4664 }
4665
4666 // Save the thread & frame from the exe_ctx for restoration after we run
4667 const uint32_t thread_idx_id = thread->GetIndexID();
4668 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4669 if (!selected_frame_sp) {
4670 thread->SetSelectedFrame(nullptr);
4671 selected_frame_sp = thread->GetSelectedFrame();
4672 if (!selected_frame_sp) {
4673 diagnostic_manager.Printf(
4674 eDiagnosticSeverityError,
4675 "RunThreadPlan called without a selected frame on thread %d",
4676 thread_idx_id);
4677 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004678 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004679 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004680
Adrian Prantl05097242018-04-30 16:49:04 +00004681 // Make sure the timeout values make sense. The one thread timeout needs to
4682 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004683 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4684 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004685 diagnostic_manager.PutString(eDiagnosticSeverityError,
4686 "RunThreadPlan called with one thread "
4687 "timeout greater than total timeout");
4688 return eExpressionSetupError;
4689 }
4690
Kate Stoneb9c1b512016-09-06 20:57:50 +00004691 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004692
Kate Stoneb9c1b512016-09-06 20:57:50 +00004693 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004694 // We don't want to do that either, so we should arrange to reset them as
4695 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004696
Kate Stoneb9c1b512016-09-06 20:57:50 +00004697 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004698
Kate Stoneb9c1b512016-09-06 20:57:50 +00004699 uint32_t selected_tid;
4700 StackID selected_stack_id;
4701 if (selected_thread_sp) {
4702 selected_tid = selected_thread_sp->GetIndexID();
4703 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4704 } else {
4705 selected_tid = LLDB_INVALID_THREAD_ID;
4706 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004707
Kate Stoneb9c1b512016-09-06 20:57:50 +00004708 HostThread backup_private_state_thread;
4709 lldb::StateType old_state = eStateInvalid;
4710 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004711
Kate Stoneb9c1b512016-09-06 20:57:50 +00004712 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4713 LIBLLDB_LOG_PROCESS));
4714 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4715 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004716 // public events on this thread, since we are the thread that is generating
4717 // public events. The simplest thing to do is to spin up a temporary thread
4718 // to handle private state thread events while we are fielding public
4719 // events here.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004720 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4721 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004722
Kate Stoneb9c1b512016-09-06 20:57:50 +00004723 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004724
Kate Stoneb9c1b512016-09-06 20:57:50 +00004725 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004726 // anything it pushes, and then stop, returning control here. But in the
4727 // normal course of things, the plan above us on the stack would be given a
4728 // shot at the stop event before deciding to stop, and we don't want that.
4729 // So we insert a "stopper" base plan on the stack before the plan we want
4730 // to run. Since base plans always stop and return control to the user,
4731 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004732 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4733 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4734 // Have to make sure our public state is stopped, since otherwise the
4735 // reporting logic below doesn't work correctly.
4736 old_state = m_public_state.GetValue();
4737 m_public_state.SetValueNoLock(eStateStopped);
4738
4739 // Now spin up the private state thread:
4740 StartPrivateStateThread(true);
4741 }
4742
4743 thread->QueueThreadPlan(
4744 thread_plan_sp, false); // This used to pass "true" does that make sense?
4745
4746 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004747 // In this case, we aren't actually going to run, we just want to stop
4748 // right away. Flush this thread so we will refetch the stacks and show the
4749 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004750 // FIXME: To make this prettier we should invent some stop reason for this,
4751 // but that
4752 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004753 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004754 thread->Flush();
4755 return eExpressionStoppedForDebug;
4756 }
4757
4758 ListenerSP listener_sp(
4759 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4760
4761 lldb::EventSP event_to_broadcast_sp;
4762
4763 {
4764 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004765 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004766 //
4767 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004768 // exits during execution), then the event is put into
4769 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004770
4771 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4772
4773 if (log) {
4774 StreamString s;
4775 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004776 LLDB_LOGF(log,
4777 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4778 " to run thread plan \"%s\".",
4779 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004780 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004781
4782 bool got_event;
4783 lldb::EventSP event_sp;
4784 lldb::StateType stop_state = lldb::eStateInvalid;
4785
4786 bool before_first_timeout = true; // This is set to false the first time
4787 // that we have to halt the target.
4788 bool do_resume = true;
4789 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004790
4791 // This is just for accounting:
4792 uint32_t num_resumes = 0;
4793
Kate Stoneb9c1b512016-09-06 20:57:50 +00004794 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00004795 // going to run one thread, then we don't need the first timeout. So we
4796 // pretend we are after the first timeout already.
4797 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004798 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00004799
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004800 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4801 options.GetStopOthers(), options.GetTryAllThreads(),
4802 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004803
Adrian Prantl05097242018-04-30 16:49:04 +00004804 // This isn't going to work if there are unfetched events on the queue. Are
4805 // there cases where we might want to run the remaining events here, and
4806 // then try to call the function? That's probably being too tricky for our
4807 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004808
4809 Event *other_events = listener_sp->PeekAtNextEvent();
4810 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004811 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004812 eDiagnosticSeverityError,
4813 "RunThreadPlan called with pending events on the queue.");
4814 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00004815 }
4816
Kate Stoneb9c1b512016-09-06 20:57:50 +00004817 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00004818 // calling a function as part of a thread plan, in which case the last
4819 // delivered event could be the running event, and we don't want event
4820 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004821 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00004822
Kate Stoneb9c1b512016-09-06 20:57:50 +00004823// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00004824// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00004825
Kate Stoneb9c1b512016-09-06 20:57:50 +00004826#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00004827 // It's pretty much impossible to write test cases for things like: One
4828 // thread timeout expires, I go to halt, but the process already stopped on
4829 // the function call stop breakpoint. Turning on this define will make us
4830 // not fetch the first event till after the halt. So if you run a quick
4831 // function, it will have completed, and the completion event will be
4832 // waiting, when you interrupt for halt. The expression evaluation should
4833 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004834 bool miss_first_event = true;
4835#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00004836 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00004837 // We usually want to resume the process if we get to the top of the
4838 // loop. The only exception is if we get two running events with no
4839 // intervening stop, which can happen, we will just wait for then next
4840 // stop event.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004841 LLDB_LOGF(log,
4842 "Top of while loop: do_resume: %i handle_running_event: %i "
4843 "before_first_timeout: %i.",
4844 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00004845
Kate Stoneb9c1b512016-09-06 20:57:50 +00004846 if (do_resume || handle_running_event) {
4847 // Do the initial resume and wait for the running event before going
4848 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00004849
Kate Stoneb9c1b512016-09-06 20:57:50 +00004850 if (do_resume) {
4851 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00004852 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004853 if (!resume_error.Success()) {
4854 diagnostic_manager.Printf(
4855 eDiagnosticSeverityError,
4856 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4857 resume_error.AsCString());
4858 return_value = eExpressionSetupError;
4859 break;
4860 }
Jason Molendaef7d6412015-08-06 03:27:10 +00004861 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004862
Pavel Labathd35031e12016-11-30 10:41:42 +00004863 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00004864 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004865 if (!got_event) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004866 LLDB_LOGF(log,
4867 "Process::RunThreadPlan(): didn't get any event after "
4868 "resume %" PRIu32 ", exiting.",
4869 num_resumes);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004870
4871 diagnostic_manager.Printf(eDiagnosticSeverityError,
4872 "didn't get any event after resume %" PRIu32
4873 ", exiting.",
4874 num_resumes);
4875 return_value = eExpressionSetupError;
4876 break;
4877 }
4878
4879 stop_state =
4880 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4881
4882 if (stop_state != eStateRunning) {
4883 bool restarted = false;
4884
4885 if (stop_state == eStateStopped) {
4886 restarted = Process::ProcessEventData::GetRestartedFromEvent(
4887 event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004888 LLDB_LOGF(
4889 log,
4890 "Process::RunThreadPlan(): didn't get running event after "
4891 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4892 "handle_running_event: %i).",
4893 num_resumes, StateAsCString(stop_state), restarted, do_resume,
4894 handle_running_event);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004895 }
4896
4897 if (restarted) {
4898 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00004899 // should ever get a stopped & restarted event here. But if I do,
4900 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004901 const bool clear_thread_plans = false;
4902 const bool use_run_lock = false;
4903 Halt(clear_thread_plans, use_run_lock);
4904 }
4905
4906 diagnostic_manager.Printf(
4907 eDiagnosticSeverityError,
4908 "didn't get running event after initial resume, got %s instead.",
4909 StateAsCString(stop_state));
4910 return_value = eExpressionSetupError;
4911 break;
4912 }
4913
4914 if (log)
4915 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00004916 // We need to call the function synchronously, so spin waiting for it
4917 // to return. If we get interrupted while executing, we're going to
4918 // lose our context, and won't be able to gather the result at this
4919 // point. We set the timeout AFTER the resume, since the resume takes
4920 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004921 } else {
4922 if (log)
4923 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
4924 }
4925
Kate Stoneb9c1b512016-09-06 20:57:50 +00004926 do_resume = true;
4927 handle_running_event = true;
4928
4929 // Now wait for the process to stop again:
4930 event_sp.reset();
4931
Pavel Labath2ce22162016-12-01 10:57:30 +00004932 Timeout<std::micro> timeout =
4933 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004934 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004935 if (timeout) {
4936 auto now = system_clock::now();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004937 LLDB_LOGF(log,
4938 "Process::RunThreadPlan(): about to wait - now is %s - "
4939 "endpoint is %s",
4940 llvm::to_string(now).c_str(),
4941 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004942 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004943 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00004944 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004945 }
4946
4947#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4948 // See comment above...
4949 if (miss_first_event) {
Pavel Labath3d4f7652019-08-05 08:23:25 +00004950 std::this_thread::sleep_for(std::chrono::milliseconds(1));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004951 miss_first_event = false;
4952 got_event = false;
4953 } else
4954#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00004955 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004956
4957 if (got_event) {
4958 if (event_sp) {
4959 bool keep_going = false;
4960 if (event_sp->GetType() == eBroadcastBitInterrupt) {
4961 const bool clear_thread_plans = false;
4962 const bool use_run_lock = false;
4963 Halt(clear_thread_plans, use_run_lock);
4964 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00004965 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
4966 "execution halted by user interrupt.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004967 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
4968 "eBroadcastBitInterrupted, exiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004969 break;
4970 } else {
4971 stop_state =
4972 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004973 LLDB_LOGF(log,
4974 "Process::RunThreadPlan(): in while loop, got event: %s.",
4975 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004976
4977 switch (stop_state) {
4978 case lldb::eStateStopped: {
4979 // We stopped, figure out what we are going to do now.
4980 ThreadSP thread_sp =
4981 GetThreadList().FindThreadByIndexID(thread_idx_id);
4982 if (!thread_sp) {
4983 // Ooh, our thread has vanished. Unlikely that this was
4984 // successful execution...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004985 LLDB_LOGF(log,
4986 "Process::RunThreadPlan(): execution completed "
4987 "but our thread (index-id=%u) has vanished.",
4988 thread_idx_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004989 return_value = eExpressionInterrupted;
Pavel Labath45dde232017-05-25 10:50:06 +00004990 } else if (Process::ProcessEventData::GetRestartedFromEvent(
4991 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004992 // If we were restarted, we just need to go back up to fetch
4993 // another event.
Pavel Labath45dde232017-05-25 10:50:06 +00004994 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004995 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
4996 "restart, so we'll continue waiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004997 }
Pavel Labath45dde232017-05-25 10:50:06 +00004998 keep_going = true;
4999 do_resume = false;
5000 handle_running_event = true;
5001 } else {
5002 const bool handle_interrupts = true;
5003 return_value = *HandleStoppedEvent(
5004 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5005 event_to_broadcast_sp, options, handle_interrupts);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005006 }
5007 } break;
5008
5009 case lldb::eStateRunning:
5010 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005011 // running events without an intervening stop, and in that case
5012 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005013 do_resume = false;
5014 keep_going = true;
5015 handle_running_event = false;
5016 break;
5017
5018 default:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005019 LLDB_LOGF(log,
5020 "Process::RunThreadPlan(): execution stopped with "
5021 "unexpected state: %s.",
5022 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005023
5024 if (stop_state == eStateExited)
5025 event_to_broadcast_sp = event_sp;
5026
Zachary Turnere2411fa2016-11-12 19:12:56 +00005027 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005028 eDiagnosticSeverityError,
5029 "execution stopped with unexpected state.");
5030 return_value = eExpressionInterrupted;
5031 break;
5032 }
5033 }
5034
5035 if (keep_going)
5036 continue;
5037 else
5038 break;
5039 } else {
5040 if (log)
5041 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5042 "the event pointer was null. How odd...");
5043 return_value = eExpressionInterrupted;
5044 break;
5045 }
5046 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005047 // If we didn't get an event that means we've timed out... We will
5048 // interrupt the process here. Depending on what we were asked to do
5049 // we will either exit, or try with all threads running for the same
5050 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005051
5052 if (log) {
5053 if (options.GetTryAllThreads()) {
5054 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005055 LLDB_LOG(log,
5056 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005057 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005058 LLDB_LOG(log, "Restarting function with all threads enabled and "
5059 "timeout: {0} timed out, abandoning execution.",
5060 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005061 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005062 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5063 "abandoning execution.",
5064 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005065 }
5066
5067 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005068 // around to calling Halt the target could have stopped. That's fine,
5069 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005070 // BUT it is also possible that we stopped & restarted (e.g. hit a
5071 // signal with "stop" set to false.) In
5072 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005073 // back to waiting for the Halt's stopped event. That's what this
5074 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005075
5076 bool back_to_top = true;
5077 uint32_t try_halt_again = 0;
5078 bool do_halt = true;
5079 const uint32_t num_retries = 5;
5080 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005081 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005082 if (do_halt) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005083 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005084 const bool clear_thread_plans = false;
5085 const bool use_run_lock = false;
5086 Halt(clear_thread_plans, use_run_lock);
5087 }
5088 if (halt_error.Success()) {
5089 if (log)
5090 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5091
Pavel Labathd35031e12016-11-30 10:41:42 +00005092 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00005093 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005094
5095 if (got_event) {
5096 stop_state =
5097 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5098 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005099 LLDB_LOGF(log,
5100 "Process::RunThreadPlan(): Stopped with event: %s",
5101 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005102 if (stop_state == lldb::eStateStopped &&
5103 Process::ProcessEventData::GetInterruptedFromEvent(
5104 event_sp.get()))
5105 log->PutCString(" Event was the Halt interruption event.");
5106 }
5107
5108 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005109 if (Process::ProcessEventData::GetRestartedFromEvent(
5110 event_sp.get())) {
5111 if (log)
5112 log->PutCString("Process::RunThreadPlan(): Went to halt "
5113 "but got a restarted event, there must be "
5114 "an un-restarted stopped event so try "
5115 "again... "
5116 "Exiting wait loop.");
5117 try_halt_again++;
5118 do_halt = false;
5119 continue;
5120 }
5121
Pavel Labath45dde232017-05-25 10:50:06 +00005122 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005123 // delivered it, the process could have already finished its
5124 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005125 const bool handle_interrupts = false;
5126 if (auto result = HandleStoppedEvent(
5127 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5128 event_to_broadcast_sp, options, handle_interrupts)) {
5129 return_value = *result;
5130 back_to_top = false;
5131 break;
5132 }
5133
Kate Stoneb9c1b512016-09-06 20:57:50 +00005134 if (!options.GetTryAllThreads()) {
5135 if (log)
5136 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5137 "was false, we stopped so now we're "
5138 "quitting.");
5139 return_value = eExpressionInterrupted;
5140 back_to_top = false;
5141 break;
5142 }
5143
5144 if (before_first_timeout) {
5145 // Set all the other threads to run, and return to the top of
5146 // the loop, which will continue;
5147 before_first_timeout = false;
5148 thread_plan_sp->SetStopOthers(false);
5149 if (log)
5150 log->PutCString(
5151 "Process::RunThreadPlan(): about to resume.");
5152
5153 back_to_top = true;
5154 break;
5155 } else {
5156 // Running all threads failed, so return Interrupted.
5157 if (log)
5158 log->PutCString("Process::RunThreadPlan(): running all "
5159 "threads timed out.");
5160 return_value = eExpressionInterrupted;
5161 back_to_top = false;
5162 break;
5163 }
5164 }
5165 } else {
5166 if (log)
5167 log->PutCString("Process::RunThreadPlan(): halt said it "
5168 "succeeded, but I got no event. "
5169 "I'm getting out of here passing Interrupted.");
5170 return_value = eExpressionInterrupted;
5171 back_to_top = false;
5172 break;
5173 }
5174 } else {
5175 try_halt_again++;
5176 continue;
5177 }
5178 }
5179
5180 if (!back_to_top || try_halt_again > num_retries)
5181 break;
5182 else
5183 continue;
5184 }
5185 } // END WAIT LOOP
5186
Adrian Prantl05097242018-04-30 16:49:04 +00005187 // If we had to start up a temporary private state thread to run this
5188 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005189 if (backup_private_state_thread.IsJoinable()) {
5190 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005191 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005192 m_private_state_thread = backup_private_state_thread;
5193 if (stopper_base_plan_sp) {
5194 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5195 }
5196 if (old_state != eStateInvalid)
5197 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005198 }
5199
Kate Stoneb9c1b512016-09-06 20:57:50 +00005200 if (return_value != eExpressionCompleted && log) {
5201 // Print a backtrace into the log so we can figure out where we are:
5202 StreamString s;
5203 s.PutCString("Thread state after unsuccessful completion: \n");
5204 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005205 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005206 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005207 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005208 // There are three cases where this could happen: 1) The execution
5209 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5210 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005211 bool should_unwind = (return_value == eExpressionInterrupted &&
5212 options.DoesUnwindOnError()) ||
5213 (return_value == eExpressionHitBreakpoint &&
5214 options.DoesIgnoreBreakpoints());
5215
5216 if (return_value == eExpressionCompleted || should_unwind) {
5217 thread_plan_sp->RestoreThreadState();
5218 }
5219
5220 // Now do some processing on the results of the run:
5221 if (return_value == eExpressionInterrupted ||
5222 return_value == eExpressionHitBreakpoint) {
5223 if (log) {
5224 StreamString s;
5225 if (event_sp)
5226 event_sp->Dump(&s);
5227 else {
5228 log->PutCString("Process::RunThreadPlan(): Stop event that "
5229 "interrupted us is NULL.");
5230 }
5231
5232 StreamString ts;
5233
5234 const char *event_explanation = nullptr;
5235
5236 do {
5237 if (!event_sp) {
5238 event_explanation = "<no event>";
5239 break;
5240 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5241 event_explanation = "<user interrupt>";
5242 break;
5243 } else {
5244 const Process::ProcessEventData *event_data =
5245 Process::ProcessEventData::GetEventDataFromEvent(
5246 event_sp.get());
5247
5248 if (!event_data) {
5249 event_explanation = "<no event data>";
5250 break;
5251 }
5252
5253 Process *process = event_data->GetProcessSP().get();
5254
5255 if (!process) {
5256 event_explanation = "<no process>";
5257 break;
5258 }
5259
5260 ThreadList &thread_list = process->GetThreadList();
5261
5262 uint32_t num_threads = thread_list.GetSize();
5263 uint32_t thread_index;
5264
5265 ts.Printf("<%u threads> ", num_threads);
5266
5267 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5268 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5269
5270 if (!thread) {
5271 ts.Printf("<?> ");
5272 continue;
5273 }
5274
5275 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5276 RegisterContext *register_context =
5277 thread->GetRegisterContext().get();
5278
5279 if (register_context)
5280 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5281 else
5282 ts.Printf("[ip unknown] ");
5283
5284 // Show the private stop info here, the public stop info will be
5285 // from the last natural stop.
5286 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5287 if (stop_info_sp) {
5288 const char *stop_desc = stop_info_sp->GetDescription();
5289 if (stop_desc)
5290 ts.PutCString(stop_desc);
5291 }
5292 ts.Printf(">");
5293 }
5294
5295 event_explanation = ts.GetData();
5296 }
Jonas Devlieghere09ad8c82019-05-24 00:44:33 +00005297 } while (false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005298
5299 if (event_explanation)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005300 LLDB_LOGF(log,
5301 "Process::RunThreadPlan(): execution interrupted: %s %s",
5302 s.GetData(), event_explanation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005303 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005304 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
5305 s.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005306 }
5307
5308 if (should_unwind) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005309 LLDB_LOGF(log,
5310 "Process::RunThreadPlan: ExecutionInterrupted - "
5311 "discarding thread plans up to %p.",
5312 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005313 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5314 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005315 LLDB_LOGF(log,
5316 "Process::RunThreadPlan: ExecutionInterrupted - for "
5317 "plan: %p not discarding.",
5318 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005319 }
5320 } else if (return_value == eExpressionSetupError) {
5321 if (log)
5322 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5323
5324 if (options.DoesUnwindOnError()) {
5325 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5326 }
5327 } else {
5328 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5329 if (log)
5330 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5331 return_value = eExpressionCompleted;
5332 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5333 if (log)
5334 log->PutCString(
5335 "Process::RunThreadPlan(): thread plan was discarded");
5336 return_value = eExpressionDiscarded;
5337 } else {
5338 if (log)
5339 log->PutCString(
5340 "Process::RunThreadPlan(): thread plan stopped in mid course");
5341 if (options.DoesUnwindOnError() && thread_plan_sp) {
5342 if (log)
5343 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5344 "'cause unwind_on_error is set.");
5345 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5346 }
5347 }
5348 }
5349
5350 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005351 // target Check that it's still there, and if it is put it back in the
5352 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005353 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5354 if (thread) {
5355 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5356 }
5357
5358 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005359 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005360
5361 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5362 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5363 selected_stack_id.IsValid()) {
5364 // We were able to restore the selected thread, now restore the frame:
5365 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5366 StackFrameSP old_frame_sp =
5367 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5368 selected_stack_id);
5369 if (old_frame_sp)
5370 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5371 old_frame_sp.get());
5372 }
5373 }
5374 }
5375
5376 // If the process exited during the run of the thread plan, notify everyone.
5377
5378 if (event_to_broadcast_sp) {
5379 if (log)
5380 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5381 BroadcastEvent(event_to_broadcast_sp);
5382 }
5383
5384 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005385}
5386
Kate Stoneb9c1b512016-09-06 20:57:50 +00005387const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5388 const char *result_name;
5389
5390 switch (result) {
5391 case eExpressionCompleted:
5392 result_name = "eExpressionCompleted";
5393 break;
5394 case eExpressionDiscarded:
5395 result_name = "eExpressionDiscarded";
5396 break;
5397 case eExpressionInterrupted:
5398 result_name = "eExpressionInterrupted";
5399 break;
5400 case eExpressionHitBreakpoint:
5401 result_name = "eExpressionHitBreakpoint";
5402 break;
5403 case eExpressionSetupError:
5404 result_name = "eExpressionSetupError";
5405 break;
5406 case eExpressionParseError:
5407 result_name = "eExpressionParseError";
5408 break;
5409 case eExpressionResultUnavailable:
5410 result_name = "eExpressionResultUnavailable";
5411 break;
5412 case eExpressionTimedOut:
5413 result_name = "eExpressionTimedOut";
5414 break;
5415 case eExpressionStoppedForDebug:
5416 result_name = "eExpressionStoppedForDebug";
5417 break;
5418 }
5419 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005420}
5421
Kate Stoneb9c1b512016-09-06 20:57:50 +00005422void Process::GetStatus(Stream &strm) {
5423 const StateType state = GetState();
5424 if (StateIsStoppedState(state, false)) {
5425 if (state == eStateExited) {
5426 int exit_status = GetExitStatus();
5427 const char *exit_description = GetExitDescription();
5428 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5429 GetID(), exit_status, exit_status,
5430 exit_description ? exit_description : "");
5431 } else {
5432 if (state == eStateConnected)
5433 strm.Printf("Connected to remote target.\n");
5434 else
5435 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5436 }
5437 } else {
5438 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5439 }
Pavel Labatha933d512016-04-05 13:07:16 +00005440}
5441
Kate Stoneb9c1b512016-09-06 20:57:50 +00005442size_t Process::GetThreadStatus(Stream &strm,
5443 bool only_threads_with_stop_reason,
5444 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005445 uint32_t num_frames_with_source,
5446 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005447 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005448
Kate Stoneb9c1b512016-09-06 20:57:50 +00005449 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005450 // very well might run code (e.g. if we need it to get return values or
5451 // arguments.) For that to work the process has to be able to acquire it.
5452 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005453
5454 uint32_t num_threads;
5455 std::vector<lldb::tid_t> thread_id_array;
5456 // Scope for thread list locker;
5457 {
5458 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5459 ThreadList &curr_thread_list = GetThreadList();
5460 num_threads = curr_thread_list.GetSize();
5461 uint32_t idx;
5462 thread_id_array.resize(num_threads);
5463 for (idx = 0; idx < num_threads; ++idx)
5464 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5465 }
5466
5467 for (uint32_t i = 0; i < num_threads; i++) {
5468 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5469 if (thread_sp) {
5470 if (only_threads_with_stop_reason) {
5471 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5472 if (!stop_info_sp || !stop_info_sp->IsValid())
5473 continue;
5474 }
5475 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005476 num_frames_with_source,
5477 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005478 ++num_thread_infos_dumped;
5479 } else {
5480 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005481 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
5482 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005483 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005484 }
5485 return num_thread_infos_dumped;
5486}
5487
5488void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5489 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5490}
5491
5492bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5493 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5494 region.GetByteSize());
5495}
5496
5497void Process::AddPreResumeAction(PreResumeActionCallback callback,
5498 void *baton) {
5499 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5500}
5501
5502bool Process::RunPreResumeActions() {
5503 bool result = true;
5504 while (!m_pre_resume_actions.empty()) {
5505 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5506 m_pre_resume_actions.pop_back();
5507 bool this_result = action.callback(action.baton);
5508 if (result)
5509 result = this_result;
5510 }
5511 return result;
5512}
5513
5514void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5515
Jim Inghamffd91752016-10-20 22:50:00 +00005516void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5517{
5518 PreResumeCallbackAndBaton element(callback, baton);
5519 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5520 if (found_iter != m_pre_resume_actions.end())
5521 {
5522 m_pre_resume_actions.erase(found_iter);
5523 }
5524}
5525
Kate Stoneb9c1b512016-09-06 20:57:50 +00005526ProcessRunLock &Process::GetRunLock() {
5527 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5528 return m_private_run_lock;
5529 else
5530 return m_public_run_lock;
5531}
5532
Jim Ingham58c3235e2019-10-01 00:47:25 +00005533bool Process::CurrentThreadIsPrivateStateThread()
5534{
5535 return m_private_state_thread.EqualsThread(Host::GetCurrentThread());
5536}
5537
5538
Kate Stoneb9c1b512016-09-06 20:57:50 +00005539void Process::Flush() {
5540 m_thread_list.Flush();
5541 m_extended_thread_list.Flush();
5542 m_extended_thread_stop_id = 0;
5543 m_queue_list.Clear();
5544 m_queue_list_stop_id = 0;
5545}
5546
5547void Process::DidExec() {
5548 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005549 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005550
5551 Target &target = GetTarget();
5552 target.CleanupProcess();
5553 target.ClearModules(false);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005554 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005555 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005556 m_system_runtime_up.reset();
5557 m_os_up.reset();
5558 m_dyld_up.reset();
5559 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005560 m_image_tokens.clear();
5561 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +00005562 {
5563 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5564 m_language_runtimes.clear();
5565 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005566 m_instrumentation_runtimes.clear();
5567 m_thread_list.DiscardThreadPlans();
5568 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005569 DoDidExec();
5570 CompleteAttach();
5571 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005572 // CompleteAttach() in case the dynamic loader loaded things in new
5573 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005574 Flush();
5575
Adrian Prantl05097242018-04-30 16:49:04 +00005576 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5577 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005578 target.DidExec();
5579}
5580
Zachary Turner97206d52017-05-12 04:51:55 +00005581addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005582 if (address == nullptr) {
5583 error.SetErrorString("Invalid address argument");
5584 return LLDB_INVALID_ADDRESS;
5585 }
5586
5587 addr_t function_addr = LLDB_INVALID_ADDRESS;
5588
5589 addr_t addr = address->GetLoadAddress(&GetTarget());
5590 std::map<addr_t, addr_t>::const_iterator iter =
5591 m_resolved_indirect_addresses.find(addr);
5592 if (iter != m_resolved_indirect_addresses.end()) {
5593 function_addr = (*iter).second;
5594 } else {
Alex Langford5b2b38e2019-09-13 00:02:05 +00005595 if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005596 Symbol *symbol = address->CalculateSymbolContextSymbol();
5597 error.SetErrorStringWithFormat(
5598 "Unable to call resolver for indirect function %s",
5599 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5600 function_addr = LLDB_INVALID_ADDRESS;
5601 } else {
5602 m_resolved_indirect_addresses.insert(
5603 std::pair<addr_t, addr_t>(addr, function_addr));
5604 }
5605 }
5606 return function_addr;
5607}
5608
5609void Process::ModulesDidLoad(ModuleList &module_list) {
5610 SystemRuntime *sys_runtime = GetSystemRuntime();
5611 if (sys_runtime) {
5612 sys_runtime->ModulesDidLoad(module_list);
5613 }
5614
5615 GetJITLoaders().ModulesDidLoad(module_list);
5616
5617 // Give runtimes a chance to be created.
5618 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5619 m_instrumentation_runtimes);
5620
5621 // Tell runtimes about new modules.
5622 for (auto pos = m_instrumentation_runtimes.begin();
5623 pos != m_instrumentation_runtimes.end(); ++pos) {
5624 InstrumentationRuntimeSP runtime = pos->second;
5625 runtime->ModulesDidLoad(module_list);
5626 }
5627
Adrian Prantl05097242018-04-30 16:49:04 +00005628 // Let any language runtimes we have already created know about the modules
5629 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005630
Adrian Prantl05097242018-04-30 16:49:04 +00005631 // Iterate over a copy of this language runtime list in case the language
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005632 // runtime ModulesDidLoad somehow causes the language runtime to be
Adrian Prantl05097242018-04-30 16:49:04 +00005633 // unloaded.
Alex Langford74eb76f2019-05-22 23:01:18 +00005634 {
5635 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5636 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5637 for (const auto &pair : language_runtimes) {
5638 // We must check language_runtime_sp to make sure it is not nullptr as we
5639 // might cache the fact that we didn't have a language runtime for a
5640 // language.
5641 LanguageRuntimeSP language_runtime_sp = pair.second;
5642 if (language_runtime_sp)
5643 language_runtime_sp->ModulesDidLoad(module_list);
5644 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005645 }
5646
5647 // If we don't have an operating system plug-in, try to load one since
5648 // loading shared libraries might cause a new one to try and load
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005649 if (!m_os_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005650 LoadOperatingSystemPlugin(false);
5651
5652 // Give structured-data plugins a chance to see the modified modules.
5653 for (auto pair : m_structured_data_plugin_map) {
5654 if (pair.second)
5655 pair.second->ModulesDidLoad(*this, module_list);
5656 }
5657}
5658
5659void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5660 const char *fmt, ...) {
5661 bool print_warning = true;
5662
5663 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5664 if (!stream_sp)
5665 return;
5666 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5667 return;
5668 }
5669
5670 if (repeat_key != nullptr) {
5671 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5672 if (it == m_warnings_issued.end()) {
5673 m_warnings_issued[warning_type] = WarningsPointerSet();
5674 m_warnings_issued[warning_type].insert(repeat_key);
5675 } else {
5676 if (it->second.find(repeat_key) != it->second.end()) {
5677 print_warning = false;
5678 } else {
5679 it->second.insert(repeat_key);
5680 }
5681 }
5682 }
5683
5684 if (print_warning) {
5685 va_list args;
5686 va_start(args, fmt);
5687 stream_sp->PrintfVarArg(fmt, args);
5688 va_end(args);
5689 }
5690}
5691
5692void Process::PrintWarningOptimization(const SymbolContext &sc) {
5693 if (GetWarningsOptimization() && sc.module_sp &&
5694 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5695 sc.function->GetIsOptimized()) {
5696 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5697 "%s was compiled with optimization - stepping may behave "
5698 "oddly; variables may not be available.\n",
5699 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5700 }
5701}
5702
5703bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5704 info.Clear();
5705
5706 PlatformSP platform_sp = GetTarget().GetPlatform();
5707 if (!platform_sp)
5708 return false;
5709
5710 return platform_sp->GetProcessInfo(GetID(), info);
5711}
5712
5713ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5714 ThreadCollectionSP threads;
5715
5716 const MemoryHistorySP &memory_history =
5717 MemoryHistory::FindPlugin(shared_from_this());
5718
5719 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005720 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005721 }
5722
Jonas Devlieghere796ac802019-02-11 23:13:08 +00005723 threads = std::make_shared<ThreadCollection>(
5724 memory_history->GetHistoryThreads(addr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005725
5726 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005727}
Kuba Brecka63927542014-10-11 01:59:32 +00005728
5729InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005730Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5731 InstrumentationRuntimeCollection::iterator pos;
5732 pos = m_instrumentation_runtimes.find(type);
5733 if (pos == m_instrumentation_runtimes.end()) {
5734 return InstrumentationRuntimeSP();
5735 } else
5736 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005737}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005738
Kate Stoneb9c1b512016-09-06 20:57:50 +00005739bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5740 const ArchSpec &arch, ModuleSpec &module_spec) {
5741 module_spec.Clear();
5742 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005743}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005744
Kate Stoneb9c1b512016-09-06 20:57:50 +00005745size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5746 m_image_tokens.push_back(image_ptr);
5747 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005748}
5749
Kate Stoneb9c1b512016-09-06 20:57:50 +00005750lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5751 if (token < m_image_tokens.size())
5752 return m_image_tokens[token];
5753 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005754}
5755
Kate Stoneb9c1b512016-09-06 20:57:50 +00005756void Process::ResetImageToken(size_t token) {
5757 if (token < m_image_tokens.size())
5758 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005759}
Jason Molendafd4cea52016-01-08 21:40:11 +00005760
5761Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005762Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5763 AddressRange range_bounds) {
5764 Target &target = GetTarget();
5765 DisassemblerSP disassembler_sp;
5766 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005767
Kate Stoneb9c1b512016-09-06 20:57:50 +00005768 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005769
Kate Stoneb9c1b512016-09-06 20:57:50 +00005770 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005771 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005772 if (!default_stop_addr.IsValid())
5773 return retval;
5774
5775 ExecutionContext exe_ctx(this);
5776 const char *plugin_name = nullptr;
5777 const char *flavor = nullptr;
5778 const bool prefer_file_cache = true;
5779 disassembler_sp = Disassembler::DisassembleRange(
5780 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
5781 prefer_file_cache);
5782 if (disassembler_sp)
5783 insn_list = &disassembler_sp->GetInstructionList();
5784
5785 if (insn_list == nullptr) {
5786 return retval;
5787 }
5788
5789 size_t insn_offset =
5790 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5791 if (insn_offset == UINT32_MAX) {
5792 return retval;
5793 }
5794
5795 uint32_t branch_index =
Greg Claytondf225762019-05-09 20:39:34 +00005796 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target,
Jim Ingham434905b2019-12-16 17:38:13 -08005797 false /* ignore_calls*/,
5798 nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005799 if (branch_index == UINT32_MAX) {
5800 return retval;
5801 }
5802
5803 if (branch_index > insn_offset) {
5804 Address next_branch_insn_address =
5805 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5806 if (next_branch_insn_address.IsValid() &&
5807 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5808 retval = next_branch_insn_address;
5809 }
5810 }
5811
5812 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00005813}
Howard Hellyerad007562016-07-07 08:21:28 +00005814
Zachary Turner97206d52017-05-12 04:51:55 +00005815Status
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005816Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00005817
Zachary Turner97206d52017-05-12 04:51:55 +00005818 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00005819
Kate Stoneb9c1b512016-09-06 20:57:50 +00005820 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00005821
Kate Stoneb9c1b512016-09-06 20:57:50 +00005822 region_list.clear();
5823 do {
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005824 lldb_private::MemoryRegionInfo region_info;
5825 error = GetMemoryRegionInfo(range_end, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005826 // GetMemoryRegionInfo should only return an error if it is unimplemented.
5827 if (error.Fail()) {
5828 region_list.clear();
5829 break;
Todd Fiala75930012016-08-19 04:21:48 +00005830 }
5831
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005832 range_end = region_info.GetRange().GetRangeEnd();
5833 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5834 region_list.push_back(std::move(region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005835 }
5836 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00005837
Kate Stoneb9c1b512016-09-06 20:57:50 +00005838 return error;
5839}
5840
Zachary Turner97206d52017-05-12 04:51:55 +00005841Status
Adrian Prantl0e4c4822019-03-06 21:22:25 +00005842Process::ConfigureStructuredData(ConstString type_name,
Zachary Turner97206d52017-05-12 04:51:55 +00005843 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005844 // If you get this, the Process-derived class needs to implement a method to
5845 // enable an already-reported asynchronous structured data feature. See
5846 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00005847 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005848}
5849
5850void Process::MapSupportedStructuredDataPlugins(
5851 const StructuredData::Array &supported_type_names) {
5852 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5853
5854 // Bail out early if there are no type names to map.
5855 if (supported_type_names.GetSize() == 0) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005856 LLDB_LOGF(log, "Process::%s(): no structured data types supported",
5857 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005858 return;
5859 }
Todd Fiala75930012016-08-19 04:21:48 +00005860
Kate Stoneb9c1b512016-09-06 20:57:50 +00005861 // Convert StructuredData type names to ConstString instances.
5862 std::set<ConstString> const_type_names;
5863
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005864 LLDB_LOGF(log,
5865 "Process::%s(): the process supports the following async "
5866 "structured data types:",
5867 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005868
5869 supported_type_names.ForEach(
5870 [&const_type_names, &log](StructuredData::Object *object) {
5871 if (!object) {
5872 // Invalid - shouldn't be null objects in the array.
5873 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005874 }
5875
5876 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005877 if (!type_name) {
5878 // Invalid format - all type names should be strings.
5879 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005880 }
5881
5882 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00005883 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00005884 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005885 });
Todd Fiala75930012016-08-19 04:21:48 +00005886
Adrian Prantl05097242018-04-30 16:49:04 +00005887 // For each StructuredDataPlugin, if the plugin handles any of the types in
5888 // the supported_type_names, map that type name to that plugin. Stop when
5889 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005890 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00005891 // supports?
5892 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
5893 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00005894 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
5895 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00005896 if (!create_instance)
5897 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005898
Kate Stoneb9c1b512016-09-06 20:57:50 +00005899 // Create the plugin.
5900 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
5901 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005902 // This plugin doesn't think it can work with the process. Move on to the
5903 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005904 continue;
Todd Fiala75930012016-08-19 04:21:48 +00005905 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005906
Adrian Prantl05097242018-04-30 16:49:04 +00005907 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005908 std::vector<ConstString> names_to_remove;
5909 for (auto &type_name : const_type_names) {
5910 if (plugin_sp->SupportsStructuredDataType(type_name)) {
5911 m_structured_data_plugin_map.insert(
5912 std::make_pair(type_name, plugin_sp));
5913 names_to_remove.push_back(type_name);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005914 LLDB_LOGF(log,
5915 "Process::%s(): using plugin %s for type name "
5916 "%s",
5917 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
5918 type_name.GetCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005919 }
5920 }
5921
5922 // Remove the type names that were consumed by this plugin.
5923 for (auto &type_name : names_to_remove)
5924 const_type_names.erase(type_name);
5925 }
Todd Fiala75930012016-08-19 04:21:48 +00005926}
5927
Kate Stoneb9c1b512016-09-06 20:57:50 +00005928bool Process::RouteAsyncStructuredData(
5929 const StructuredData::ObjectSP object_sp) {
5930 // Nothing to do if there's no data.
5931 if (!object_sp)
5932 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005933
Adrian Prantl05097242018-04-30 16:49:04 +00005934 // The contract is this must be a dictionary, so we can look up the routing
5935 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005936 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
5937 if (!dictionary)
5938 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005939
Kate Stoneb9c1b512016-09-06 20:57:50 +00005940 // Grab the async structured type name (i.e. the feature/plugin name).
5941 ConstString type_name;
5942 if (!dictionary->GetValueForKeyAsString("type", type_name))
5943 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005944
Kate Stoneb9c1b512016-09-06 20:57:50 +00005945 // Check if there's a plugin registered for this type name.
5946 auto find_it = m_structured_data_plugin_map.find(type_name);
5947 if (find_it == m_structured_data_plugin_map.end()) {
5948 // We don't have a mapping for this structured data type.
5949 return false;
5950 }
Todd Fiala75930012016-08-19 04:21:48 +00005951
Kate Stoneb9c1b512016-09-06 20:57:50 +00005952 // Route the structured data to the plugin.
5953 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
5954 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00005955}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005956
Zachary Turner97206d52017-05-12 04:51:55 +00005957Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005958 // Default implementation does nothign.
5959 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00005960 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005961}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005962
Frederic Rissd10d3792018-05-11 18:21:11 +00005963UtilityFunction *Process::GetLoadImageUtilityFunction(
5964 Platform *platform,
5965 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005966 if (platform != GetTarget().GetPlatform().get())
5967 return nullptr;
Michal Gorny3276fff2019-09-03 12:31:24 +00005968 llvm::call_once(m_dlopen_utility_func_flag_once,
5969 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005970 return m_dlopen_utility_func_up.get();
5971}
Alex Langford5b2b38e2019-09-13 00:02:05 +00005972
5973bool Process::CallVoidArgVoidPtrReturn(const Address *address,
5974 addr_t &returned_func,
5975 bool trap_exceptions) {
5976 Thread *thread = GetThreadList().GetExpressionExecutionThread().get();
5977 if (thread == nullptr || address == nullptr)
5978 return false;
5979
5980 EvaluateExpressionOptions options;
5981 options.SetStopOthers(true);
5982 options.SetUnwindOnError(true);
5983 options.SetIgnoreBreakpoints(true);
5984 options.SetTryAllThreads(true);
5985 options.SetDebug(false);
5986 options.SetTimeout(GetUtilityExpressionTimeout());
5987 options.SetTrapExceptions(trap_exceptions);
5988
5989 auto type_system_or_err =
5990 GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC);
5991 if (!type_system_or_err) {
5992 llvm::consumeError(type_system_or_err.takeError());
5993 return false;
5994 }
5995 CompilerType void_ptr_type =
5996 type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
5997 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction(
5998 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
5999 if (call_plan_sp) {
6000 DiagnosticManager diagnostics;
6001
6002 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6003 if (frame) {
6004 ExecutionContext exe_ctx;
6005 frame->CalculateExecutionContext(exe_ctx);
6006 ExpressionResults result =
6007 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
6008 if (result == eExpressionCompleted) {
6009 returned_func =
6010 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6011 LLDB_INVALID_ADDRESS);
6012
6013 if (GetAddressByteSize() == 4) {
6014 if (returned_func == UINT32_MAX)
6015 return false;
6016 } else if (GetAddressByteSize() == 8) {
6017 if (returned_func == UINT64_MAX)
6018 return false;
6019 }
6020 return true;
6021 }
6022 }
6023 }
6024
6025 return false;
6026}