blob: 4d6d96fb47c47bf6399d9b5503031f25b134d8ee [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
Sean Callanan579e70c2016-03-19 00:03:59 +000016#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017#include "lldb/Breakpoint/BreakpointLocation.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000018#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include "lldb/Core/Debugger.h"
Greg Clayton1f746072012-08-29 21:13:06 +000020#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000021#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000023#include "lldb/Core/StreamFile.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000024#include "lldb/Expression/DiagnosticManager.h"
Alex Langfordbab7e3d2019-07-12 00:58:02 +000025#include "lldb/Expression/DynamicCheckerFunctions.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000026#include "lldb/Expression/UserExpression.h"
Jim Ingham1ecb34f2018-04-17 20:44:47 +000027#include "lldb/Expression/UtilityFunction.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000028#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000029#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000031#include "lldb/Host/HostInfo.h"
Zachary Turner3eb2b442017-03-22 23:33:16 +000032#include "lldb/Host/OptionParser.h"
Greg Clayton100eb932014-07-02 21:10:39 +000033#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000034#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000035#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000036#include "lldb/Interpreter/CommandInterpreter.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000037#include "lldb/Interpreter/OptionArgParser.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000038#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000039#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000040#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000042#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000043#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000044#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000045#include "lldb/Target/JITLoaderList.h"
Alex Langford03e1a822019-05-29 18:08:22 +000046#include "lldb/Target/Language.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000047#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000048#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000049#include "lldb/Target/MemoryRegionInfo.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000050#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000051#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000052#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000054#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000055#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000056#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057#include "lldb/Target/Target.h"
58#include "lldb/Target/TargetList.h"
59#include "lldb/Target/Thread.h"
60#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000061#include "lldb/Target/ThreadPlanBase.h"
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
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000115static constexpr PropertyDefinition g_properties[] = {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000116#define LLDB_PROPERTIES_process
117#include "lldb/Core/Properties.inc"
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000118};
Greg Clayton67cc0632012-08-22 17:17:09 +0000119
120enum {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000121#define LLDB_PROPERTIES_process
122#include "lldb/Core/PropertiesEnum.inc"
Greg Clayton67cc0632012-08-22 17:17:09 +0000123};
124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125ProcessProperties::ProcessProperties(lldb_private::Process *process)
126 : Properties(),
127 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000128{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 if (process == nullptr) {
130 // Global process properties, set them up one time
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000131 m_collection_sp =
132 std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 m_collection_sp->Initialize(g_properties);
134 m_collection_sp->AppendProperty(
135 ConstString("thread"), ConstString("Settings specific to threads."),
136 true, Thread::GetGlobalProperties()->GetValueProperties());
137 } else {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000138 m_collection_sp = std::make_shared<ProcessOptionValueProperties>(
139 Process::GetGlobalProperties().get());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 m_collection_sp->SetValueChangedCallback(
141 ePropertyPythonOSPluginPath,
142 ProcessProperties::OptionValueChangedCallback, this);
143 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000144}
145
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000146ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148void ProcessProperties::OptionValueChangedCallback(void *baton,
149 OptionValue *option_value) {
150 ProcessProperties *properties = (ProcessProperties *)baton;
151 if (properties->m_process)
152 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000153}
154
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155bool ProcessProperties::GetDisableMemoryCache() const {
156 const uint32_t idx = ePropertyDisableMemCache;
157 return m_collection_sp->GetPropertyAtIndexAsBoolean(
158 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000159}
160
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
162 const uint32_t idx = ePropertyMemCacheLineSize;
163 return m_collection_sp->GetPropertyAtIndexAsUInt64(
164 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000165}
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167Args ProcessProperties::GetExtraStartupCommands() const {
168 Args args;
169 const uint32_t idx = ePropertyExtraStartCommand;
170 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
171 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000172}
173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174void ProcessProperties::SetExtraStartupCommands(const Args &args) {
175 const uint32_t idx = ePropertyExtraStartCommand;
176 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000177}
178
Kate Stoneb9c1b512016-09-06 20:57:50 +0000179FileSpec ProcessProperties::GetPythonOSPluginPath() const {
180 const uint32_t idx = ePropertyPythonOSPluginPath;
181 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000182}
183
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
185 const uint32_t idx = ePropertyPythonOSPluginPath;
186 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000187}
188
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
190 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
191 return m_collection_sp->GetPropertyAtIndexAsBoolean(
192 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
196 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
197 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000198}
199
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
201 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
202 return m_collection_sp->GetPropertyAtIndexAsBoolean(
203 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000204}
205
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
207 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
208 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000209}
210
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
212 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
213 return m_collection_sp->GetPropertyAtIndexAsBoolean(
214 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000215}
216
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
218 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
219 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
220}
221
222bool ProcessProperties::GetDetachKeepsStopped() const {
223 const uint32_t idx = ePropertyDetachKeepsStopped;
224 return m_collection_sp->GetPropertyAtIndexAsBoolean(
225 nullptr, idx, g_properties[idx].default_uint_value != 0);
226}
227
228void ProcessProperties::SetDetachKeepsStopped(bool stop) {
229 const uint32_t idx = ePropertyDetachKeepsStopped;
230 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
231}
232
233bool ProcessProperties::GetWarningsOptimization() const {
234 const uint32_t idx = ePropertyWarningOptimization;
235 return m_collection_sp->GetPropertyAtIndexAsBoolean(
236 nullptr, idx, g_properties[idx].default_uint_value != 0);
237}
238
Jim Inghamba205c12017-12-05 02:50:45 +0000239bool ProcessProperties::GetStopOnExec() const {
240 const uint32_t idx = ePropertyStopOnExec;
241 return m_collection_sp->GetPropertyAtIndexAsBoolean(
242 nullptr, idx, g_properties[idx].default_uint_value != 0);
243}
244
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000245std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
246 const uint32_t idx = ePropertyUtilityExpressionTimeout;
247 uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
248 nullptr, idx, g_properties[idx].default_uint_value);
249 return std::chrono::seconds(value);
250}
251
Zachary Turner97206d52017-05-12 04:51:55 +0000252Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000253 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000255 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 const int short_option = m_getopt_table[option_idx].val;
257
258 switch (short_option) {
259 case 's': // Stop at program entry point
260 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
261 break;
262
263 case 'i': // STDIN for read only
264 {
265 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000266 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 launch_info.AppendFileAction(action);
268 break;
269 }
270
271 case 'o': // Open STDOUT for write only
272 {
273 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000274 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275 launch_info.AppendFileAction(action);
276 break;
277 }
278
279 case 'e': // STDERR for write only
280 {
281 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000282 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283 launch_info.AppendFileAction(action);
284 break;
285 }
286
287 case 'p': // Process plug-in name
288 launch_info.SetProcessPluginName(option_arg);
289 break;
290
291 case 'n': // Disable STDIO
292 {
293 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000294 const FileSpec dev_null(FileSystem::DEV_NULL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000295 if (action.Open(STDIN_FILENO, dev_null, true, false))
296 launch_info.AppendFileAction(action);
297 if (action.Open(STDOUT_FILENO, dev_null, false, true))
298 launch_info.AppendFileAction(action);
299 if (action.Open(STDERR_FILENO, dev_null, false, true))
300 launch_info.AppendFileAction(action);
301 break;
302 }
303
304 case 'w':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000305 launch_info.SetWorkingDirectory(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306 break;
307
308 case 't': // Open process in new terminal window
309 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
310 break;
311
312 case 'a': {
313 TargetSP target_sp =
314 execution_context ? execution_context->GetTargetSP() : TargetSP();
315 PlatformSP platform_sp =
316 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000317 launch_info.GetArchitecture() =
318 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 } break;
320
321 case 'A': // Disable ASLR.
322 {
323 bool success;
324 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000325 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 if (success)
327 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000328 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 error.SetErrorStringWithFormat(
330 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000331 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 break;
333 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000334
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 case 'X': // shell expand args.
336 {
337 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000338 const bool expand_args =
339 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 if (success)
341 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000342 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 error.SetErrorStringWithFormat(
344 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000345 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346 break;
347 }
348
349 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000350 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000351 launch_info.SetShell(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 else
353 launch_info.SetShell(HostInfo::GetDefaultShell());
354 break;
355
356 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000357 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 break;
359
360 default:
361 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
362 short_option);
363 break;
364 }
365 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000366}
367
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000368static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000370 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 "Stop at the entry point of the program when launching a process."},
372 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000373 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 "Set whether to disable address space layout randomization when launching "
375 "a process."},
376 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000377 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378 "Name of the process plugin you want to use."},
379 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000380 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 eArgTypeDirectoryName,
382 "Set the current working directory to <path> when running the inferior."},
383 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000384 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 "Set the architecture for the process to launch when ambiguous."},
386 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000387 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 "Specify an environment variable name/value string (--environment "
389 "NAME=VALUE). Can be specified multiple times for subsequent environment "
390 "entries."},
391 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000392 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000396 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 "Redirect stdin for the process to <filename>."},
398 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000399 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 "Redirect stdout for the process to <filename>."},
401 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000402 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000406 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000410 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 "Do not set up for terminal I/O to go to running process."},
412 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000413 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000415};
416
417llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000418 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000419}
Greg Clayton32e0a752011-03-30 18:16:51 +0000420
Zachary Turner31659452016-11-17 21:15:14 +0000421ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
422 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 ListenerSP listener_sp,
424 const FileSpec *crash_file_path) {
425 static uint32_t g_process_unique_id = 0;
426
427 ProcessSP process_sp;
428 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000429 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 ConstString const_plugin_name(plugin_name);
431 create_callback =
432 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
433 if (create_callback) {
434 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
435 if (process_sp) {
436 if (process_sp->CanDebug(target_sp, true)) {
437 process_sp->m_process_unique_id = ++g_process_unique_id;
438 } else
439 process_sp.reset();
440 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000441 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 } else {
443 for (uint32_t idx = 0;
444 (create_callback =
445 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
446 ++idx) {
447 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
448 if (process_sp) {
449 if (process_sp->CanDebug(target_sp, false)) {
450 process_sp->m_process_unique_id = ++g_process_unique_id;
451 break;
452 } else
453 process_sp.reset();
454 }
455 }
456 }
457 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000458}
459
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460ConstString &Process::GetStaticBroadcasterClass() {
461 static ConstString class_name("lldb.process");
462 return class_name;
463}
464
465Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
466 : Process(target_sp, listener_sp,
467 UnixSignals::Create(HostInfo::GetArchitecture())) {
468 // This constructor just delegates to the full Process constructor,
469 // defaulting to using the Host's UnixSignals.
470}
471
472Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
473 const UnixSignalsSP &unix_signals_sp)
474 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
475 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
476 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000477 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 m_private_state(eStateUnloaded),
479 m_private_state_broadcaster(nullptr,
480 "lldb.process.internal_state_broadcaster"),
481 m_private_state_control_broadcaster(
482 nullptr, "lldb.process.internal_state_control_broadcaster"),
483 m_private_state_listener_sp(
484 Listener::MakeListener("lldb.process.internal_state_listener")),
485 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
486 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
487 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
488 m_thread_list(this), m_extended_thread_list(this),
489 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
490 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000491 m_breakpoint_site_list(), m_dynamic_checkers_up(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
493 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
494 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
495 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
496 m_memory_cache(*this), m_allocated_memory_cache(*this),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000497 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000498 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
500 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
501 m_can_interpret_function_calls(false), m_warnings_issued(),
502 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
503 CheckInWithManager();
504
505 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000506 LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507
508 if (!m_unix_signals_sp)
509 m_unix_signals_sp = std::make_shared<UnixSignals>();
510
511 SetEventName(eBroadcastBitStateChanged, "state-changed");
512 SetEventName(eBroadcastBitInterrupt, "interrupt");
513 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
514 SetEventName(eBroadcastBitSTDERR, "stderr-available");
515 SetEventName(eBroadcastBitProfileData, "profile-data-available");
516 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
517
518 m_private_state_control_broadcaster.SetEventName(
519 eBroadcastInternalStateControlStop, "control-stop");
520 m_private_state_control_broadcaster.SetEventName(
521 eBroadcastInternalStateControlPause, "control-pause");
522 m_private_state_control_broadcaster.SetEventName(
523 eBroadcastInternalStateControlResume, "control-resume");
524
525 m_listener_sp->StartListeningForEvents(
526 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
527 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
528 eBroadcastBitProfileData | eBroadcastBitStructuredData);
529
530 m_private_state_listener_sp->StartListeningForEvents(
531 &m_private_state_broadcaster,
532 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
533
534 m_private_state_listener_sp->StartListeningForEvents(
535 &m_private_state_control_broadcaster,
536 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
537 eBroadcastInternalStateControlResume);
538 // We need something valid here, even if just the default UnixSignalsSP.
539 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
540
541 // Allow the platform to override the default cache line size
542 OptionValueSP value_sp =
543 m_collection_sp
544 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
545 ->GetValue();
546 uint32_t platform_cache_line_size =
547 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
548 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
549 value_sp->SetUInt64Value(platform_cache_line_size);
550}
551
552Process::~Process() {
553 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000554 LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 StopPrivateStateThread();
556
557 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000558 // explicitly clear the thread list here to ensure that the mutex is not
559 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 m_thread_list.Clear();
561}
562
563const ProcessPropertiesSP &Process::GetGlobalProperties() {
564 // NOTE: intentional leak so we don't crash if global destructor chain gets
565 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000566 static ProcessPropertiesSP *g_settings_sp_ptr =
567 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 return *g_settings_sp_ptr;
569}
570
571void Process::Finalize() {
572 m_finalizing = true;
573
574 // Destroy this process if needed
575 switch (GetPrivateState()) {
576 case eStateConnected:
577 case eStateAttaching:
578 case eStateLaunching:
579 case eStateStopped:
580 case eStateRunning:
581 case eStateStepping:
582 case eStateCrashed:
583 case eStateSuspended:
584 Destroy(false);
585 break;
586
587 case eStateInvalid:
588 case eStateUnloaded:
589 case eStateDetached:
590 case eStateExited:
591 break;
592 }
593
594 // Clear our broadcaster before we proceed with destroying
595 Broadcaster::Clear();
596
Adrian Prantl05097242018-04-30 16:49:04 +0000597 // Do any cleanup needed prior to being destructed... Subclasses that
598 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599
600 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000601 // destroyed since it is very likely that undoing the loader will require
602 // access to the real process.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000603 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000605 m_os_up.reset();
606 m_system_runtime_up.reset();
607 m_dyld_up.reset();
608 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 m_thread_list_real.Destroy();
610 m_thread_list.Destroy();
611 m_extended_thread_list.Destroy();
612 m_queue_list.Clear();
613 m_queue_list_stop_id = 0;
614 std::vector<Notifications> empty_notifications;
615 m_notifications.swap(empty_notifications);
616 m_image_tokens.clear();
617 m_memory_cache.Clear();
618 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +0000619 {
620 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
621 m_language_runtimes.clear();
622 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 m_instrumentation_runtimes.clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000624 m_next_event_action_up.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000625 // Clear the last natural stop ID since it has a strong reference to this
626 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
628 //#ifdef LLDB_CONFIGURATION_DEBUG
629 // StreamFile s(stdout, false);
630 // EventSP event_sp;
631 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
632 // {
633 // event_sp->Dump (&s);
634 // s.EOL();
635 // }
636 //#endif
637 // We have to be very careful here as the m_private_state_listener might
638 // contain events that have ProcessSP values in them which can keep this
639 // process around forever. These events need to be cleared out.
640 m_private_state_listener_sp->Clear();
641 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
642 m_public_run_lock.SetStopped();
643 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
644 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000645 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646 m_finalize_called = true;
647}
648
649void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
650 m_notifications.push_back(callbacks);
651 if (callbacks.initialize != nullptr)
652 callbacks.initialize(callbacks.baton, this);
653}
654
655bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
656 std::vector<Notifications>::iterator pos, end = m_notifications.end();
657 for (pos = m_notifications.begin(); pos != end; ++pos) {
658 if (pos->baton == callbacks.baton &&
659 pos->initialize == callbacks.initialize &&
660 pos->process_state_changed == callbacks.process_state_changed) {
661 m_notifications.erase(pos);
662 return true;
663 }
664 }
665 return false;
666}
667
668void Process::SynchronouslyNotifyStateChanged(StateType state) {
669 std::vector<Notifications>::iterator notification_pos,
670 notification_end = m_notifications.end();
671 for (notification_pos = m_notifications.begin();
672 notification_pos != notification_end; ++notification_pos) {
673 if (notification_pos->process_state_changed)
674 notification_pos->process_state_changed(notification_pos->baton, this,
675 state);
676 }
677}
678
679// FIXME: We need to do some work on events before the general Listener sees
680// them.
681// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000682// we do the little "insert real insn, step & stop" trick. But we can't do
683// that when the event is delivered by the broadcaster - since that is done on
684// the thread that is waiting for new events, so if we needed more than one
685// event for our handling, we would stall. So instead we do it when we fetch
686// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000687//
688
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689StateType Process::GetNextEvent(EventSP &event_sp) {
690 StateType state = eStateInvalid;
691
Pavel Labathd35031e12016-11-30 10:41:42 +0000692 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
693 std::chrono::seconds(0)) &&
694 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
696
697 return state;
698}
699
Pavel Labath3879fe02018-05-09 14:29:30 +0000700void Process::SyncIOHandler(uint32_t iohandler_id,
701 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 // don't sync (potentially context switch) in case where there is no process
703 // IO
704 if (!m_process_input_reader)
705 return;
706
Pavel Labath3879fe02018-05-09 14:29:30 +0000707 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708
709 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000710 if (Result) {
711 LLDB_LOG(
712 log,
713 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
714 iohandler_id, *Result);
715 } else {
716 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
717 iohandler_id);
718 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719}
720
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000721StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
722 EventSP *event_sp_ptr, bool wait_always,
723 ListenerSP hijack_listener_sp,
724 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000726 // have restarted the target. We have to actually check each event, and in
727 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000728 if (event_sp_ptr)
729 event_sp_ptr->reset();
730 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000731 // If we are exited or detached, we won't ever get back to any other valid
732 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000734 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000737 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000738
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 if (!wait_always && StateIsStoppedState(state, true) &&
740 StateIsStoppedState(GetPrivateState(), true)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000741 LLDB_LOGF(log,
742 "Process::%s returning without waiting for events; process "
743 "private and public states are already 'stopped'.",
744 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745 // We need to toggle the run lock as this won't get done in
746 // SetPublicState() if the process is hijacked.
747 if (hijack_listener_sp && use_run_lock)
748 m_public_run_lock.SetStopped();
749 return state;
750 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000751
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 while (state != eStateInvalid) {
753 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000754 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755 if (event_sp_ptr && event_sp)
756 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +0000757
Kate Stoneb9c1b512016-09-06 20:57:50 +0000758 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
759 Process::HandleProcessStateChangedEvent(event_sp, stream,
760 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +0000761
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762 switch (state) {
763 case eStateCrashed:
764 case eStateDetached:
765 case eStateExited:
766 case eStateUnloaded:
767 // We need to toggle the run lock as this won't get done in
768 // SetPublicState() if the process is hijacked.
769 if (hijack_listener_sp && use_run_lock)
770 m_public_run_lock.SetStopped();
771 return state;
772 case eStateStopped:
773 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
774 continue;
775 else {
Pavel Labath78521ef2015-03-06 10:52:47 +0000776 // We need to toggle the run lock as this won't get done in
777 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +0000778 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779 m_public_run_lock.SetStopped();
780 return state;
781 }
782 default:
783 continue;
784 }
785 }
786 return state;
787}
788
789bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
790 Stream *stream,
791 bool &pop_process_io_handler) {
792 const bool handle_pop = pop_process_io_handler;
793
794 pop_process_io_handler = false;
795 ProcessSP process_sp =
796 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
797
798 if (!process_sp)
799 return false;
800
801 StateType event_state =
802 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
803 if (event_state == eStateInvalid)
804 return false;
805
806 switch (event_state) {
807 case eStateInvalid:
808 case eStateUnloaded:
809 case eStateAttaching:
810 case eStateLaunching:
811 case eStateStepping:
812 case eStateDetached:
813 if (stream)
814 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
815 StateAsCString(event_state));
816 if (event_state == eStateDetached)
817 pop_process_io_handler = true;
818 break;
819
820 case eStateConnected:
821 case eStateRunning:
822 // Don't be chatty when we run...
823 break;
824
825 case eStateExited:
826 if (stream)
827 process_sp->GetStatus(*stream);
828 pop_process_io_handler = true;
829 break;
830
831 case eStateStopped:
832 case eStateCrashed:
833 case eStateSuspended:
834 // Make sure the program hasn't been auto-restarted:
835 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
836 if (stream) {
837 size_t num_reasons =
838 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
839 if (num_reasons > 0) {
840 // FIXME: Do we want to report this, or would that just be annoyingly
841 // chatty?
842 if (num_reasons == 1) {
843 const char *reason =
844 Process::ProcessEventData::GetRestartedReasonAtIndex(
845 event_sp.get(), 0);
846 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
847 process_sp->GetID(),
848 reason ? reason : "<UNKNOWN REASON>");
849 } else {
850 stream->Printf("Process %" PRIu64
851 " stopped and restarted, reasons:\n",
852 process_sp->GetID());
853
854 for (size_t i = 0; i < num_reasons; i++) {
855 const char *reason =
856 Process::ProcessEventData::GetRestartedReasonAtIndex(
857 event_sp.get(), i);
858 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
859 }
860 }
861 }
862 }
863 } else {
864 StopInfoSP curr_thread_stop_info_sp;
865 // Lock the thread list so it doesn't change on us, this is the scope for
866 // the locker:
867 {
868 ThreadList &thread_list = process_sp->GetThreadList();
869 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
870
871 ThreadSP curr_thread(thread_list.GetSelectedThread());
872 ThreadSP thread;
873 StopReason curr_thread_stop_reason = eStopReasonInvalid;
874 if (curr_thread) {
875 curr_thread_stop_reason = curr_thread->GetStopReason();
876 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
877 }
878 if (!curr_thread || !curr_thread->IsValid() ||
879 curr_thread_stop_reason == eStopReasonInvalid ||
880 curr_thread_stop_reason == eStopReasonNone) {
881 // Prefer a thread that has just completed its plan over another
882 // thread as current thread.
883 ThreadSP plan_thread;
884 ThreadSP other_thread;
885
886 const size_t num_threads = thread_list.GetSize();
887 size_t i;
888 for (i = 0; i < num_threads; ++i) {
889 thread = thread_list.GetThreadAtIndex(i);
890 StopReason thread_stop_reason = thread->GetStopReason();
891 switch (thread_stop_reason) {
892 case eStopReasonInvalid:
893 case eStopReasonNone:
894 break;
895
896 case eStopReasonSignal: {
897 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +0000898 // that signal. We have to have had another reason for stopping
899 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 uint64_t signo = thread->GetStopInfo()->GetValue();
901 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
902 if (!other_thread)
903 other_thread = thread;
904 }
905 break;
906 }
907 case eStopReasonTrace:
908 case eStopReasonBreakpoint:
909 case eStopReasonWatchpoint:
910 case eStopReasonException:
911 case eStopReasonExec:
912 case eStopReasonThreadExiting:
913 case eStopReasonInstrumentation:
914 if (!other_thread)
915 other_thread = thread;
916 break;
917 case eStopReasonPlanComplete:
918 if (!plan_thread)
919 plan_thread = thread;
920 break;
921 }
922 }
923 if (plan_thread)
924 thread_list.SetSelectedThreadByID(plan_thread->GetID());
925 else if (other_thread)
926 thread_list.SetSelectedThreadByID(other_thread->GetID());
927 else {
928 if (curr_thread && curr_thread->IsValid())
929 thread = curr_thread;
930 else
931 thread = thread_list.GetThreadAtIndex(0);
932
933 if (thread)
934 thread_list.SetSelectedThreadByID(thread->GetID());
935 }
936 }
937 }
938 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +0000939 // have to run code, e.g. for Data formatters, and if we hold the
940 // ThreadList mutex, then the process is going to have a hard time
941 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 if (stream) {
943 Debugger &debugger = process_sp->GetTarget().GetDebugger();
944 if (debugger.GetTargetList().GetSelectedTarget().get() ==
945 &process_sp->GetTarget()) {
946 const bool only_threads_with_stop_reason = true;
947 const uint32_t start_frame = 0;
948 const uint32_t num_frames = 1;
949 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +0000950 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 process_sp->GetStatus(*stream);
952 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
953 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000954 num_frames_with_source,
955 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956 if (curr_thread_stop_info_sp) {
957 lldb::addr_t crashing_address;
958 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
959 curr_thread_stop_info_sp, &crashing_address);
960 if (valobj_sp) {
961 const bool qualify_cxx_base_classes = false;
962
963 const ValueObject::GetExpressionPathFormat format =
964 ValueObject::GetExpressionPathFormat::
965 eGetExpressionPathFormatHonorPointers;
966 stream->PutCString("Likely cause: ");
967 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
968 format);
969 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
970 }
971 }
972 } else {
973 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
974 process_sp->GetTarget().shared_from_this());
975 if (target_idx != UINT32_MAX)
976 stream->Printf("Target %d: (", target_idx);
977 else
978 stream->Printf("Target <unknown index>: (");
979 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
980 stream->Printf(") stopped.\n");
981 }
982 }
983
984 // Pop the process IO handler
985 pop_process_io_handler = true;
986 }
987 break;
988 }
989
990 if (handle_pop && pop_process_io_handler)
991 process_sp->PopProcessIOHandler();
992
993 return true;
994}
995
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996bool Process::HijackProcessEvents(ListenerSP listener_sp) {
997 if (listener_sp) {
998 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
999 eBroadcastBitInterrupt);
1000 } else
1001 return false;
1002}
Greg Claytondc6224e2014-10-21 01:00:42 +00001003
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001005
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001006StateType Process::GetStateChangedEvents(EventSP &event_sp,
1007 const Timeout<std::micro> &timeout,
1008 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001010 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001011
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 ListenerSP listener_sp = hijack_listener_sp;
1013 if (!listener_sp)
1014 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001015
Kate Stoneb9c1b512016-09-06 20:57:50 +00001016 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001017 if (listener_sp->GetEventForBroadcasterWithType(
1018 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001019 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1021 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001022 else
1023 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001025
Pavel Labathd02b1c82017-02-10 11:49:33 +00001026 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027 return state;
1028}
Greg Claytondc6224e2014-10-21 01:00:42 +00001029
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030Event *Process::PeekAtStateChangedEvents() {
1031 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001032
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001033 LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001034
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 Event *event_ptr;
1036 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1037 this, eBroadcastBitStateChanged);
1038 if (log) {
1039 if (event_ptr) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001040 LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
1041 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001043 LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001044 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 }
1046 return event_ptr;
1047}
Greg Claytondc6224e2014-10-21 01:00:42 +00001048
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001049StateType
1050Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1051 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001052 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001053 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054
1055 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001056 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1057 &m_private_state_broadcaster,
1058 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001059 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1061 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1062
Pavel Labathd02b1c82017-02-10 11:49:33 +00001063 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1064 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065 return state;
1066}
1067
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001068bool Process::GetEventsPrivate(EventSP &event_sp,
1069 const Timeout<std::micro> &timeout,
1070 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001072 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073
1074 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001075 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001076 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001078 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079}
1080
1081bool Process::IsRunning() const {
1082 return StateIsRunningState(m_public_state.GetValue());
1083}
1084
1085int Process::GetExitStatus() {
1086 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1087
1088 if (m_public_state.GetValue() == eStateExited)
1089 return m_exit_status;
1090 return -1;
1091}
1092
1093const char *Process::GetExitDescription() {
1094 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1095
1096 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1097 return m_exit_string.c_str();
1098 return nullptr;
1099}
1100
1101bool Process::SetExitStatus(int status, const char *cstr) {
1102 // Use a mutex to protect setting the exit status.
1103 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1104
1105 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1106 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001107 LLDB_LOGF(
1108 log, "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1109 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", cstr ? "\"" : "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110
1111 // We were already in the exited state
1112 if (m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001113 LLDB_LOGF(log, "Process::SetExitStatus () ignoring exit status because "
1114 "state was already set to eStateExited");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001115 return false;
1116 }
1117
1118 m_exit_status = status;
1119 if (cstr)
1120 m_exit_string = cstr;
1121 else
1122 m_exit_string.clear();
1123
Adrian Prantl05097242018-04-30 16:49:04 +00001124 // Clear the last natural stop ID since it has a strong reference to this
1125 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1127
1128 SetPrivateState(eStateExited);
1129
1130 // Allow subclasses to do some cleanup
1131 DidExit();
1132
1133 return true;
1134}
1135
1136bool Process::IsAlive() {
1137 switch (m_private_state.GetValue()) {
1138 case eStateConnected:
1139 case eStateAttaching:
1140 case eStateLaunching:
1141 case eStateStopped:
1142 case eStateRunning:
1143 case eStateStepping:
1144 case eStateCrashed:
1145 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001146 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147 default:
1148 return false;
1149 }
Jason Molendaa814f702015-11-05 23:03:44 +00001150}
1151
Adrian Prantl05097242018-04-30 16:49:04 +00001152// This static callback can be used to watch for local child processes on the
1153// current host. The child process exits, the process will be found in the
1154// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001156bool Process::SetProcessExitStatus(
1157 lldb::pid_t pid, bool exited,
1158 int signo, // Zero for no signal
1159 int exit_status // Exit value of process if signal is zero
1160 ) {
1161 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001162 LLDB_LOGF(log,
1163 "Process::SetProcessExitStatus (pid=%" PRIu64
1164 ", exited=%i, signal=%i, exit_status=%i)\n",
1165 pid, exited, signo, exit_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166
1167 if (exited) {
1168 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1169 if (target_sp) {
1170 ProcessSP process_sp(target_sp->GetProcessSP());
1171 if (process_sp) {
1172 const char *signal_cstr = nullptr;
1173 if (signo)
1174 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1175
1176 process_sp->SetExitStatus(exit_status, signal_cstr);
1177 }
1178 }
1179 return true;
1180 }
1181 return false;
1182}
1183
1184void Process::UpdateThreadListIfNeeded() {
1185 const uint32_t stop_id = GetStopID();
1186 if (m_thread_list.GetSize(false) == 0 ||
1187 stop_id != m_thread_list.GetStopID()) {
1188 const StateType state = GetPrivateState();
1189 if (StateIsStoppedState(state, true)) {
1190 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Adrian Prantl05097242018-04-30 16:49:04 +00001191 // m_thread_list does have its own mutex, but we need to hold onto the
1192 // mutex between the call to UpdateThreadList(...) and the
1193 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194 ThreadList &old_thread_list = m_thread_list;
1195 ThreadList real_thread_list(this);
1196 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001197 // Always update the thread list with the protocol specific thread list,
1198 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1200 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001201 // are shutting down, since that may call back into the SBAPI's,
1202 // requiring the API lock which is already held by whoever is shutting
1203 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 OperatingSystem *os = GetOperatingSystem();
1205 if (os && !m_destroy_in_process) {
1206 // Clear any old backing threads where memory threads might have been
1207 // backed by actual threads from the lldb_private::Process subclass
1208 size_t num_old_threads = old_thread_list.GetSize(false);
1209 for (size_t i = 0; i < num_old_threads; ++i)
1210 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1211
1212 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001213 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001214 // dynamic type or not and we need to avoid this. OperatingSystem
1215 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001216
1217 Target &target = GetTarget();
1218 const lldb::DynamicValueType saved_prefer_dynamic =
1219 target.GetPreferDynamicValue();
1220 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1221 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1222
1223 // Now let the OperatingSystem plug-in update the thread list
1224
1225 os->UpdateThreadList(
1226 old_thread_list, // Old list full of threads created by OS plug-in
1227 real_thread_list, // The actual thread list full of threads
1228 // created by each lldb_private::Process
1229 // subclass
1230 new_thread_list); // The new thread list that we will show to the
1231 // user that gets filled in
1232
1233 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1234 target.SetPreferDynamicValue(saved_prefer_dynamic);
1235 } else {
1236 // No OS plug-in, the new thread list is the same as the real thread
1237 // list
1238 new_thread_list = real_thread_list;
1239 }
1240
1241 m_thread_list_real.Update(real_thread_list);
1242 m_thread_list.Update(new_thread_list);
1243 m_thread_list.SetStopID(stop_id);
1244
1245 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1246 // Clear any extended threads that we may have accumulated previously
1247 m_extended_thread_list.Clear();
1248 m_extended_thread_stop_id = GetLastNaturalStopID();
1249
1250 m_queue_list.Clear();
1251 m_queue_list_stop_id = GetLastNaturalStopID();
1252 }
1253 }
1254 }
1255 }
1256}
1257
1258void Process::UpdateQueueListIfNeeded() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001259 if (m_system_runtime_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001260 if (m_queue_list.GetSize() == 0 ||
1261 m_queue_list_stop_id != GetLastNaturalStopID()) {
1262 const StateType state = GetPrivateState();
1263 if (StateIsStoppedState(state, true)) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001264 m_system_runtime_up->PopulateQueueList(m_queue_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 m_queue_list_stop_id = GetLastNaturalStopID();
1266 }
1267 }
1268 }
1269}
1270
1271ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1272 OperatingSystem *os = GetOperatingSystem();
1273 if (os)
1274 return os->CreateThread(tid, context);
1275 return ThreadSP();
1276}
1277
1278uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1279 return AssignIndexIDToThread(thread_id);
1280}
1281
1282bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1283 return (m_thread_id_to_index_id_map.find(thread_id) !=
1284 m_thread_id_to_index_id_map.end());
1285}
1286
1287uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1288 uint32_t result = 0;
1289 std::map<uint64_t, uint32_t>::iterator iterator =
1290 m_thread_id_to_index_id_map.find(thread_id);
1291 if (iterator == m_thread_id_to_index_id_map.end()) {
1292 result = ++m_thread_index_id;
1293 m_thread_id_to_index_id_map[thread_id] = result;
1294 } else {
1295 result = iterator->second;
1296 }
1297
1298 return result;
1299}
1300
1301StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302 return m_public_state.GetValue();
1303}
1304
Kate Stoneb9c1b512016-09-06 20:57:50 +00001305void Process::SetPublicState(StateType new_state, bool restarted) {
1306 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1307 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001308 LLDB_LOGF(log, "Process::SetPublicState (state = %s, restarted = %i)",
1309 StateAsCString(new_state), restarted);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001310 const StateType old_state = m_public_state.GetValue();
1311 m_public_state.SetValue(new_state);
1312
Adrian Prantl05097242018-04-30 16:49:04 +00001313 // On the transition from Run to Stopped, we unlock the writer end of the run
1314 // lock. The lock gets locked in Resume, which is the public API to tell the
1315 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 if (!StateChangedIsExternallyHijacked()) {
1317 if (new_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001318 LLDB_LOGF(log,
1319 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1320 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001321 m_public_run_lock.SetStopped();
1322 } else {
1323 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1324 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1325 if ((old_state_is_stopped != new_state_is_stopped)) {
1326 if (new_state_is_stopped && !restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001327 LLDB_LOGF(log, "Process::SetPublicState (%s) -- unlocking run lock",
1328 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001329 m_public_run_lock.SetStopped();
1330 }
1331 }
1332 }
1333 }
1334}
1335
Zachary Turner97206d52017-05-12 04:51:55 +00001336Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001337 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1338 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001339 LLDB_LOGF(log, "Process::Resume -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001340 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001341 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001342 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001343 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001345 Status error = PrivateResume();
1346 if (!error.Success()) {
1347 // Undo running state change
1348 m_public_run_lock.SetStopped();
1349 }
1350 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001351}
1352
Jim Ingham3139fc92019-03-01 18:13:38 +00001353static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1354
Zachary Turner97206d52017-05-12 04:51:55 +00001355Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1357 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001358 LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001359 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001360 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001361 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 return error;
1363 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001364
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365 ListenerSP listener_sp(
Jim Ingham3139fc92019-03-01 18:13:38 +00001366 Listener::MakeListener(g_resume_sync_name));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001367 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001368
Zachary Turner97206d52017-05-12 04:51:55 +00001369 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001370 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001371 StateType state =
Konrad Kleine248a1302019-05-23 11:14:47 +00001372 WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373 const bool must_be_alive =
1374 false; // eStateExited is ok, so this must be false
1375 if (!StateIsStoppedState(state, must_be_alive))
1376 error.SetErrorStringWithFormat(
1377 "process not in stopped state after synchronous resume: %s",
1378 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001379 } else {
1380 // Undo running state change
1381 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 }
Ed Mastec29693f2013-07-02 16:35:47 +00001383
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384 // Undo the hijacking of process events...
1385 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001386
Kate Stoneb9c1b512016-09-06 20:57:50 +00001387 return error;
1388}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001389
Jim Ingham3139fc92019-03-01 18:13:38 +00001390bool Process::StateChangedIsExternallyHijacked() {
1391 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1392 const char *hijacking_name = GetHijackingListenerName();
1393 if (hijacking_name &&
1394 strcmp(hijacking_name, g_resume_sync_name))
1395 return true;
1396 }
1397 return false;
1398}
1399
1400bool Process::StateChangedIsHijackedForSynchronousResume() {
1401 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1402 const char *hijacking_name = GetHijackingListenerName();
1403 if (hijacking_name &&
1404 strcmp(hijacking_name, g_resume_sync_name) == 0)
1405 return true;
1406 }
1407 return false;
1408}
1409
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001411
Kate Stoneb9c1b512016-09-06 20:57:50 +00001412void Process::SetPrivateState(StateType new_state) {
1413 if (m_finalize_called)
1414 return;
1415
1416 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1417 LIBLLDB_LOG_PROCESS));
1418 bool state_changed = false;
1419
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001420 LLDB_LOGF(log, "Process::SetPrivateState (%s)", StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421
1422 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1423 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1424
1425 const StateType old_state = m_private_state.GetValueNoLock();
1426 state_changed = old_state != new_state;
1427
1428 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1429 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1430 if (old_state_is_stopped != new_state_is_stopped) {
1431 if (new_state_is_stopped)
1432 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001433 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 m_private_run_lock.SetRunning();
1435 }
1436
1437 if (state_changed) {
1438 m_private_state.SetValueNoLock(new_state);
1439 EventSP event_sp(
1440 new Event(eBroadcastBitStateChanged,
1441 new ProcessEventData(shared_from_this(), new_state)));
1442 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001443 // Note, this currently assumes that all threads in the list stop when
1444 // the process stops. In the future we will want to support a debugging
1445 // model where some threads continue to run while others are stopped.
1446 // When that happens we will either need a way for the thread list to
1447 // identify which threads are stopping or create a special thread list
1448 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 //
Adrian Prantl05097242018-04-30 16:49:04 +00001450 // The process plugin is responsible for managing the actual behavior of
1451 // the threads and should have stopped any threads that are going to stop
1452 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453 m_thread_list.DidStop();
1454
1455 m_mod_id.BumpStopID();
1456 if (!m_mod_id.IsLastResumeForUserExpression())
1457 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1458 m_memory_cache.Clear();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001459 LLDB_LOGF(log, "Process::SetPrivateState (%s) stop_id = %u",
1460 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001461 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001462
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 // Use our target to get a shared pointer to ourselves...
1464 if (m_finalize_called && !PrivateStateThreadIsValid())
1465 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001466 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001467 m_private_state_broadcaster.BroadcastEvent(event_sp);
1468 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001469 LLDB_LOGF(log,
1470 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1471 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001472 }
Jim Ingham22777012010-09-23 02:01:19 +00001473}
1474
Kate Stoneb9c1b512016-09-06 20:57:50 +00001475void Process::SetRunningUserExpression(bool on) {
1476 m_mod_id.SetRunningUserExpression(on);
1477}
1478
Raphael Isemannc01783a2018-08-29 22:50:54 +00001479void Process::SetRunningUtilityFunction(bool on) {
1480 m_mod_id.SetRunningUtilityFunction(on);
1481}
1482
Kate Stoneb9c1b512016-09-06 20:57:50 +00001483addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1484
1485const lldb::ABISP &Process::GetABI() {
1486 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001487 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001488 return m_abi_sp;
1489}
1490
Alex Langford03e1a822019-05-29 18:08:22 +00001491std::vector<LanguageRuntime *>
1492Process::GetLanguageRuntimes(bool retry_if_null) {
1493 std::vector<LanguageRuntime *> language_runtimes;
1494
1495 if (m_finalizing)
1496 return language_runtimes;
1497
1498 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1499 // Before we pass off a copy of the language runtimes, we must make sure that
1500 // our collection is properly populated. It's possible that some of the
1501 // language runtimes were not loaded yet, either because nobody requested it
1502 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1503 // hadn't been loaded).
1504 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
1505 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type, retry_if_null))
1506 language_runtimes.emplace_back(runtime);
1507 }
1508
1509 return language_runtimes;
1510}
1511
Kate Stoneb9c1b512016-09-06 20:57:50 +00001512LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1513 bool retry_if_null) {
1514 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001515 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001516
Alex Langford7d3e97f2019-05-29 21:07:53 +00001517 LanguageRuntime *runtime = nullptr;
1518
Alex Langford74eb76f2019-05-22 23:01:18 +00001519 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001520 LanguageRuntimeCollection::iterator pos;
1521 pos = m_language_runtimes.find(language);
Alex Langford7d3e97f2019-05-29 21:07:53 +00001522 if (pos == m_language_runtimes.end() || (retry_if_null && !pos->second)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001523 lldb::LanguageRuntimeSP runtime_sp(
1524 LanguageRuntime::FindPlugin(this, language));
1525
1526 m_language_runtimes[language] = runtime_sp;
Alex Langford7d3e97f2019-05-29 21:07:53 +00001527 runtime = runtime_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001528 } else
Alex Langford7d3e97f2019-05-29 21:07:53 +00001529 runtime = pos->second.get();
1530
1531 if (runtime)
1532 // It's possible that a language runtime can support multiple LanguageTypes,
1533 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1534 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1535 // primary language type and make sure that our runtime supports it.
1536 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1537
1538 return runtime;
Jim Ingham22777012010-09-23 02:01:19 +00001539}
1540
Kate Stoneb9c1b512016-09-06 20:57:50 +00001541bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1542 if (m_finalizing)
1543 return false;
1544
1545 if (in_value.IsDynamic())
1546 return false;
1547 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1548
1549 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1550 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1551 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1552 }
1553
Alex Langford41dc5522019-05-30 21:03:53 +00001554 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1555 if (runtime->CouldHaveDynamicValue(in_value))
1556 return true;
1557 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001558
Alex Langford41dc5522019-05-30 21:03:53 +00001559 return false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001560}
1561
Kate Stoneb9c1b512016-09-06 20:57:50 +00001562void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001563 m_dynamic_checkers_up.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001564}
1565
Kate Stoneb9c1b512016-09-06 20:57:50 +00001566BreakpointSiteList &Process::GetBreakpointSiteList() {
1567 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001568}
1569
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1571 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001572}
1573
Kate Stoneb9c1b512016-09-06 20:57:50 +00001574void Process::DisableAllBreakpointSites() {
1575 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1576 // bp_site->SetEnabled(true);
1577 DisableBreakpointSite(bp_site);
1578 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001579}
1580
Zachary Turner97206d52017-05-12 04:51:55 +00001581Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1582 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001583
Kate Stoneb9c1b512016-09-06 20:57:50 +00001584 if (error.Success())
1585 m_breakpoint_site_list.Remove(break_id);
1586
1587 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001588}
1589
Zachary Turner97206d52017-05-12 04:51:55 +00001590Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1591 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001592 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1593 if (bp_site_sp) {
1594 if (bp_site_sp->IsEnabled())
1595 error = DisableBreakpointSite(bp_site_sp.get());
1596 } else {
1597 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1598 break_id);
1599 }
1600
1601 return error;
1602}
1603
Zachary Turner97206d52017-05-12 04:51:55 +00001604Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1605 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001606 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1607 if (bp_site_sp) {
1608 if (!bp_site_sp->IsEnabled())
1609 error = EnableBreakpointSite(bp_site_sp.get());
1610 } else {
1611 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1612 break_id);
1613 }
1614 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001615}
1616
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001617lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001618Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1619 bool use_hardware) {
1620 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001621
Kate Stoneb9c1b512016-09-06 20:57:50 +00001622 bool show_error = true;
1623 switch (GetState()) {
1624 case eStateInvalid:
1625 case eStateUnloaded:
1626 case eStateConnected:
1627 case eStateAttaching:
1628 case eStateLaunching:
1629 case eStateDetached:
1630 case eStateExited:
1631 show_error = false;
1632 break;
1633
1634 case eStateStopped:
1635 case eStateRunning:
1636 case eStateStepping:
1637 case eStateCrashed:
1638 case eStateSuspended:
1639 show_error = IsAlive();
1640 break;
1641 }
1642
Adrian Prantl05097242018-04-30 16:49:04 +00001643 // Reset the IsIndirect flag here, in case the location changes from pointing
1644 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001645 owner->SetIsIndirect(false);
1646
1647 if (owner->ShouldResolveIndirectFunctions()) {
1648 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1649 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001650 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001651 Address symbol_address = symbol->GetAddress();
1652 load_addr = ResolveIndirectFunction(&symbol_address, error);
1653 if (!error.Success() && show_error) {
1654 GetTarget().GetDebugger().GetErrorFile()->Printf(
1655 "warning: failed to resolve indirect function at 0x%" PRIx64
1656 " for breakpoint %i.%i: %s\n",
1657 symbol->GetLoadAddress(&GetTarget()),
1658 owner->GetBreakpoint().GetID(), owner->GetID(),
1659 error.AsCString() ? error.AsCString() : "unknown error");
1660 return LLDB_INVALID_BREAK_ID;
1661 }
1662 Address resolved_address(load_addr);
1663 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1664 owner->SetIsIndirect(true);
1665 } else
1666 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1667 } else
1668 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1669
1670 if (load_addr != LLDB_INVALID_ADDRESS) {
1671 BreakpointSiteSP bp_site_sp;
1672
1673 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001674 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675
1676 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1677
1678 if (bp_site_sp) {
1679 bp_site_sp->AddOwner(owner);
1680 owner->SetBreakpointSite(bp_site_sp);
1681 return bp_site_sp->GetID();
1682 } else {
1683 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1684 load_addr, use_hardware));
1685 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001686 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001687 if (error.Success()) {
1688 owner->SetBreakpointSite(bp_site_sp);
1689 return m_breakpoint_site_list.Add(bp_site_sp);
1690 } else {
Jonas Devliegheree103ae92018-11-15 01:18:15 +00001691 if (show_error || use_hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001692 // Report error for setting breakpoint...
1693 GetTarget().GetDebugger().GetErrorFile()->Printf(
1694 "warning: failed to set breakpoint site at 0x%" PRIx64
1695 " for breakpoint %i.%i: %s\n",
1696 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1697 error.AsCString() ? error.AsCString() : "unknown error");
1698 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001699 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001700 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001701 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001702 }
1703 // We failed to enable the breakpoint
1704 return LLDB_INVALID_BREAK_ID;
1705}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001706
Kate Stoneb9c1b512016-09-06 20:57:50 +00001707void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1708 lldb::user_id_t owner_loc_id,
1709 BreakpointSiteSP &bp_site_sp) {
1710 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1711 if (num_owners == 0) {
1712 // Don't try to disable the site if we don't have a live process anymore.
1713 if (IsAlive())
1714 DisableBreakpointSite(bp_site_sp.get());
1715 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1716 }
1717}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001718
Kate Stoneb9c1b512016-09-06 20:57:50 +00001719size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1720 uint8_t *buf) const {
1721 size_t bytes_removed = 0;
1722 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001723
Kate Stoneb9c1b512016-09-06 20:57:50 +00001724 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1725 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001726 bp_sites_in_range.ForEach([bp_addr, size,
1727 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001728 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1729 addr_t intersect_addr;
1730 size_t intersect_size;
1731 size_t opcode_offset;
1732 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1733 &intersect_size, &opcode_offset)) {
1734 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1735 assert(bp_addr < intersect_addr + intersect_size &&
1736 intersect_addr + intersect_size <= bp_addr + size);
1737 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1738 size_t buf_offset = intersect_addr - bp_addr;
1739 ::memcpy(buf + buf_offset,
1740 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1741 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001742 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001743 }
1744 });
1745 }
1746 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001747}
1748
Kate Stoneb9c1b512016-09-06 20:57:50 +00001749size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1750 PlatformSP platform_sp(GetTarget().GetPlatform());
1751 if (platform_sp)
1752 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1753 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001754}
1755
Zachary Turner97206d52017-05-12 04:51:55 +00001756Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1757 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758 assert(bp_site != nullptr);
1759 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1760 const addr_t bp_addr = bp_site->GetLoadAddress();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001761 LLDB_LOGF(
1762 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1763 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001764 if (bp_site->IsEnabled()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001765 LLDB_LOGF(
1766 log,
1767 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1768 " -- already enabled",
1769 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001770 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001771 }
1772
1773 if (bp_addr == LLDB_INVALID_ADDRESS) {
1774 error.SetErrorString("BreakpointSite contains an invalid load address.");
1775 return error;
1776 }
1777 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1778 // trap for the breakpoint site
1779 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1780
1781 if (bp_opcode_size == 0) {
1782 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1783 "returned zero, unable to get breakpoint "
1784 "trap for address 0x%" PRIx64,
1785 bp_addr);
1786 } else {
1787 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1788
1789 if (bp_opcode_bytes == nullptr) {
1790 error.SetErrorString(
1791 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1792 return error;
1793 }
1794
1795 // Save the original opcode by reading it
1796 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1797 error) == bp_opcode_size) {
1798 // Write a software breakpoint in place of the original opcode
1799 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1800 bp_opcode_size) {
1801 uint8_t verify_bp_opcode_bytes[64];
1802 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1803 error) == bp_opcode_size) {
1804 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1805 bp_opcode_size) == 0) {
1806 bp_site->SetEnabled(true);
1807 bp_site->SetType(BreakpointSite::eSoftware);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001808 LLDB_LOGF(log,
1809 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1810 "addr = 0x%" PRIx64 " -- SUCCESS",
1811 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001812 } else
1813 error.SetErrorString(
1814 "failed to verify the breakpoint trap in memory.");
1815 } else
1816 error.SetErrorString(
1817 "Unable to read memory to verify breakpoint trap.");
1818 } else
1819 error.SetErrorString("Unable to write breakpoint trap to memory.");
1820 } else
1821 error.SetErrorString("Unable to read memory at breakpoint address.");
1822 }
1823 if (log && error.Fail())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001824 LLDB_LOGF(
1825 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001826 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1827 " -- FAILED: %s",
1828 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1829 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830}
1831
Zachary Turner97206d52017-05-12 04:51:55 +00001832Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1833 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001834 assert(bp_site != nullptr);
1835 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1836 addr_t bp_addr = bp_site->GetLoadAddress();
1837 lldb::user_id_t breakID = bp_site->GetID();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001838 LLDB_LOGF(log,
1839 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1840 ") addr = 0x%" PRIx64,
1841 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001842
Kate Stoneb9c1b512016-09-06 20:57:50 +00001843 if (bp_site->IsHardware()) {
1844 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1845 } else if (bp_site->IsEnabled()) {
1846 const size_t break_op_size = bp_site->GetByteSize();
1847 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1848 if (break_op_size > 0) {
1849 // Clear a software breakpoint instruction
1850 uint8_t curr_break_op[8];
1851 assert(break_op_size <= sizeof(curr_break_op));
1852 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001853
Kate Stoneb9c1b512016-09-06 20:57:50 +00001854 // Read the breakpoint opcode
1855 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1856 break_op_size) {
1857 bool verify = false;
1858 // Make sure the breakpoint opcode exists at this address
1859 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1860 break_op_found = true;
1861 // We found a valid breakpoint opcode at this address, now restore
1862 // the saved opcode.
1863 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1864 break_op_size, error) == break_op_size) {
1865 verify = true;
1866 } else
1867 error.SetErrorString(
1868 "Memory write failed when restoring original opcode.");
1869 } else {
1870 error.SetErrorString(
1871 "Original breakpoint trap is no longer in memory.");
1872 // Set verify to true and so we can check if the original opcode has
1873 // already been restored
1874 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001875 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001876
Kate Stoneb9c1b512016-09-06 20:57:50 +00001877 if (verify) {
1878 uint8_t verify_opcode[8];
1879 assert(break_op_size < sizeof(verify_opcode));
1880 // Verify that our original opcode made it back to the inferior
1881 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1882 break_op_size) {
1883 // compare the memory we just read with the original opcode
1884 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1885 break_op_size) == 0) {
1886 // SUCCESS
1887 bp_site->SetEnabled(false);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001888 LLDB_LOGF(log,
1889 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1890 "addr = 0x%" PRIx64 " -- SUCCESS",
1891 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001892 return error;
1893 } else {
1894 if (break_op_found)
1895 error.SetErrorString("Failed to restore original opcode.");
1896 }
1897 } else
1898 error.SetErrorString("Failed to read memory to verify that "
1899 "breakpoint trap was restored.");
1900 }
1901 } else
1902 error.SetErrorString(
1903 "Unable to read memory that should contain the breakpoint trap.");
1904 }
1905 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001906 LLDB_LOGF(
1907 log,
1908 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1909 " -- already disabled",
1910 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001911 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001912 }
1913
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001914 LLDB_LOGF(
1915 log,
1916 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1917 " -- FAILED: %s",
1918 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001919 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001920}
1921
Adrian Prantl05097242018-04-30 16:49:04 +00001922// Uncomment to verify memory caching works after making changes to caching
1923// code
Greg Clayton58be07b2011-01-07 06:08:19 +00001924//#define VERIFY_MEMORY_READS
1925
Zachary Turner97206d52017-05-12 04:51:55 +00001926size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001927 error.Clear();
1928 if (!GetDisableMemoryCache()) {
1929#if defined(VERIFY_MEMORY_READS)
1930 // Memory caching is enabled, with debug verification
1931
1932 if (buf && size) {
1933 // Uncomment the line below to make sure memory caching is working.
1934 // I ran this through the test suite and got no assertions, so I am
1935 // pretty confident this is working well. If any changes are made to
1936 // memory caching, uncomment the line below and test your changes!
1937
1938 // Verify all memory reads by using the cache first, then redundantly
1939 // reading the same memory from the inferior and comparing to make sure
1940 // everything is exactly the same.
1941 std::string verify_buf(size, '\0');
1942 assert(verify_buf.size() == size);
1943 const size_t cache_bytes_read =
1944 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00001945 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001946 const size_t verify_bytes_read =
1947 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1948 verify_buf.size(), verify_error);
1949 assert(cache_bytes_read == verify_bytes_read);
1950 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1951 assert(verify_error.Success() == error.Success());
1952 return cache_bytes_read;
1953 }
1954 return 0;
1955#else // !defined(VERIFY_MEMORY_READS)
1956 // Memory caching is enabled, without debug verification
1957
1958 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00001959#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001960 } else {
1961 // Memory caching is disabled
1962
1963 return ReadMemoryFromInferior(addr, buf, size, error);
1964 }
Greg Clayton58be07b2011-01-07 06:08:19 +00001965}
Kate Stoneb9c1b512016-09-06 20:57:50 +00001966
1967size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00001968 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001969 char buf[256];
1970 out_str.clear();
1971 addr_t curr_addr = addr;
1972 while (true) {
1973 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
1974 if (length == 0)
1975 break;
1976 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00001977 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1978 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00001979 if (length == sizeof(buf) - 1)
1980 curr_addr += length;
1981 else
1982 break;
1983 }
1984 return out_str.size();
1985}
1986
1987size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00001988 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001989 size_t total_bytes_read = 0;
1990 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00001991 // Ensure a null terminator independent of the number of bytes that is
1992 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001993 memset(dst, 0, max_bytes);
1994 size_t bytes_left = max_bytes - type_width;
1995
1996 const char terminator[4] = {'\0', '\0', '\0', '\0'};
1997 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
1998 "string with more than 4 bytes "
1999 "per character!");
2000
Greg Clayton4c82d422012-05-18 23:20:01 +00002001 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002002 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2003 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002004
Kate Stoneb9c1b512016-09-06 20:57:50 +00002005 error.Clear();
2006 while (bytes_left > 0 && error.Success()) {
2007 addr_t cache_line_bytes_left =
2008 cache_line_size - (curr_addr % cache_line_size);
2009 addr_t bytes_to_read =
2010 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2011 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002012
Kate Stoneb9c1b512016-09-06 20:57:50 +00002013 if (bytes_read == 0)
2014 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002015
Kate Stoneb9c1b512016-09-06 20:57:50 +00002016 // Search for a null terminator of correct size and alignment in
2017 // bytes_read
2018 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2019 for (size_t i = aligned_start;
2020 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2021 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2022 error.Clear();
2023 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002024 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002025
2026 total_bytes_read += bytes_read;
2027 curr_dst += bytes_read;
2028 curr_addr += bytes_read;
2029 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002030 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002031 } else {
2032 if (max_bytes)
2033 error.SetErrorString("invalid arguments");
2034 }
2035 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002036}
2037
Kate Stoneb9c1b512016-09-06 20:57:50 +00002038// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002039// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002040size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002041 size_t dst_max_len,
2042 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002043 size_t total_cstr_len = 0;
2044 if (dst && dst_max_len) {
2045 result_error.Clear();
2046 // NULL out everything just to be safe
2047 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002048 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002049 addr_t curr_addr = addr;
2050 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2051 size_t bytes_left = dst_max_len - 1;
2052 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002053
Kate Stoneb9c1b512016-09-06 20:57:50 +00002054 while (bytes_left > 0) {
2055 addr_t cache_line_bytes_left =
2056 cache_line_size - (curr_addr % cache_line_size);
2057 addr_t bytes_to_read =
2058 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2059 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002060
Kate Stoneb9c1b512016-09-06 20:57:50 +00002061 if (bytes_read == 0) {
2062 result_error = error;
2063 dst[total_cstr_len] = '\0';
2064 break;
2065 }
2066 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002067
Kate Stoneb9c1b512016-09-06 20:57:50 +00002068 total_cstr_len += len;
2069
2070 if (len < bytes_to_read)
2071 break;
2072
2073 curr_dst += bytes_read;
2074 curr_addr += bytes_read;
2075 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002076 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002077 } else {
2078 if (dst == nullptr)
2079 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002080 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002081 result_error.Clear();
2082 }
2083 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002084}
2085
Kate Stoneb9c1b512016-09-06 20:57:50 +00002086size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002087 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002088 if (buf == nullptr || size == 0)
2089 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002090
Kate Stoneb9c1b512016-09-06 20:57:50 +00002091 size_t bytes_read = 0;
2092 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002093
Kate Stoneb9c1b512016-09-06 20:57:50 +00002094 while (bytes_read < size) {
2095 const size_t curr_size = size - bytes_read;
2096 const size_t curr_bytes_read =
2097 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2098 bytes_read += curr_bytes_read;
2099 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2100 break;
2101 }
2102
2103 // Replace any software breakpoint opcodes that fall into this range back
2104 // into "buf" before we return
2105 if (bytes_read > 0)
2106 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2107 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108}
2109
Kate Stoneb9c1b512016-09-06 20:57:50 +00002110uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2111 size_t integer_byte_size,
2112 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002113 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002114 Scalar scalar;
2115 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2116 error))
2117 return scalar.ULongLong(fail_value);
2118 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002119}
2120
Kate Stoneb9c1b512016-09-06 20:57:50 +00002121int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2122 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002123 int64_t fail_value,
2124 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002125 Scalar scalar;
2126 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2127 error))
2128 return scalar.SLongLong(fail_value);
2129 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002130}
2131
Zachary Turner97206d52017-05-12 04:51:55 +00002132addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002133 Scalar scalar;
2134 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2135 error))
2136 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2137 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002138}
2139
Kate Stoneb9c1b512016-09-06 20:57:50 +00002140bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002141 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002142 Scalar scalar;
2143 const uint32_t addr_byte_size = GetAddressByteSize();
2144 if (addr_byte_size <= 4)
2145 scalar = (uint32_t)ptr_value;
2146 else
2147 scalar = ptr_value;
2148 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2149 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002150}
2151
Kate Stoneb9c1b512016-09-06 20:57:50 +00002152size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002153 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002154 size_t bytes_written = 0;
2155 const uint8_t *bytes = (const uint8_t *)buf;
2156
2157 while (bytes_written < size) {
2158 const size_t curr_size = size - bytes_written;
2159 const size_t curr_bytes_written = DoWriteMemory(
2160 addr + bytes_written, bytes + bytes_written, curr_size, error);
2161 bytes_written += curr_bytes_written;
2162 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2163 break;
2164 }
2165 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002166}
2167
Kate Stoneb9c1b512016-09-06 20:57:50 +00002168size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002169 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002170#if defined(ENABLE_MEMORY_CACHING)
2171 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002172#endif
2173
Kate Stoneb9c1b512016-09-06 20:57:50 +00002174 if (buf == nullptr || size == 0)
2175 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002176
Kate Stoneb9c1b512016-09-06 20:57:50 +00002177 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002178
Kate Stoneb9c1b512016-09-06 20:57:50 +00002179 // We need to write any data that would go where any current software traps
2180 // (enabled software breakpoints) any software traps (breakpoints) that we
2181 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002182
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183 BreakpointSiteList bp_sites_in_range;
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002184 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002185 return WriteMemoryPrivate(addr, buf, size, error);
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002186
2187 // No breakpoint sites overlap
2188 if (bp_sites_in_range.IsEmpty())
2189 return WriteMemoryPrivate(addr, buf, size, error);
2190
2191 const uint8_t *ubuf = (const uint8_t *)buf;
2192 uint64_t bytes_written = 0;
2193
2194 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2195 &error](BreakpointSite *bp) -> void {
2196 if (error.Fail())
2197 return;
2198
2199 addr_t intersect_addr;
2200 size_t intersect_size;
2201 size_t opcode_offset;
2202 const bool intersects = bp->IntersectsRange(
2203 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2204 UNUSED_IF_ASSERT_DISABLED(intersects);
2205 assert(intersects);
2206 assert(addr <= intersect_addr && intersect_addr < addr + size);
2207 assert(addr < intersect_addr + intersect_size &&
2208 intersect_addr + intersect_size <= addr + size);
2209 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2210
2211 // Check for bytes before this breakpoint
2212 const addr_t curr_addr = addr + bytes_written;
2213 if (intersect_addr > curr_addr) {
2214 // There are some bytes before this breakpoint that we need to just
2215 // write to memory
2216 size_t curr_size = intersect_addr - curr_addr;
2217 size_t curr_bytes_written =
2218 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2219 bytes_written += curr_bytes_written;
2220 if (curr_bytes_written != curr_size) {
2221 // We weren't able to write all of the requested bytes, we are
2222 // done looping and will return the number of bytes that we have
2223 // written so far.
2224 if (error.Success())
2225 error.SetErrorToGenericError();
2226 }
2227 }
2228 // Now write any bytes that would cover up any software breakpoints
2229 // directly into the breakpoint opcode buffer
2230 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2231 intersect_size);
2232 bytes_written += intersect_size;
2233 });
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234
2235 // Write any remaining bytes after the last breakpoint if we have any left
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002236 if (bytes_written < size)
2237 bytes_written +=
2238 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2239 size - bytes_written, error);
2240
2241 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002242}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002243
Kate Stoneb9c1b512016-09-06 20:57:50 +00002244size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002245 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002246 if (byte_size == UINT32_MAX)
2247 byte_size = scalar.GetByteSize();
2248 if (byte_size > 0) {
2249 uint8_t buf[32];
2250 const size_t mem_size =
2251 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2252 if (mem_size > 0)
2253 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002254 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002255 error.SetErrorString("failed to get scalar as memory data");
2256 } else {
2257 error.SetErrorString("invalid scalar value");
2258 }
2259 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002260}
2261
Kate Stoneb9c1b512016-09-06 20:57:50 +00002262size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2263 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002264 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265 uint64_t uval = 0;
2266 if (byte_size == 0) {
2267 error.SetErrorString("byte size is zero");
2268 } else if (byte_size & (byte_size - 1)) {
2269 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2270 byte_size);
2271 } else if (byte_size <= sizeof(uval)) {
2272 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2273 if (bytes_read == byte_size) {
2274 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2275 GetAddressByteSize());
2276 lldb::offset_t offset = 0;
2277 if (byte_size <= 4)
2278 scalar = data.GetMaxU32(&offset, byte_size);
2279 else
2280 scalar = data.GetMaxU64(&offset, byte_size);
2281 if (is_signed)
2282 scalar.SignExtend(byte_size * 8);
2283 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002284 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002285 } else {
2286 error.SetErrorStringWithFormat(
2287 "byte size of %u is too large for integer scalar type", byte_size);
2288 }
2289 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002290}
2291
Pavel Labath16064d32018-03-20 11:56:24 +00002292Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2293 Status error;
2294 for (const auto &Entry : entries) {
2295 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2296 error);
2297 if (!error.Success())
2298 break;
2299 }
2300 return error;
2301}
2302
Greg Claytond495c532011-05-17 03:37:42 +00002303#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002304addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002305 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002306 if (GetPrivateState() != eStateStopped) {
2307 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002308 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002309 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002310
2311#if defined(USE_ALLOCATE_MEMORY_CACHE)
2312 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002313#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002314 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2315 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002316 LLDB_LOGF(log,
2317 "Process::AllocateMemory(size=%" PRIu64
2318 ", permissions=%s) => 0x%16.16" PRIx64
2319 " (m_stop_id = %u m_memory_id = %u)",
2320 (uint64_t)size, GetPermissionsAsCString(permissions),
2321 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2322 m_mod_id.GetMemoryID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002323 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002324#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002325}
2326
Kate Stoneb9c1b512016-09-06 20:57:50 +00002327addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002328 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002329 addr_t return_addr = AllocateMemory(size, permissions, error);
2330 if (error.Success()) {
2331 std::string buffer(size, 0);
2332 WriteMemory(return_addr, buffer.c_str(), size, error);
2333 }
2334 return return_addr;
2335}
2336
2337bool Process::CanJIT() {
2338 if (m_can_jit == eCanJITDontKnow) {
2339 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002340 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341
2342 uint64_t allocated_memory = AllocateMemory(
2343 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2344 err);
2345
2346 if (err.Success()) {
2347 m_can_jit = eCanJITYes;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002348 LLDB_LOGF(log,
2349 "Process::%s pid %" PRIu64
2350 " allocation test passed, CanJIT () is true",
2351 __FUNCTION__, GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002352 } else {
2353 m_can_jit = eCanJITNo;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002354 LLDB_LOGF(log,
2355 "Process::%s pid %" PRIu64
2356 " allocation test failed, CanJIT () is false: %s",
2357 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002358 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359
2360 DeallocateMemory(allocated_memory);
2361 }
2362
2363 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002364}
2365
Kate Stoneb9c1b512016-09-06 20:57:50 +00002366void Process::SetCanJIT(bool can_jit) {
2367 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002368}
2369
Kate Stoneb9c1b512016-09-06 20:57:50 +00002370void Process::SetCanRunCode(bool can_run_code) {
2371 SetCanJIT(can_run_code);
2372 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002373}
2374
Zachary Turner97206d52017-05-12 04:51:55 +00002375Status Process::DeallocateMemory(addr_t ptr) {
2376 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002377#if defined(USE_ALLOCATE_MEMORY_CACHE)
2378 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2379 error.SetErrorStringWithFormat(
2380 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2381 }
Greg Claytond495c532011-05-17 03:37:42 +00002382#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002383 error = DoDeallocateMemory(ptr);
2384
2385 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002386 LLDB_LOGF(log,
2387 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2388 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2389 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2390 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002391#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002392 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002393}
2394
Kate Stoneb9c1b512016-09-06 20:57:50 +00002395ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2396 lldb::addr_t header_addr,
2397 size_t size_to_read) {
2398 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2399 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002400 LLDB_LOGF(log,
2401 "Process::ReadModuleFromMemory reading %s binary from memory",
2402 file_spec.GetPath().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403 }
2404 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2405 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002406 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2408 shared_from_this(), header_addr, error, size_to_read);
2409 if (objfile)
2410 return module_sp;
2411 }
2412 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413}
2414
Kate Stoneb9c1b512016-09-06 20:57:50 +00002415bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2416 uint32_t &permissions) {
2417 MemoryRegionInfo range_info;
2418 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002419 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002420 if (!error.Success())
2421 return false;
2422 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2423 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2424 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2425 return false;
2426 }
2427
2428 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2429 permissions |= lldb::ePermissionsReadable;
2430
2431 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2432 permissions |= lldb::ePermissionsWritable;
2433
2434 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2435 permissions |= lldb::ePermissionsExecutable;
2436
2437 return true;
2438}
2439
Zachary Turner97206d52017-05-12 04:51:55 +00002440Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2441 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002442 error.SetErrorString("watchpoints are not supported");
2443 return error;
2444}
2445
Zachary Turner97206d52017-05-12 04:51:55 +00002446Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2447 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002448 error.SetErrorString("watchpoints are not supported");
2449 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002450}
2451
2452StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002453Process::WaitForProcessStopPrivate(EventSP &event_sp,
2454 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002455 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002456
Kate Stoneb9c1b512016-09-06 20:57:50 +00002457 while (true) {
2458 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002459 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002460
Kate Stoneb9c1b512016-09-06 20:57:50 +00002461 if (StateIsStoppedState(state, false))
2462 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002463
Kate Stoneb9c1b512016-09-06 20:57:50 +00002464 // If state is invalid, then we timed out
2465 if (state == eStateInvalid)
2466 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002467
Kate Stoneb9c1b512016-09-06 20:57:50 +00002468 if (event_sp)
2469 HandlePrivateEvent(event_sp);
2470 }
2471 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002472}
2473
Kate Stoneb9c1b512016-09-06 20:57:50 +00002474void Process::LoadOperatingSystemPlugin(bool flush) {
2475 if (flush)
2476 m_thread_list.Clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002477 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002478 if (flush)
2479 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002480}
2481
Zachary Turner97206d52017-05-12 04:51:55 +00002482Status Process::Launch(ProcessLaunchInfo &launch_info) {
2483 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002484 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002485 m_dyld_up.reset();
2486 m_jit_loaders_up.reset();
2487 m_system_runtime_up.reset();
2488 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002489 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002490
Kate Stoneb9c1b512016-09-06 20:57:50 +00002491 Module *exe_module = GetTarget().GetExecutableModulePointer();
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002492 if (!exe_module) {
2493 error.SetErrorString("executable module does not exist");
2494 return error;
2495 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002496
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002497 char local_exec_file_path[PATH_MAX];
2498 char platform_exec_file_path[PATH_MAX];
2499 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2500 sizeof(local_exec_file_path));
2501 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2502 sizeof(platform_exec_file_path));
2503 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2504 // Install anything that might need to be installed prior to launching.
2505 // For host systems, this will do nothing, but if we are connected to a
2506 // remote platform it will install any needed binaries
2507 error = GetTarget().Install(&launch_info);
2508 if (error.Fail())
2509 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002510
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002511 if (PrivateStateThreadIsValid())
2512 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002513
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002514 error = WillLaunch(exe_module);
2515 if (error.Success()) {
2516 const bool restarted = false;
2517 SetPublicState(eStateLaunching, restarted);
2518 m_should_detach = false;
2519
2520 if (m_public_run_lock.TrySetRunning()) {
2521 // Now launch using these arguments.
2522 error = DoLaunch(exe_module, launch_info);
2523 } else {
2524 // This shouldn't happen
2525 error.SetErrorString("failed to acquire process run lock");
2526 }
2527
2528 if (error.Fail()) {
2529 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2530 SetID(LLDB_INVALID_PROCESS_ID);
2531 const char *error_string = error.AsCString();
2532 if (error_string == nullptr)
2533 error_string = "launch failed";
2534 SetExitStatus(-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002535 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002536 } else {
2537 EventSP event_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002538
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002539 // Now wait for the process to launch and return control to us, and then
2540 // call DidLaunch:
2541 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Stella Stamenova36d457c2018-06-01 19:14:53 +00002542
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002543 if (state == eStateInvalid || !event_sp) {
2544 // We were able to launch the process, but we failed to catch the
2545 // initial stop.
2546 error.SetErrorString("failed to catch stop after launch");
2547 SetExitStatus(0, "failed to catch stop after launch");
2548 Destroy(false);
2549 } else if (state == eStateStopped || state == eStateCrashed) {
2550 DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002551
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002552 DynamicLoader *dyld = GetDynamicLoader();
2553 if (dyld)
2554 dyld->DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002555
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002556 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002557
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002558 SystemRuntime *system_runtime = GetSystemRuntime();
2559 if (system_runtime)
2560 system_runtime->DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002561
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002562 if (!m_os_up)
2563 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002564
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002565 // We successfully launched the process and stopped, now it the
2566 // right time to set up signal filters before resuming.
2567 UpdateAutomaticSignalFiltering();
Greg Clayton35824e32015-02-20 20:59:47 +00002568
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002569 // Note, the stop event was consumed above, but not handled. This
2570 // was done to give DidLaunch a chance to run. The target is either
2571 // stopped or crashed. Directly set the state. This is done to
2572 // prevent a stop message with a bunch of spurious output on thread
2573 // status, as well as not pop a ProcessIOHandler.
2574 SetPublicState(state, false);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002575
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002576 if (PrivateStateThreadIsValid())
2577 ResumePrivateStateThread();
2578 else
2579 StartPrivateStateThread();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002580
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002581 // Target was stopped at entry as was intended. Need to notify the
2582 // listeners about it.
2583 if (state == eStateStopped &&
2584 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002585 HandlePrivateEvent(event_sp);
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002586 } else if (state == eStateExited) {
2587 // We exited while trying to launch somehow. Don't call DidLaunch
2588 // as that's not likely to work, and return an invalid pid.
2589 HandlePrivateEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002590 }
2591 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002592 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002593 } else {
2594 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2595 local_exec_file_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002596 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002597
Kate Stoneb9c1b512016-09-06 20:57:50 +00002598 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002599}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002600
Zachary Turner97206d52017-05-12 04:51:55 +00002601Status Process::LoadCore() {
2602 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002603 if (error.Success()) {
2604 ListenerSP listener_sp(
2605 Listener::MakeListener("lldb.process.load_core_listener"));
2606 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002607
Kate Stoneb9c1b512016-09-06 20:57:50 +00002608 if (PrivateStateThreadIsValid())
2609 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002610 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002611 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002612
Kate Stoneb9c1b512016-09-06 20:57:50 +00002613 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002614 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002615 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002616
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002617 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002618
Kate Stoneb9c1b512016-09-06 20:57:50 +00002619 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002620 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002621 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002622
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002623 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00002624 LoadOperatingSystemPlugin(false);
2625
Kate Stoneb9c1b512016-09-06 20:57:50 +00002626 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002627 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002628 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002629
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002630 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002631 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002632 StateType state =
Pavel Labath7ada1c52019-06-25 07:14:29 +00002633 WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002634
2635 if (!StateIsStoppedState(state, false)) {
2636 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002637 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2638 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002639 error.SetErrorString(
2640 "Did not get stopped event after loading the core file.");
2641 }
2642 RestoreProcessEvents();
2643 }
2644 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002645}
2646
Kate Stoneb9c1b512016-09-06 20:57:50 +00002647DynamicLoader *Process::GetDynamicLoader() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002648 if (!m_dyld_up)
2649 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2650 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002651}
2652
Antonio Afonso943faef2019-06-11 20:16:13 +00002653DataExtractor Process::GetAuxvData() { return DataExtractor(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002654
2655JITLoaderList &Process::GetJITLoaders() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002656 if (!m_jit_loaders_up) {
2657 m_jit_loaders_up.reset(new JITLoaderList());
2658 JITLoader::LoadPlugins(this, *m_jit_loaders_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002659 }
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002660 return *m_jit_loaders_up;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002661}
2662
2663SystemRuntime *Process::GetSystemRuntime() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002664 if (!m_system_runtime_up)
2665 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2666 return m_system_runtime_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002667}
2668
2669Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2670 uint32_t exec_count)
2671 : NextEventAction(process), m_exec_count(exec_count) {
2672 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002673 LLDB_LOGF(
2674 log,
2675 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2676 __FUNCTION__, static_cast<void *>(process), exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002677}
2678
2679Process::NextEventAction::EventActionResult
2680Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2681 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2682
2683 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002684 LLDB_LOGF(log,
2685 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2686 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002687
2688 switch (state) {
2689 case eStateAttaching:
2690 return eEventActionSuccess;
2691
2692 case eStateRunning:
2693 case eStateConnected:
2694 return eEventActionRetry;
2695
2696 case eStateStopped:
2697 case eStateCrashed:
2698 // During attach, prior to sending the eStateStopped event,
2699 // lldb_private::Process subclasses must set the new process ID.
2700 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002701 // We don't want these events to be reported, so go set the
2702 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002703 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2704
2705 if (m_exec_count > 0) {
2706 --m_exec_count;
2707
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002708 LLDB_LOGF(log,
2709 "Process::AttachCompletionHandler::%s state %s: reduced "
2710 "remaining exec count to %" PRIu32 ", requesting resume",
2711 __FUNCTION__, StateAsCString(state), m_exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712
2713 RequestResume();
2714 return eEventActionRetry;
2715 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002716 LLDB_LOGF(log,
2717 "Process::AttachCompletionHandler::%s state %s: no more "
2718 "execs expected to start, continuing with attach",
2719 __FUNCTION__, StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002720
2721 m_process->CompleteAttach();
2722 return eEventActionSuccess;
2723 }
2724 break;
2725
2726 default:
2727 case eStateExited:
2728 case eStateInvalid:
2729 break;
2730 }
2731
2732 m_exit_string.assign("No valid Process");
2733 return eEventActionExit;
2734}
2735
2736Process::NextEventAction::EventActionResult
2737Process::AttachCompletionHandler::HandleBeingInterrupted() {
2738 return eEventActionSuccess;
2739}
2740
2741const char *Process::AttachCompletionHandler::GetExitString() {
2742 return m_exit_string.c_str();
2743}
2744
2745ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2746 if (m_listener_sp)
2747 return m_listener_sp;
2748 else
2749 return debugger.GetListener();
2750}
2751
Zachary Turner97206d52017-05-12 04:51:55 +00002752Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002753 m_abi_sp.reset();
2754 m_process_input_reader.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002755 m_dyld_up.reset();
2756 m_jit_loaders_up.reset();
2757 m_system_runtime_up.reset();
2758 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002759
2760 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002761 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2763 char process_name[PATH_MAX];
2764
2765 if (attach_info.GetExecutableFile().GetPath(process_name,
2766 sizeof(process_name))) {
2767 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2768
2769 if (wait_for_launch) {
2770 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2771 if (error.Success()) {
2772 if (m_public_run_lock.TrySetRunning()) {
2773 m_should_detach = true;
2774 const bool restarted = false;
2775 SetPublicState(eStateAttaching, restarted);
2776 // Now attach using these arguments.
2777 error = DoAttachToProcessWithName(process_name, attach_info);
2778 } else {
2779 // This shouldn't happen
2780 error.SetErrorString("failed to acquire process run lock");
2781 }
2782
2783 if (error.Fail()) {
2784 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2785 SetID(LLDB_INVALID_PROCESS_ID);
2786 if (error.AsCString() == nullptr)
2787 error.SetErrorString("attach failed");
2788
2789 SetExitStatus(-1, error.AsCString());
2790 }
2791 } else {
2792 SetNextEventAction(new Process::AttachCompletionHandler(
2793 this, attach_info.GetResumeCount()));
2794 StartPrivateStateThread();
2795 }
2796 return error;
2797 }
2798 } else {
2799 ProcessInstanceInfoList process_infos;
2800 PlatformSP platform_sp(GetTarget().GetPlatform());
2801
2802 if (platform_sp) {
2803 ProcessInstanceInfoMatch match_info;
2804 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00002805 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806 platform_sp->FindProcesses(match_info, process_infos);
2807 const uint32_t num_matches = process_infos.GetSize();
2808 if (num_matches == 1) {
2809 attach_pid = process_infos.GetProcessIDAtIndex(0);
2810 // Fall through and attach using the above process ID
2811 } else {
2812 match_info.GetProcessInfo().GetExecutableFile().GetPath(
2813 process_name, sizeof(process_name));
2814 if (num_matches > 1) {
2815 StreamString s;
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002816 ProcessInstanceInfo::DumpTableHeader(s, true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817 for (size_t i = 0; i < num_matches; i++) {
2818 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002819 s, platform_sp->GetUserIDResolver(), true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002820 }
2821 error.SetErrorStringWithFormat(
2822 "more than one process named %s:\n%s", process_name,
2823 s.GetData());
2824 } else
2825 error.SetErrorStringWithFormat(
2826 "could not find a process named %s", process_name);
2827 }
2828 } else {
2829 error.SetErrorString(
2830 "invalid platform, can't find processes by name");
2831 return error;
2832 }
2833 }
2834 } else {
2835 error.SetErrorString("invalid process name");
2836 }
2837 }
2838
2839 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2840 error = WillAttachToProcessWithID(attach_pid);
2841 if (error.Success()) {
2842
2843 if (m_public_run_lock.TrySetRunning()) {
2844 // Now attach using these arguments.
2845 m_should_detach = true;
2846 const bool restarted = false;
2847 SetPublicState(eStateAttaching, restarted);
2848 error = DoAttachToProcessWithID(attach_pid, attach_info);
2849 } else {
2850 // This shouldn't happen
2851 error.SetErrorString("failed to acquire process run lock");
2852 }
2853
2854 if (error.Success()) {
2855 SetNextEventAction(new Process::AttachCompletionHandler(
2856 this, attach_info.GetResumeCount()));
2857 StartPrivateStateThread();
2858 } else {
Greg Clayton71337622011-02-24 22:24:29 +00002859 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002860 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002861
Kate Stoneb9c1b512016-09-06 20:57:50 +00002862 const char *error_string = error.AsCString();
2863 if (error_string == nullptr)
2864 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00002865
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866 SetExitStatus(-1, error_string);
2867 }
Greg Claytonb766a732011-02-04 01:58:07 +00002868 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002869 }
2870 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00002871}
2872
Kate Stoneb9c1b512016-09-06 20:57:50 +00002873void Process::CompleteAttach() {
2874 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2875 LIBLLDB_LOG_TARGET));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002876 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002877
2878 // Let the process subclass figure out at much as it can about the process
2879 // before we go looking for a dynamic loader plug-in.
2880 ArchSpec process_arch;
2881 DidAttach(process_arch);
2882
2883 if (process_arch.IsValid()) {
2884 GetTarget().SetArchitecture(process_arch);
2885 if (log) {
2886 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002887 LLDB_LOGF(log,
2888 "Process::%s replacing process architecture with DidAttach() "
2889 "architecture: %s",
2890 __FUNCTION__, triple_str ? triple_str : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002891 }
2892 }
2893
2894 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00002895 // architecture, and if it isn't the same as the one we've already set,
2896 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002897 PlatformSP platform_sp(GetTarget().GetPlatform());
2898 assert(platform_sp);
2899 if (platform_sp) {
2900 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2901 if (target_arch.IsValid() &&
2902 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2903 ArchSpec platform_arch;
2904 platform_sp =
2905 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2906 if (platform_sp) {
2907 GetTarget().SetPlatform(platform_sp);
2908 GetTarget().SetArchitecture(platform_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002909 LLDB_LOGF(log,
2910 "Process::%s switching platform to %s and architecture "
2911 "to %s based on info from attach",
2912 __FUNCTION__, platform_sp->GetName().AsCString(""),
2913 platform_arch.GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002914 }
2915 } else if (!process_arch.IsValid()) {
2916 ProcessInstanceInfo process_info;
2917 GetProcessInfo(process_info);
2918 const ArchSpec &process_arch = process_info.GetArchitecture();
2919 if (process_arch.IsValid() &&
2920 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
2921 GetTarget().SetArchitecture(process_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002922 LLDB_LOGF(log,
2923 "Process::%s switching architecture to %s based on info "
2924 "the platform retrieved for pid %" PRIu64,
2925 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
2926 GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002927 }
2928 }
2929 }
2930
2931 // We have completed the attach, now it is time to find the dynamic loader
2932 // plug-in
2933 DynamicLoader *dyld = GetDynamicLoader();
2934 if (dyld) {
2935 dyld->DidAttach();
2936 if (log) {
2937 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002938 LLDB_LOGF(log,
2939 "Process::%s after DynamicLoader::DidAttach(), target "
2940 "executable is %s (using %s plugin)",
2941 __FUNCTION__,
2942 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2943 : "<none>",
2944 dyld->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002945 }
2946 }
2947
2948 GetJITLoaders().DidAttach();
2949
2950 SystemRuntime *system_runtime = GetSystemRuntime();
2951 if (system_runtime) {
2952 system_runtime->DidAttach();
2953 if (log) {
2954 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002955 LLDB_LOGF(log,
2956 "Process::%s after SystemRuntime::DidAttach(), target "
2957 "executable is %s (using %s plugin)",
2958 __FUNCTION__,
2959 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2960 : "<none>",
2961 system_runtime->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002962 }
2963 }
2964
Jim Ingham8864b432019-06-28 17:57:19 +00002965 if (!m_os_up) {
Greg Clayton29eeea02017-02-09 18:55:41 +00002966 LoadOperatingSystemPlugin(false);
Jim Ingham8864b432019-06-28 17:57:19 +00002967 if (m_os_up) {
2968 // Somebody might have gotten threads before now, but we need to force the
2969 // update after we've loaded the OperatingSystem plugin or it won't get a
2970 // chance to process the threads.
2971 m_thread_list.Clear();
2972 UpdateThreadListIfNeeded();
2973 }
2974 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 // Figure out which one is the executable, and set that in our target:
2976 const ModuleList &target_modules = GetTarget().GetImages();
2977 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
2978 size_t num_modules = target_modules.GetSize();
2979 ModuleSP new_executable_module_sp;
2980
2981 for (size_t i = 0; i < num_modules; i++) {
2982 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
2983 if (module_sp && module_sp->IsExecutable()) {
2984 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
2985 new_executable_module_sp = module_sp;
2986 break;
2987 }
2988 }
2989 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00002990 GetTarget().SetExecutableModule(new_executable_module_sp,
2991 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 if (log) {
2993 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002994 LLDB_LOGF(
2995 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002996 "Process::%s after looping through modules, target executable is %s",
2997 __FUNCTION__,
2998 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2999 : "<none>");
3000 }
3001 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003002}
3003
Zachary Turner97206d52017-05-12 04:51:55 +00003004Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003005 m_abi_sp.reset();
3006 m_process_input_reader.reset();
3007
3008 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003009 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003010
Zachary Turner97206d52017-05-12 04:51:55 +00003011 Status error(DoConnectRemote(strm, remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003012 if (error.Success()) {
3013 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3014 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003015 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003016
3017 if (state == eStateStopped || state == eStateCrashed) {
3018 // If we attached and actually have a process on the other end, then
3019 // this ended up being the equivalent of an attach.
3020 CompleteAttach();
3021
3022 // This delays passing the stopped event to listeners till
3023 // CompleteAttach gets a chance to complete...
3024 HandlePrivateEvent(event_sp);
3025 }
3026 }
3027
3028 if (PrivateStateThreadIsValid())
3029 ResumePrivateStateThread();
3030 else
3031 StartPrivateStateThread();
3032 }
3033 return error;
3034}
3035
Zachary Turner97206d52017-05-12 04:51:55 +00003036Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3038 LIBLLDB_LOG_STEP));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003039 LLDB_LOGF(log,
3040 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3041 "private state: %s",
3042 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3043 StateAsCString(m_private_state.GetValue()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003044
Adrian Prantl05097242018-04-30 16:49:04 +00003045 // If signals handing status changed we might want to update our signal
3046 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003047 UpdateAutomaticSignalFiltering();
3048
Zachary Turner97206d52017-05-12 04:51:55 +00003049 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003050 // Tell the process it is about to resume before the thread list
3051 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003052 // Now let the thread list know we are about to resume so it can let all of
3053 // our threads know that they are about to be resumed. Threads will each be
3054 // called with Thread::WillResume(StateType) where StateType contains the
3055 // state that they are supposed to have when the process is resumed
3056 // (suspended/running/stepping). Threads should also check their resume
3057 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3058 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003059 if (m_thread_list.WillResume()) {
3060 // Last thing, do the PreResumeActions.
3061 if (!RunPreResumeActions()) {
3062 error.SetErrorStringWithFormat(
3063 "Process::PrivateResume PreResumeActions failed, not resuming.");
3064 } else {
3065 m_mod_id.BumpResumeID();
3066 error = DoResume();
3067 if (error.Success()) {
3068 DidResume();
3069 m_thread_list.DidResume();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003070 LLDB_LOGF(log, "Process thinks the process has resumed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003071 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003072 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003073 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003074 }
3075 }
3076 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003077 // Somebody wanted to run without running (e.g. we were faking a step
3078 // from one frame of a set of inlined frames that share the same PC to
3079 // another.) So generate a continue & a stopped event, and let the world
3080 // handle them.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003081 LLDB_LOGF(log,
3082 "Process::PrivateResume() asked to simulate a start & stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003083
3084 SetPrivateState(eStateRunning);
3085 SetPrivateState(eStateStopped);
3086 }
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003087 } else
3088 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3089 error.AsCString("<unknown error>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003090 return error;
3091}
3092
Zachary Turner97206d52017-05-12 04:51:55 +00003093Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003094 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003095 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096
Adrian Prantl05097242018-04-30 16:49:04 +00003097 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3098 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 m_clear_thread_plans_on_stop |= clear_thread_plans;
3100
3101 ListenerSP halt_listener_sp(
3102 Listener::MakeListener("lldb.process.halt_listener"));
3103 HijackProcessEvents(halt_listener_sp);
3104
3105 EventSP event_sp;
3106
3107 SendAsyncInterrupt();
3108
3109 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003110 // Don't hijack and eat the eStateExited as the code that was doing the
3111 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003112 RestoreProcessEvents();
3113 SetExitStatus(SIGKILL, "Cancelled async attach.");
3114 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003115 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003116 }
3117
3118 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003119 StateType state = WaitForProcessToStop(
3120 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003121 RestoreProcessEvents();
3122
3123 if (state == eStateInvalid || !event_sp) {
3124 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003125 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003126 }
3127
3128 BroadcastEvent(event_sp);
3129
Zachary Turner97206d52017-05-12 04:51:55 +00003130 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003131}
3132
Zachary Turner97206d52017-05-12 04:51:55 +00003133Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3134 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003135
3136 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003137 // expression, for instance, then the public state will be stopped, but we
3138 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 if (m_public_state.GetValue() == eStateRunning ||
3140 m_private_state.GetValue() == eStateRunning) {
3141 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003142 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003143
Kate Stoneb9c1b512016-09-06 20:57:50 +00003144 ListenerSP listener_sp(
3145 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3146 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003147
Pavel Labath19da1f12015-12-07 12:36:52 +00003148 SendAsyncInterrupt();
3149
Kate Stoneb9c1b512016-09-06 20:57:50 +00003150 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003151 StateType state =
3152 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003153
Pavel Labath19da1f12015-12-07 12:36:52 +00003154 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003155
Kate Stoneb9c1b512016-09-06 20:57:50 +00003156 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003157 // exited event into the shared pointer passed in and return. Our caller
3158 // doesn't need to do anything else, since they don't have a process
3159 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003160
3161 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003162 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3163 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003164 return error;
3165 } else
3166 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3167
3168 if (state != eStateStopped) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003169 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3170 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003171 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003172 // here, but if the lower levels just bobbled sending the event and we
3173 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003174 StateType private_state = m_private_state.GetValue();
3175 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003176 return Status(
3177 "Attempt to stop the target in order to detach timed out. "
3178 "State = %s",
3179 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003180 }
3181 }
3182 }
3183 return error;
3184}
3185
Zachary Turner97206d52017-05-12 04:51:55 +00003186Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003187 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003188 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003189 m_destroy_in_process = true;
3190
3191 error = WillDetach();
3192
3193 if (error.Success()) {
3194 if (DetachRequiresHalt()) {
3195 error = StopForDestroyOrDetach(exit_event_sp);
3196 if (!error.Success()) {
3197 m_destroy_in_process = false;
3198 return error;
3199 } else if (exit_event_sp) {
3200 // We shouldn't need to do anything else here. There's no process left
3201 // to detach from...
3202 StopPrivateStateThread();
3203 m_destroy_in_process = false;
3204 return error;
3205 }
3206 }
3207
3208 m_thread_list.DiscardThreadPlans();
3209 DisableAllBreakpointSites();
3210
3211 error = DoDetach(keep_stopped);
3212 if (error.Success()) {
3213 DidDetach();
3214 StopPrivateStateThread();
3215 } else {
3216 return error;
3217 }
3218 }
3219 m_destroy_in_process = false;
3220
Adrian Prantl05097242018-04-30 16:49:04 +00003221 // If we exited when we were waiting for a process to stop, then forward the
3222 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003223 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003224 // Directly broadcast our exited event because we shut down our private
3225 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003226 BroadcastEvent(exit_event_sp);
3227 }
3228
3229 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003230 // not end up propagating the last events through the event system, in which
3231 // case we might strand the write lock. Unlock it here so when we do to tear
3232 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003233
3234 m_public_run_lock.SetStopped();
3235 return error;
3236}
3237
Zachary Turner97206d52017-05-12 04:51:55 +00003238Status Process::Destroy(bool force_kill) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003239
3240 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003241 // don't do any unnecessary work that might hinder the destruction. Remember
3242 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003243 // failed and the process stays around for some reason it won't be in a
3244 // confused state.
3245
3246 if (force_kill)
3247 m_should_detach = false;
3248
3249 if (GetShouldDetach()) {
3250 // FIXME: This will have to be a process setting:
3251 bool keep_stopped = false;
3252 Detach(keep_stopped);
3253 }
3254
3255 m_destroy_in_process = true;
3256
Zachary Turner97206d52017-05-12 04:51:55 +00003257 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003258 if (error.Success()) {
3259 EventSP exit_event_sp;
3260 if (DestroyRequiresHalt()) {
3261 error = StopForDestroyOrDetach(exit_event_sp);
3262 }
3263
3264 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003265 // Ditch all thread plans, and remove all our breakpoints: in case we
3266 // have to restart the target to kill it, we don't want it hitting a
3267 // breakpoint... Only do this if we've stopped, however, since if we
3268 // didn't manage to halt it above, then we're not going to have much luck
3269 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003270 m_thread_list.DiscardThreadPlans();
3271 DisableAllBreakpointSites();
3272 }
3273
3274 error = DoDestroy();
3275 if (error.Success()) {
3276 DidDestroy();
3277 StopPrivateStateThread();
3278 }
3279 m_stdio_communication.Disconnect();
3280 m_stdio_communication.StopReadThread();
3281 m_stdin_forward = false;
3282
3283 if (m_process_input_reader) {
3284 m_process_input_reader->SetIsDone(true);
3285 m_process_input_reader->Cancel();
3286 m_process_input_reader.reset();
3287 }
3288
Adrian Prantl05097242018-04-30 16:49:04 +00003289 // If we exited when we were waiting for a process to stop, then forward
3290 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003291 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003292 // Directly broadcast our exited event because we shut down our private
3293 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003294 BroadcastEvent(exit_event_sp);
3295 }
3296
Adrian Prantl05097242018-04-30 16:49:04 +00003297 // If we have been interrupted (to kill us) in the middle of running, we
3298 // may not end up propagating the last events through the event system, in
3299 // which case we might strand the write lock. Unlock it here so when we do
3300 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003301 m_public_run_lock.SetStopped();
3302 }
3303
3304 m_destroy_in_process = false;
3305
3306 return error;
3307}
3308
Zachary Turner97206d52017-05-12 04:51:55 +00003309Status Process::Signal(int signal) {
3310 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003311 if (error.Success()) {
3312 error = DoSignal(signal);
3313 if (error.Success())
3314 DidSignal();
3315 }
3316 return error;
3317}
3318
3319void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3320 assert(signals_sp && "null signals_sp");
3321 m_unix_signals_sp = signals_sp;
3322}
3323
3324const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3325 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3326 return m_unix_signals_sp;
3327}
3328
3329lldb::ByteOrder Process::GetByteOrder() const {
3330 return GetTarget().GetArchitecture().GetByteOrder();
3331}
3332
3333uint32_t Process::GetAddressByteSize() const {
3334 return GetTarget().GetArchitecture().GetAddressByteSize();
3335}
3336
3337bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3338 const StateType state =
3339 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3340 bool return_value = true;
3341 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3342 LIBLLDB_LOG_PROCESS));
3343
3344 switch (state) {
3345 case eStateDetached:
3346 case eStateExited:
3347 case eStateUnloaded:
3348 m_stdio_communication.SynchronizeWithReadThread();
3349 m_stdio_communication.Disconnect();
3350 m_stdio_communication.StopReadThread();
3351 m_stdin_forward = false;
3352
3353 LLVM_FALLTHROUGH;
3354 case eStateConnected:
3355 case eStateAttaching:
3356 case eStateLaunching:
3357 // These events indicate changes in the state of the debugging session,
3358 // always report them.
3359 return_value = true;
3360 break;
3361 case eStateInvalid:
3362 // We stopped for no apparent reason, don't report it.
3363 return_value = false;
3364 break;
3365 case eStateRunning:
3366 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003367 // If we've started the target running, we handle the cases where we are
3368 // already running and where there is a transition from stopped to running
3369 // differently. running -> running: Automatically suppress extra running
3370 // events stopped -> running: Report except when there is one or more no
3371 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003372 // and no yes votes.
3373 SynchronouslyNotifyStateChanged(state);
3374 if (m_force_next_event_delivery)
3375 return_value = true;
3376 else {
3377 switch (m_last_broadcast_state) {
3378 case eStateRunning:
3379 case eStateStepping:
3380 // We always suppress multiple runnings with no PUBLIC stop in between.
3381 return_value = false;
3382 break;
3383 default:
3384 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003385 // run if we aren't running so we don't miss any running events. If I
3386 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3387 // and hit the breakpoints on multiple threads, then somehow during the
3388 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003389
3390 // This is a transition from stop to run.
3391 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3392 case eVoteYes:
3393 case eVoteNoOpinion:
3394 return_value = true;
3395 break;
3396 case eVoteNo:
3397 return_value = false;
3398 break;
3399 }
3400 break;
3401 }
3402 }
3403 break;
3404 case eStateStopped:
3405 case eStateCrashed:
3406 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003407 // We've stopped. First see if we're going to restart the target. If we
3408 // are going to stop, then we always broadcast the event. If we aren't
3409 // going to stop, let the thread plans decide if we're going to report this
3410 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003411
3412 m_stdio_communication.SynchronizeWithReadThread();
3413 RefreshStateAfterStop();
3414 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003415 LLDB_LOGF(log,
3416 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3417 "interrupt, state: %s",
3418 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003419 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003420 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003421 m_thread_list.ShouldStop(event_ptr);
3422 return_value = true;
3423 } else {
3424 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3425 bool should_resume = false;
3426
3427 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003428 // restarted... Asking the thread list is also not likely to go well,
3429 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003430
3431 if (!was_restarted)
3432 should_resume = !m_thread_list.ShouldStop(event_ptr);
3433
3434 if (was_restarted || should_resume || m_resume_requested) {
3435 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003436 LLDB_LOGF(log,
3437 "Process::ShouldBroadcastEvent: should_resume: %i state: "
3438 "%s was_restarted: %i stop_vote: %d.",
3439 should_resume, StateAsCString(state), was_restarted,
3440 stop_vote);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003441
3442 switch (stop_vote) {
3443 case eVoteYes:
3444 return_value = true;
3445 break;
3446 case eVoteNoOpinion:
3447 case eVoteNo:
3448 return_value = false;
3449 break;
3450 }
3451
3452 if (!was_restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003453 LLDB_LOGF(log,
3454 "Process::ShouldBroadcastEvent (%p) Restarting process "
3455 "from state: %s",
3456 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003457 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3458 PrivateResume();
3459 }
3460 } else {
3461 return_value = true;
3462 SynchronouslyNotifyStateChanged(state);
3463 }
3464 }
3465 break;
3466 }
3467
3468 // Forcing the next event delivery is a one shot deal. So reset it here.
3469 m_force_next_event_delivery = false;
3470
3471 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003472 // events get coalesced.) But we only coalesce against events we actually
3473 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3474 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3475 // done, because the PublicState reflects the last event pulled off the
3476 // queue, and there may be several events stacked up on the queue unserviced.
3477 // So the PublicState may not reflect the last broadcasted event yet.
3478 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003479
3480 if (return_value)
3481 m_last_broadcast_state = state;
3482
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003483 LLDB_LOGF(log,
3484 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3485 "broadcast state: %s - %s",
3486 static_cast<void *>(event_ptr), StateAsCString(state),
3487 StateAsCString(m_last_broadcast_state),
3488 return_value ? "YES" : "NO");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003489 return return_value;
3490}
3491
3492bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3493 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3494
3495 bool already_running = PrivateStateThreadIsValid();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003496 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
3497 already_running ? " already running"
3498 : " starting private state thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003499
3500 if (!is_secondary_thread && already_running)
3501 return true;
3502
Adrian Prantl05097242018-04-30 16:49:04 +00003503 // Create a thread that watches our internal state and controls which events
3504 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003505 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003506 uint32_t max_len = llvm::get_max_thread_name_length();
3507 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003508 // On platforms with abbreviated thread name lengths, choose thread names
3509 // that fit within the limit.
3510 if (already_running)
3511 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3512 else
3513 snprintf(thread_name, sizeof(thread_name), "intern-state");
3514 } else {
3515 if (already_running)
3516 snprintf(thread_name, sizeof(thread_name),
3517 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3518 GetID());
3519 else
3520 snprintf(thread_name, sizeof(thread_name),
3521 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3522 }
3523
3524 // Create the private state thread, and start it running.
3525 PrivateStateThreadArgs *args_ptr =
3526 new PrivateStateThreadArgs(this, is_secondary_thread);
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003527 llvm::Expected<HostThread> private_state_thread =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003528 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003529 (void *)args_ptr, 8 * 1024 * 1024);
3530 if (!private_state_thread) {
3531 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3532 "failed to launch host thread: {}",
3533 llvm::toString(private_state_thread.takeError()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003534 return false;
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003535 }
3536
3537 assert(private_state_thread->IsJoinable());
3538 m_private_state_thread = *private_state_thread;
3539 ResumePrivateStateThread();
3540 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003541}
3542
3543void Process::PausePrivateStateThread() {
3544 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3545}
3546
3547void Process::ResumePrivateStateThread() {
3548 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3549}
3550
3551void Process::StopPrivateStateThread() {
3552 if (m_private_state_thread.IsJoinable())
3553 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3554 else {
3555 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003556 LLDB_LOGF(
3557 log,
3558 "Went to stop the private state thread, but it was already invalid.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003559 }
3560}
3561
3562void Process::ControlPrivateStateThread(uint32_t signal) {
3563 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3564
3565 assert(signal == eBroadcastInternalStateControlStop ||
3566 signal == eBroadcastInternalStateControlPause ||
3567 signal == eBroadcastInternalStateControlResume);
3568
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003569 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003570
3571 // Signal the private state thread
3572 if (m_private_state_thread.IsJoinable()) {
3573 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003574 // It is important to do this outside of the if below, because it's
3575 // possible that the thread state is invalid but that the thread is waiting
3576 // on a control event instead of simply being on its way out (this should
3577 // not happen, but it apparently can).
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003578 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003579 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3580 m_private_state_control_broadcaster.BroadcastEvent(signal,
3581 event_receipt_sp);
3582
3583 // Wait for the event receipt or for the private state thread to exit
3584 bool receipt_received = false;
3585 if (PrivateStateThreadIsValid()) {
3586 while (!receipt_received) {
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003587 // Check for a receipt for n seconds and then check if the private
Adrian Prantl05097242018-04-30 16:49:04 +00003588 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003589 receipt_received =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003590 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003591 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003592 // Check if the private state thread is still around. If it isn't
3593 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003594 if (!PrivateStateThreadIsValid())
3595 break; // Private state thread exited or is exiting, we are done
3596 }
3597 }
3598 }
3599
3600 if (signal == eBroadcastInternalStateControlStop) {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003601 thread_result_t result = {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003602 m_private_state_thread.Join(&result);
3603 m_private_state_thread.Reset();
3604 }
3605 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003606 LLDB_LOGF(
3607 log,
3608 "Private state thread already dead, no need to signal it to stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003609 }
3610}
3611
3612void Process::SendAsyncInterrupt() {
3613 if (PrivateStateThreadIsValid())
3614 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3615 nullptr);
3616 else
3617 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3618}
3619
3620void Process::HandlePrivateEvent(EventSP &event_sp) {
3621 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3622 m_resume_requested = false;
3623
3624 const StateType new_state =
3625 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3626
3627 // First check to see if anybody wants a shot at this event:
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003628 if (m_next_event_action_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003629 NextEventAction::EventActionResult action_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003630 m_next_event_action_up->PerformAction(event_sp);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003631 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003632
3633 switch (action_result) {
3634 case NextEventAction::eEventActionSuccess:
3635 SetNextEventAction(nullptr);
3636 break;
3637
3638 case NextEventAction::eEventActionRetry:
3639 break;
3640
3641 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003642 // Handle Exiting Here. If we already got an exited event, we should
3643 // just propagate it. Otherwise, swallow this event, and set our state
3644 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003645 if (new_state != eStateExited) {
3646 // FIXME: should cons up an exited event, and discard this one.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003647 SetExitStatus(0, m_next_event_action_up->GetExitString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003648 SetNextEventAction(nullptr);
3649 return;
3650 }
3651 SetNextEventAction(nullptr);
3652 break;
3653 }
3654 }
3655
3656 // See if we should broadcast this state to external clients?
3657 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3658
3659 if (should_broadcast) {
3660 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3661 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003662 LLDB_LOGF(log,
3663 "Process::%s (pid = %" PRIu64
3664 ") broadcasting new state %s (old state %s) to %s",
3665 __FUNCTION__, GetID(), StateAsCString(new_state),
3666 StateAsCString(GetState()),
3667 is_hijacked ? "hijacked" : "public");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003668 }
3669 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3670 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003671 // Only push the input handler if we aren't fowarding events, as this
3672 // means the curses GUI is in use... Or don't push it if we are launching
3673 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003674 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3675 new_state != eStateLaunching && new_state != eStateAttaching) {
3676 PushProcessIOHandler();
3677 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3678 eBroadcastAlways);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003679 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
3680 __FUNCTION__, m_iohandler_sync.GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003681 }
3682 } else if (StateIsStoppedState(new_state, false)) {
3683 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003684 // If the lldb_private::Debugger is handling the events, we don't want
3685 // to pop the process IOHandler here, we want to do it when we receive
3686 // the stopped event so we can carefully control when the process
3687 // IOHandler is popped because when we stop we want to display some
3688 // text stating how and why we stopped, then maybe some
3689 // process/thread/frame info, and then we want the "(lldb) " prompt to
3690 // show up. If we pop the process IOHandler here, then we will cause
3691 // the command interpreter to become the top IOHandler after the
3692 // process pops off and it will update its prompt right away... See the
3693 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003694 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3695 // Otherwise we end up getting overlapping "(lldb) " prompts and
3696 // garbled output.
3697 //
3698 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003699 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3700 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003701 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003702 // thread plans, or when commands want to run in synchronous mode and
3703 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003704 // that will hijack the events is a simple expression:
3705 //
3706 // (lldb) expr (int)puts("hello")
3707 //
3708 // This will cause the internal process state thread to resume and halt
3709 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3710 // events) and we do need the IO handler to be pushed and popped
3711 // correctly.
3712
3713 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3714 PopProcessIOHandler();
3715 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003716 }
3717
3718 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003719 } else {
3720 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003721 LLDB_LOGF(
3722 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003723 "Process::%s (pid = %" PRIu64
3724 ") suppressing state %s (old state %s): should_broadcast == false",
3725 __FUNCTION__, GetID(), StateAsCString(new_state),
3726 StateAsCString(GetState()));
3727 }
3728 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003729}
3730
Zachary Turner97206d52017-05-12 04:51:55 +00003731Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003732 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003733 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003734 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003735 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003736
3737 // Ask the process subclass to actually halt our process
3738 bool caused_stop;
3739 error = DoHalt(caused_stop);
3740
3741 DidHalt();
3742 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003743}
3744
Kate Stoneb9c1b512016-09-06 20:57:50 +00003745thread_result_t Process::PrivateStateThread(void *arg) {
3746 std::unique_ptr<PrivateStateThreadArgs> args_up(
3747 static_cast<PrivateStateThreadArgs *>(arg));
3748 thread_result_t result =
3749 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3750 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003751}
3752
Kate Stoneb9c1b512016-09-06 20:57:50 +00003753thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3754 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003755
Kate Stoneb9c1b512016-09-06 20:57:50 +00003756 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003757 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3758 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003759
Kate Stoneb9c1b512016-09-06 20:57:50 +00003760 bool exit_now = false;
3761 bool interrupt_requested = false;
3762 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003763 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003764 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003765 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003766 LLDB_LOGF(log,
3767 "Process::%s (arg = %p, pid = %" PRIu64
3768 ") got a control event: %d",
3769 __FUNCTION__, static_cast<void *>(this), GetID(),
3770 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003771
Kate Stoneb9c1b512016-09-06 20:57:50 +00003772 switch (event_sp->GetType()) {
3773 case eBroadcastInternalStateControlStop:
3774 exit_now = true;
3775 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003776
Kate Stoneb9c1b512016-09-06 20:57:50 +00003777 case eBroadcastInternalStateControlPause:
3778 control_only = true;
3779 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003780
Kate Stoneb9c1b512016-09-06 20:57:50 +00003781 case eBroadcastInternalStateControlResume:
3782 control_only = false;
3783 break;
3784 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003785
Kate Stoneb9c1b512016-09-06 20:57:50 +00003786 continue;
3787 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3788 if (m_public_state.GetValue() == eStateAttaching) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003789 LLDB_LOGF(log,
3790 "Process::%s (arg = %p, pid = %" PRIu64
3791 ") woke up with an interrupt while attaching - "
3792 "forwarding interrupt.",
3793 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003794 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3795 } else if (StateIsRunningState(m_last_broadcast_state)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003796 LLDB_LOGF(log,
3797 "Process::%s (arg = %p, pid = %" PRIu64
3798 ") woke up with an interrupt - Halting.",
3799 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00003800 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003801 if (error.Fail() && log)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003802 LLDB_LOGF(log,
3803 "Process::%s (arg = %p, pid = %" PRIu64
3804 ") failed to halt the process: %s",
3805 __FUNCTION__, static_cast<void *>(this), GetID(),
3806 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00003807 // Halt should generate a stopped event. Make a note of the fact that
3808 // we were doing the interrupt, so we can set the interrupted flag
3809 // after we receive the event. We deliberately set this to true even if
3810 // HaltPrivate failed, so that we can interrupt on the next natural
3811 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003812 interrupt_requested = true;
3813 } else {
3814 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00003815 // running and sends an interrupt request, but the process actually
3816 // stops before we receive it. In that case, we can just ignore the
3817 // request. We use m_last_broadcast_state, because the Stopped event
3818 // may not have been popped of the event queue yet, which is when the
3819 // public state gets updated.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003820 LLDB_LOGF(log,
3821 "Process::%s ignoring interrupt as we have already stopped.",
3822 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003823 }
3824 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003825 }
3826
Kate Stoneb9c1b512016-09-06 20:57:50 +00003827 const StateType internal_state =
3828 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003829
Kate Stoneb9c1b512016-09-06 20:57:50 +00003830 if (internal_state != eStateInvalid) {
3831 if (m_clear_thread_plans_on_stop &&
3832 StateIsStoppedState(internal_state, true)) {
3833 m_clear_thread_plans_on_stop = false;
3834 m_thread_list.DiscardThreadPlans();
3835 }
3836
3837 if (interrupt_requested) {
3838 if (StateIsStoppedState(internal_state, true)) {
3839 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00003840 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00003841 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3842 interrupt_requested = false;
3843 } else if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003844 LLDB_LOGF(log,
3845 "Process::%s interrupt_requested, but a non-stopped "
3846 "state '%s' received.",
3847 __FUNCTION__, StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003848 }
3849 }
3850
3851 HandlePrivateEvent(event_sp);
3852 }
3853
3854 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3855 internal_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003856 LLDB_LOGF(log,
3857 "Process::%s (arg = %p, pid = %" PRIu64
3858 ") about to exit with internal state %s...",
3859 __FUNCTION__, static_cast<void *>(this), GetID(),
3860 StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003861
3862 break;
3863 }
3864 }
3865
3866 // Verify log is still enabled before attempting to write to it...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003867 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3868 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003869
3870 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00003871 // will have already acquired the public_run_lock, and isn't done with what
3872 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003873 if (!is_secondary_thread)
3874 m_public_run_lock.SetStopped();
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003875 return {};
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003876}
3877
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003878// Process Event Data
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003879
Kate Stoneb9c1b512016-09-06 20:57:50 +00003880Process::ProcessEventData::ProcessEventData()
3881 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3882 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003883
Kate Stoneb9c1b512016-09-06 20:57:50 +00003884Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3885 StateType state)
3886 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3887 m_update_state(0), m_interrupted(false) {
3888 if (process_sp)
3889 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003890}
3891
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003892Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003893
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003894ConstString Process::ProcessEventData::GetFlavorString() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003895 static ConstString g_flavor("Process::ProcessEventData");
3896 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003897}
3898
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003899ConstString Process::ProcessEventData::GetFlavor() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003900 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003901}
3902
Kate Stoneb9c1b512016-09-06 20:57:50 +00003903void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
3904 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00003905
Kate Stoneb9c1b512016-09-06 20:57:50 +00003906 if (!process_sp)
3907 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003908
Kate Stoneb9c1b512016-09-06 20:57:50 +00003909 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00003910 // pulled off of the private process event queue, and then any number of
3911 // times, first when it gets pulled off of the public event queue, then other
3912 // times when we're pretending that this is where we stopped at the end of
3913 // expression evaluation. m_update_state is used to distinguish these three
3914 // cases; it is 0 when we're just pulling it off for private handling, and >
3915 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00003916 // command handling then.
3917 if (m_update_state != 1)
3918 return;
3919
3920 process_sp->SetPublicState(
3921 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
3922
Jason Molendab3a3cd12016-12-08 06:27:29 +00003923 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00003924 // Let process subclasses know we are about to do a public stop and do
3925 // anything they might need to in order to speed up register and memory
3926 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00003927 process_sp->WillPublicStop();
3928 }
3929
Kate Stoneb9c1b512016-09-06 20:57:50 +00003930 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00003931 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
3932 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00003933 // end up restarting the process.
3934 if (m_interrupted)
3935 return;
3936
3937 // If we're stopped and haven't restarted, then do the StopInfo actions here:
3938 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003939 ThreadList &curr_thread_list = process_sp->GetThreadList();
3940 uint32_t num_threads = curr_thread_list.GetSize();
3941 uint32_t idx;
3942
3943 // The actions might change one of the thread's stop_info's opinions about
Adrian Prantl05097242018-04-30 16:49:04 +00003944 // whether we should stop the process, so we need to query that as we go.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003945
3946 // One other complication here, is that we try to catch any case where the
Adrian Prantl05097242018-04-30 16:49:04 +00003947 // target has run (except for expressions) and immediately exit, but if we
3948 // get that wrong (which is possible) then the thread list might have
3949 // changed, and that would cause our iteration here to crash. We could
3950 // make a copy of the thread list, but we'd really like to also know if it
3951 // has changed at all, so we make up a vector of the thread ID's and check
3952 // what we get back against this list & bag out if anything differs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003953 std::vector<uint32_t> thread_index_array(num_threads);
3954 for (idx = 0; idx < num_threads; ++idx)
3955 thread_index_array[idx] =
3956 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3957
3958 // Use this to track whether we should continue from here. We will only
Adrian Prantl05097242018-04-30 16:49:04 +00003959 // continue the target running if no thread says we should stop. Of course
3960 // if some thread's PerformAction actually sets the target running, then it
3961 // doesn't matter what the other threads say...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003962
3963 bool still_should_stop = false;
3964
3965 // Sometimes - for instance if we have a bug in the stub we are talking to,
Adrian Prantl05097242018-04-30 16:49:04 +00003966 // we stop but no thread has a valid stop reason. In that case we should
3967 // just stop, because we have no way of telling what the right thing to do
3968 // is, and it's better to let the user decide than continue behind their
3969 // backs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003970
3971 bool does_anybody_have_an_opinion = false;
3972
3973 for (idx = 0; idx < num_threads; ++idx) {
3974 curr_thread_list = process_sp->GetThreadList();
3975 if (curr_thread_list.GetSize() != num_threads) {
3976 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
3977 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003978 LLDB_LOGF(
3979 log,
3980 "Number of threads changed from %u to %u while processing event.",
3981 num_threads, curr_thread_list.GetSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003982 break;
3983 }
3984
3985 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3986
3987 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
3988 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
3989 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003990 LLDB_LOGF(log,
3991 "The thread at position %u changed from %u to %u while "
3992 "processing event.",
3993 idx, thread_index_array[idx], thread_sp->GetIndexID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003994 break;
3995 }
3996
3997 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
3998 if (stop_info_sp && stop_info_sp->IsValid()) {
3999 does_anybody_have_an_opinion = true;
4000 bool this_thread_wants_to_stop;
4001 if (stop_info_sp->GetOverrideShouldStop()) {
4002 this_thread_wants_to_stop =
4003 stop_info_sp->GetOverriddenShouldStopValue();
4004 } else {
4005 stop_info_sp->PerformAction(event_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +00004006 // The stop action might restart the target. If it does, then we
4007 // want to mark that in the event so that whoever is receiving it
4008 // will know to wait for the running event and reflect that state
4009 // appropriately. We also need to stop processing actions, since they
4010 // aren't expecting the target to be running.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004011
4012 // FIXME: we might have run.
4013 if (stop_info_sp->HasTargetRunSinceMe()) {
4014 SetRestarted(true);
4015 break;
4016 }
4017
4018 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004019 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004020
4021 if (!still_should_stop)
4022 still_should_stop = this_thread_wants_to_stop;
4023 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004024 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004025
4026 if (!GetRestarted()) {
4027 if (!still_should_stop && does_anybody_have_an_opinion) {
4028 // We've been asked to continue, so do that here.
4029 SetRestarted(true);
Adrian Prantl05097242018-04-30 16:49:04 +00004030 // Use the public resume method here, since this is just extending a
4031 // public resume.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004032 process_sp->PrivateResume();
4033 } else {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004034 bool hijacked =
4035 process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4036 !process_sp->StateChangedIsHijackedForSynchronousResume();
Jim Ingham3139fc92019-03-01 18:13:38 +00004037
4038 if (!hijacked) {
4039 // If we didn't restart, run the Stop Hooks here.
4040 // Don't do that if state changed events aren't hooked up to the
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004041 // public (or SyncResume) broadcasters. StopHooks are just for
4042 // real public stops. They might also restart the target,
Jim Ingham3139fc92019-03-01 18:13:38 +00004043 // so watch for that.
4044 process_sp->GetTarget().RunStopHooks();
4045 if (process_sp->GetPrivateState() == eStateRunning)
4046 SetRestarted(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004047 }
4048 }
4049 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004050}
Zachary Turner805e7102019-03-04 21:51:03 +00004051}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004052
Kate Stoneb9c1b512016-09-06 20:57:50 +00004053void Process::ProcessEventData::Dump(Stream *s) const {
4054 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004055
Kate Stoneb9c1b512016-09-06 20:57:50 +00004056 if (process_sp)
4057 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4058 static_cast<void *>(process_sp.get()), process_sp->GetID());
4059 else
4060 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004061
Kate Stoneb9c1b512016-09-06 20:57:50 +00004062 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004063}
4064
4065const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004066Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4067 if (event_ptr) {
4068 const EventData *event_data = event_ptr->GetData();
4069 if (event_data &&
4070 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4071 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4072 }
4073 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004074}
4075
4076ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004077Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4078 ProcessSP process_sp;
4079 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4080 if (data)
4081 process_sp = data->GetProcessSP();
4082 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004083}
4084
Kate Stoneb9c1b512016-09-06 20:57:50 +00004085StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4086 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4087 if (data == nullptr)
4088 return eStateInvalid;
4089 else
4090 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004091}
4092
Kate Stoneb9c1b512016-09-06 20:57:50 +00004093bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4094 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4095 if (data == nullptr)
4096 return false;
4097 else
4098 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004099}
4100
Kate Stoneb9c1b512016-09-06 20:57:50 +00004101void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4102 bool new_value) {
4103 ProcessEventData *data =
4104 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4105 if (data != nullptr)
4106 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004107}
4108
Jim Ingham0161b492013-02-09 01:29:05 +00004109size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004110Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4111 ProcessEventData *data =
4112 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4113 if (data != nullptr)
4114 return data->GetNumRestartedReasons();
4115 else
4116 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004117}
4118
4119const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004120Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4121 size_t idx) {
4122 ProcessEventData *data =
4123 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4124 if (data != nullptr)
4125 return data->GetRestartedReasonAtIndex(idx);
4126 else
4127 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004128}
4129
Kate Stoneb9c1b512016-09-06 20:57:50 +00004130void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4131 const char *reason) {
4132 ProcessEventData *data =
4133 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4134 if (data != nullptr)
4135 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004136}
4137
Kate Stoneb9c1b512016-09-06 20:57:50 +00004138bool Process::ProcessEventData::GetInterruptedFromEvent(
4139 const Event *event_ptr) {
4140 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4141 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004142 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004143 else
4144 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004145}
4146
Kate Stoneb9c1b512016-09-06 20:57:50 +00004147void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4148 bool new_value) {
4149 ProcessEventData *data =
4150 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4151 if (data != nullptr)
4152 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004153}
4154
Kate Stoneb9c1b512016-09-06 20:57:50 +00004155bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4156 ProcessEventData *data =
4157 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4158 if (data) {
4159 data->SetUpdateStateOnRemoval();
4160 return true;
4161 }
4162 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004163}
4164
Jim Inghamb87b9e62018-06-26 23:38:58 +00004165lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004166
4167void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4168 exe_ctx.SetTargetPtr(&GetTarget());
4169 exe_ctx.SetProcessPtr(this);
4170 exe_ctx.SetThreadPtr(nullptr);
4171 exe_ctx.SetFramePtr(nullptr);
4172}
4173
4174// uint32_t
4175// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4176// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004177//{
4178// return 0;
4179//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004180//
4181// ArchSpec
4182// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004183//{
4184// return Host::GetArchSpecForExistingProcess (pid);
4185//}
4186//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004187// ArchSpec
4188// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004189//{
4190// return Host::GetArchSpecForExistingProcess (process_name);
4191//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004192
Kate Stoneb9c1b512016-09-06 20:57:50 +00004193void Process::AppendSTDOUT(const char *s, size_t len) {
4194 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4195 m_stdout_data.append(s, len);
4196 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4197 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004198}
4199
Kate Stoneb9c1b512016-09-06 20:57:50 +00004200void Process::AppendSTDERR(const char *s, size_t len) {
4201 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4202 m_stderr_data.append(s, len);
4203 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4204 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004205}
4206
Kate Stoneb9c1b512016-09-06 20:57:50 +00004207void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4208 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4209 m_profile_data.push_back(one_profile_data);
4210 BroadcastEventIfUnique(eBroadcastBitProfileData,
4211 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004212}
4213
Kate Stoneb9c1b512016-09-06 20:57:50 +00004214void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4215 const StructuredDataPluginSP &plugin_sp) {
4216 BroadcastEvent(
4217 eBroadcastBitStructuredData,
4218 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004219}
4220
4221StructuredDataPluginSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004222Process::GetStructuredDataPlugin(ConstString type_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004223 auto find_it = m_structured_data_plugin_map.find(type_name);
4224 if (find_it != m_structured_data_plugin_map.end())
4225 return find_it->second;
4226 else
4227 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004228}
4229
Zachary Turner97206d52017-05-12 04:51:55 +00004230size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004231 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4232 if (m_profile_data.empty())
4233 return 0;
4234
4235 std::string &one_profile_data = m_profile_data.front();
4236 size_t bytes_available = one_profile_data.size();
4237 if (bytes_available > 0) {
4238 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004239 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4240 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004241 if (bytes_available > buf_size) {
4242 memcpy(buf, one_profile_data.c_str(), buf_size);
4243 one_profile_data.erase(0, buf_size);
4244 bytes_available = buf_size;
4245 } else {
4246 memcpy(buf, one_profile_data.c_str(), bytes_available);
4247 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004248 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004249 }
4250 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004251}
4252
Greg Clayton93e86192011-11-13 04:45:22 +00004253// Process STDIO
Greg Clayton93e86192011-11-13 04:45:22 +00004254
Zachary Turner97206d52017-05-12 04:51:55 +00004255size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004256 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4257 size_t bytes_available = m_stdout_data.size();
4258 if (bytes_available > 0) {
4259 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004260 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4261 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004262 if (bytes_available > buf_size) {
4263 memcpy(buf, m_stdout_data.c_str(), buf_size);
4264 m_stdout_data.erase(0, buf_size);
4265 bytes_available = buf_size;
4266 } else {
4267 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4268 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004269 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004270 }
4271 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004272}
4273
Zachary Turner97206d52017-05-12 04:51:55 +00004274size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004275 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4276 size_t bytes_available = m_stderr_data.size();
4277 if (bytes_available > 0) {
4278 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004279 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4280 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004281 if (bytes_available > buf_size) {
4282 memcpy(buf, m_stderr_data.c_str(), buf_size);
4283 m_stderr_data.erase(0, buf_size);
4284 bytes_available = buf_size;
4285 } else {
4286 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4287 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004288 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004289 }
4290 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004291}
4292
Kate Stoneb9c1b512016-09-06 20:57:50 +00004293void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4294 size_t src_len) {
4295 Process *process = (Process *)baton;
4296 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004297}
4298
Kate Stoneb9c1b512016-09-06 20:57:50 +00004299class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004300public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004301 IOHandlerProcessSTDIO(Process *process, int write_fd)
4302 : IOHandler(process->GetTarget().GetDebugger(),
4303 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004304 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004305 m_pipe.CreateNew(false);
4306 m_read_file.SetDescriptor(GetInputFD(), false);
4307 }
4308
4309 ~IOHandlerProcessSTDIO() override = default;
4310
Adrian Prantl05097242018-04-30 16:49:04 +00004311 // Each IOHandler gets to run until it is done. It should read data from the
4312 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004313 void Run() override {
4314 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4315 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4316 SetIsDone(true);
4317 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004318 }
4319
Kate Stoneb9c1b512016-09-06 20:57:50 +00004320 SetIsDone(false);
4321 const int read_fd = m_read_file.GetDescriptor();
4322 TerminalState terminal_state;
4323 terminal_state.Save(read_fd, false);
4324 Terminal terminal(read_fd);
4325 terminal.SetCanonical(false);
4326 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004327// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004328#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004329 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4330 m_is_running = true;
4331 while (!GetIsDone()) {
4332 SelectHelper select_helper;
4333 select_helper.FDSetRead(read_fd);
4334 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004335 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004336
Kate Stoneb9c1b512016-09-06 20:57:50 +00004337 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004338 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004339 } else {
4340 char ch = 0;
4341 size_t n;
4342 if (select_helper.FDIsSetRead(read_fd)) {
4343 n = 1;
4344 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4345 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4346 SetIsDone(true);
4347 } else
4348 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004349 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004350 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4351 size_t bytes_read;
4352 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004353 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004354 if (error.Success()) {
4355 switch (ch) {
4356 case 'q':
4357 SetIsDone(true);
4358 break;
4359 case 'i':
4360 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004361 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004362 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004363 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004364 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004365 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004366 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004367 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004368 m_is_running = false;
4369#endif
4370 terminal_state.Restore();
4371 }
4372
4373 void Cancel() override {
4374 SetIsDone(true);
4375 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004376 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4377 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004378 //
4379 // (lldb) step_process_thousands_of_times
4380 //
4381 // In this case the command interpreter will be in the middle of handling
4382 // the command and if the process pushes and pops the IOHandler thousands
4383 // of times, we can end up writing to m_pipe without ever consuming the
4384 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4385 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4386 if (m_is_running) {
4387 char ch = 'q'; // Send 'q' for quit
4388 size_t bytes_written = 0;
4389 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004390 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004391 }
4392
4393 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004394 // Do only things that are safe to do in an interrupt context (like in a
4395 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004396 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4397 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004398 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004399 if (m_active) {
4400 char ch = 'i'; // Send 'i' for interrupt
4401 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004402 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004403 return result.Success();
4404 } else {
4405 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004406 // currently so do the right thing if we aren't actively watching for
4407 // STDIN by sending the interrupt to the process. Otherwise the write to
4408 // the pipe above would do nothing. This can happen when the command
4409 // interpreter is running and gets a "expression ...". It will be on the
4410 // IOHandler thread and sending the input is complete to the delegate
4411 // which will cause the expression to run, which will push the process IO
4412 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004413
4414 if (StateIsRunningState(m_process->GetState())) {
4415 m_process->SendAsyncInterrupt();
4416 return true;
4417 }
4418 }
4419 return false;
4420 }
4421
4422 void GotEOF() override {}
4423
Greg Clayton44d93782014-01-27 23:43:24 +00004424protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004425 Process *m_process;
4426 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4427 File m_write_file; // Write to this file (usually the master pty for getting
4428 // io to debuggee)
4429 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004430 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004431};
4432
Kate Stoneb9c1b512016-09-06 20:57:50 +00004433void Process::SetSTDIOFileDescriptor(int fd) {
4434 // First set up the Read Thread for reading/handling process I/O
4435
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004436 std::unique_ptr<ConnectionFileDescriptor> conn_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004437 new ConnectionFileDescriptor(fd, true));
4438
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004439 if (conn_up) {
4440 m_stdio_communication.SetConnection(conn_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004441 if (m_stdio_communication.IsConnected()) {
4442 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4443 STDIOReadThreadBytesReceived, this);
4444 m_stdio_communication.StartReadThread();
4445
4446 // Now read thread is set up, set up input reader.
4447
4448 if (!m_process_input_reader)
Jonas Devlieghere796ac802019-02-11 23:13:08 +00004449 m_process_input_reader =
4450 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004451 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004452 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004453}
4454
Kate Stoneb9c1b512016-09-06 20:57:50 +00004455bool Process::ProcessIOHandlerIsActive() {
4456 IOHandlerSP io_handler_sp(m_process_input_reader);
4457 if (io_handler_sp)
4458 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4459 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004460}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004461bool Process::PushProcessIOHandler() {
4462 IOHandlerSP io_handler_sp(m_process_input_reader);
4463 if (io_handler_sp) {
4464 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004465 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004466
Kate Stoneb9c1b512016-09-06 20:57:50 +00004467 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004468 // If we evaluate an utility function, then we don't cancel the current
4469 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4470 // existing IOHandler that potentially provides the user interface (e.g.
4471 // the IOHandler for Editline).
4472 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4473 GetTarget().GetDebugger().PushIOHandler(io_handler_sp, cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004474 return true;
4475 }
4476 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004477}
4478
Kate Stoneb9c1b512016-09-06 20:57:50 +00004479bool Process::PopProcessIOHandler() {
4480 IOHandlerSP io_handler_sp(m_process_input_reader);
4481 if (io_handler_sp)
4482 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4483 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004484}
4485
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004486// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004487void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004488
Kate Stoneb9c1b512016-09-06 20:57:50 +00004489void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004490
Kate Stoneb9c1b512016-09-06 20:57:50 +00004491namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004492// RestorePlanState is used to record the "is private", "is master" and "okay
4493// to discard" fields of the plan we are running, and reset it on Clean or on
4494// destruction. It will only reset the state once, so you can call Clean and
4495// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004496
Kate Stoneb9c1b512016-09-06 20:57:50 +00004497class RestorePlanState {
4498public:
4499 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4500 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4501 if (m_thread_plan_sp) {
4502 m_private = m_thread_plan_sp->GetPrivate();
4503 m_is_master = m_thread_plan_sp->IsMasterPlan();
4504 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4505 }
4506 }
4507
4508 ~RestorePlanState() { Clean(); }
4509
4510 void Clean() {
4511 if (!m_already_reset && m_thread_plan_sp) {
4512 m_already_reset = true;
4513 m_thread_plan_sp->SetPrivate(m_private);
4514 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4515 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4516 }
4517 }
4518
4519private:
4520 lldb::ThreadPlanSP m_thread_plan_sp;
4521 bool m_already_reset;
4522 bool m_private;
4523 bool m_is_master;
4524 bool m_okay_to_discard;
4525};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004526} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004527
Pavel Labath2ce22162016-12-01 10:57:30 +00004528static microseconds
4529GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4530 const milliseconds default_one_thread_timeout(250);
4531
4532 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004533 if (!options.GetTimeout()) {
4534 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4535 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004536 }
4537
4538 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004539 if (options.GetOneThreadTimeout())
4540 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004541
4542 // Otherwise use half the total timeout, bounded by the
4543 // default_one_thread_timeout.
4544 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004545 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004546}
4547
4548static Timeout<std::micro>
4549GetExpressionTimeout(const EvaluateExpressionOptions &options,
4550 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004551 // If we are going to run all threads the whole time, or if we are only going
4552 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004553 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004554 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004555
4556 if (before_first_timeout)
4557 return GetOneThreadExpressionTimeout(options);
4558
Pavel Labath43d35412016-12-06 11:24:51 +00004559 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004560 return llvm::None;
4561 else
Pavel Labath43d35412016-12-06 11:24:51 +00004562 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004563}
4564
Pavel Labath45dde232017-05-25 10:50:06 +00004565static llvm::Optional<ExpressionResults>
4566HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4567 RestorePlanState &restorer, const EventSP &event_sp,
4568 EventSP &event_to_broadcast_sp,
4569 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4570 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4571
4572 ThreadPlanSP plan = thread.GetCompletedPlan();
4573 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4574 LLDB_LOG(log, "execution completed successfully");
4575
4576 // Restore the plan state so it will get reported as intended when we are
4577 // done.
4578 restorer.Clean();
4579 return eExpressionCompleted;
4580 }
4581
4582 StopInfoSP stop_info_sp = thread.GetStopInfo();
4583 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4584 stop_info_sp->ShouldNotify(event_sp.get())) {
4585 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4586 if (!options.DoesIgnoreBreakpoints()) {
4587 // Restore the plan state and then force Private to false. We are going
4588 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004589 // it won't report correctly when we continue to its termination later
4590 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004591 restorer.Clean();
4592 thread_plan_sp->SetPrivate(false);
4593 event_to_broadcast_sp = event_sp;
4594 }
4595 return eExpressionHitBreakpoint;
4596 }
4597
4598 if (!handle_interrupts &&
4599 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4600 return llvm::None;
4601
4602 LLDB_LOG(log, "thread plan did not successfully complete");
4603 if (!options.DoesUnwindOnError())
4604 event_to_broadcast_sp = event_sp;
4605 return eExpressionInterrupted;
4606}
4607
Jim Ingham1624a2d2014-05-05 02:26:40 +00004608ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004609Process::RunThreadPlan(ExecutionContext &exe_ctx,
4610 lldb::ThreadPlanSP &thread_plan_sp,
4611 const EvaluateExpressionOptions &options,
4612 DiagnosticManager &diagnostic_manager) {
4613 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004614
Kate Stoneb9c1b512016-09-06 20:57:50 +00004615 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4616
4617 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004618 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004619 eDiagnosticSeverityError,
4620 "RunThreadPlan called with empty thread plan.");
4621 return eExpressionSetupError;
4622 }
4623
4624 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004625 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004626 eDiagnosticSeverityError,
4627 "RunThreadPlan called with an invalid thread plan.");
4628 return eExpressionSetupError;
4629 }
4630
4631 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004632 diagnostic_manager.PutString(eDiagnosticSeverityError,
4633 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004634 return eExpressionSetupError;
4635 }
4636
4637 Thread *thread = exe_ctx.GetThreadPtr();
4638 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004639 diagnostic_manager.PutString(eDiagnosticSeverityError,
4640 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004641 return eExpressionSetupError;
4642 }
4643
4644 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004645 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004646
4647 RestorePlanState thread_plan_restorer(thread_plan_sp);
4648
Adrian Prantl05097242018-04-30 16:49:04 +00004649 // We rely on the thread plan we are running returning "PlanCompleted" if
4650 // when it successfully completes. For that to be true the plan can't be
4651 // private - since private plans suppress themselves in the GetCompletedPlan
4652 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004653
4654 thread_plan_sp->SetPrivate(false);
4655
4656 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004657 // when they are done we will end up asking the plan above us whether we
4658 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004659
4660 thread_plan_sp->SetIsMasterPlan(true);
4661 thread_plan_sp->SetOkayToDiscard(false);
4662
Raphael Isemannc01783a2018-08-29 22:50:54 +00004663 // If we are running some utility expression for LLDB, we now have to mark
4664 // this in the ProcesModID of this process. This RAII takes care of marking
4665 // and reverting the mark it once we are done running the expression.
4666 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4667
Kate Stoneb9c1b512016-09-06 20:57:50 +00004668 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004669 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004670 eDiagnosticSeverityError,
4671 "RunThreadPlan called while the private state was not stopped.");
4672 return eExpressionSetupError;
4673 }
4674
4675 // Save the thread & frame from the exe_ctx for restoration after we run
4676 const uint32_t thread_idx_id = thread->GetIndexID();
4677 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4678 if (!selected_frame_sp) {
4679 thread->SetSelectedFrame(nullptr);
4680 selected_frame_sp = thread->GetSelectedFrame();
4681 if (!selected_frame_sp) {
4682 diagnostic_manager.Printf(
4683 eDiagnosticSeverityError,
4684 "RunThreadPlan called without a selected frame on thread %d",
4685 thread_idx_id);
4686 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004687 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004688 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004689
Adrian Prantl05097242018-04-30 16:49:04 +00004690 // Make sure the timeout values make sense. The one thread timeout needs to
4691 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004692 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4693 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004694 diagnostic_manager.PutString(eDiagnosticSeverityError,
4695 "RunThreadPlan called with one thread "
4696 "timeout greater than total timeout");
4697 return eExpressionSetupError;
4698 }
4699
Kate Stoneb9c1b512016-09-06 20:57:50 +00004700 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004701
Kate Stoneb9c1b512016-09-06 20:57:50 +00004702 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004703 // We don't want to do that either, so we should arrange to reset them as
4704 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004705
Kate Stoneb9c1b512016-09-06 20:57:50 +00004706 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004707
Kate Stoneb9c1b512016-09-06 20:57:50 +00004708 uint32_t selected_tid;
4709 StackID selected_stack_id;
4710 if (selected_thread_sp) {
4711 selected_tid = selected_thread_sp->GetIndexID();
4712 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4713 } else {
4714 selected_tid = LLDB_INVALID_THREAD_ID;
4715 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004716
Kate Stoneb9c1b512016-09-06 20:57:50 +00004717 HostThread backup_private_state_thread;
4718 lldb::StateType old_state = eStateInvalid;
4719 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004720
Kate Stoneb9c1b512016-09-06 20:57:50 +00004721 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4722 LIBLLDB_LOG_PROCESS));
4723 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4724 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004725 // public events on this thread, since we are the thread that is generating
4726 // public events. The simplest thing to do is to spin up a temporary thread
4727 // to handle private state thread events while we are fielding public
4728 // events here.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004729 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4730 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004731
Kate Stoneb9c1b512016-09-06 20:57:50 +00004732 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004733
Kate Stoneb9c1b512016-09-06 20:57:50 +00004734 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004735 // anything it pushes, and then stop, returning control here. But in the
4736 // normal course of things, the plan above us on the stack would be given a
4737 // shot at the stop event before deciding to stop, and we don't want that.
4738 // So we insert a "stopper" base plan on the stack before the plan we want
4739 // to run. Since base plans always stop and return control to the user,
4740 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004741 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4742 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4743 // Have to make sure our public state is stopped, since otherwise the
4744 // reporting logic below doesn't work correctly.
4745 old_state = m_public_state.GetValue();
4746 m_public_state.SetValueNoLock(eStateStopped);
4747
4748 // Now spin up the private state thread:
4749 StartPrivateStateThread(true);
4750 }
4751
4752 thread->QueueThreadPlan(
4753 thread_plan_sp, false); // This used to pass "true" does that make sense?
4754
4755 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004756 // In this case, we aren't actually going to run, we just want to stop
4757 // right away. Flush this thread so we will refetch the stacks and show the
4758 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004759 // FIXME: To make this prettier we should invent some stop reason for this,
4760 // but that
4761 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004762 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004763 thread->Flush();
4764 return eExpressionStoppedForDebug;
4765 }
4766
4767 ListenerSP listener_sp(
4768 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4769
4770 lldb::EventSP event_to_broadcast_sp;
4771
4772 {
4773 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004774 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004775 //
4776 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004777 // exits during execution), then the event is put into
4778 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004779
4780 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4781
4782 if (log) {
4783 StreamString s;
4784 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004785 LLDB_LOGF(log,
4786 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4787 " to run thread plan \"%s\".",
4788 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004789 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004790
4791 bool got_event;
4792 lldb::EventSP event_sp;
4793 lldb::StateType stop_state = lldb::eStateInvalid;
4794
4795 bool before_first_timeout = true; // This is set to false the first time
4796 // that we have to halt the target.
4797 bool do_resume = true;
4798 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004799
4800 // This is just for accounting:
4801 uint32_t num_resumes = 0;
4802
Kate Stoneb9c1b512016-09-06 20:57:50 +00004803 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00004804 // going to run one thread, then we don't need the first timeout. So we
4805 // pretend we are after the first timeout already.
4806 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004807 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00004808
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004809 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4810 options.GetStopOthers(), options.GetTryAllThreads(),
4811 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004812
Adrian Prantl05097242018-04-30 16:49:04 +00004813 // This isn't going to work if there are unfetched events on the queue. Are
4814 // there cases where we might want to run the remaining events here, and
4815 // then try to call the function? That's probably being too tricky for our
4816 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004817
4818 Event *other_events = listener_sp->PeekAtNextEvent();
4819 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004820 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004821 eDiagnosticSeverityError,
4822 "RunThreadPlan called with pending events on the queue.");
4823 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00004824 }
4825
Kate Stoneb9c1b512016-09-06 20:57:50 +00004826 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00004827 // calling a function as part of a thread plan, in which case the last
4828 // delivered event could be the running event, and we don't want event
4829 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004830 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00004831
Kate Stoneb9c1b512016-09-06 20:57:50 +00004832// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00004833// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00004834
Kate Stoneb9c1b512016-09-06 20:57:50 +00004835#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00004836 // It's pretty much impossible to write test cases for things like: One
4837 // thread timeout expires, I go to halt, but the process already stopped on
4838 // the function call stop breakpoint. Turning on this define will make us
4839 // not fetch the first event till after the halt. So if you run a quick
4840 // function, it will have completed, and the completion event will be
4841 // waiting, when you interrupt for halt. The expression evaluation should
4842 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004843 bool miss_first_event = true;
4844#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00004845 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00004846 // We usually want to resume the process if we get to the top of the
4847 // loop. The only exception is if we get two running events with no
4848 // intervening stop, which can happen, we will just wait for then next
4849 // stop event.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004850 LLDB_LOGF(log,
4851 "Top of while loop: do_resume: %i handle_running_event: %i "
4852 "before_first_timeout: %i.",
4853 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00004854
Kate Stoneb9c1b512016-09-06 20:57:50 +00004855 if (do_resume || handle_running_event) {
4856 // Do the initial resume and wait for the running event before going
4857 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00004858
Kate Stoneb9c1b512016-09-06 20:57:50 +00004859 if (do_resume) {
4860 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00004861 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004862 if (!resume_error.Success()) {
4863 diagnostic_manager.Printf(
4864 eDiagnosticSeverityError,
4865 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4866 resume_error.AsCString());
4867 return_value = eExpressionSetupError;
4868 break;
4869 }
Jason Molendaef7d6412015-08-06 03:27:10 +00004870 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004871
Pavel Labathd35031e12016-11-30 10:41:42 +00004872 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00004873 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004874 if (!got_event) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004875 LLDB_LOGF(log,
4876 "Process::RunThreadPlan(): didn't get any event after "
4877 "resume %" PRIu32 ", exiting.",
4878 num_resumes);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004879
4880 diagnostic_manager.Printf(eDiagnosticSeverityError,
4881 "didn't get any event after resume %" PRIu32
4882 ", exiting.",
4883 num_resumes);
4884 return_value = eExpressionSetupError;
4885 break;
4886 }
4887
4888 stop_state =
4889 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4890
4891 if (stop_state != eStateRunning) {
4892 bool restarted = false;
4893
4894 if (stop_state == eStateStopped) {
4895 restarted = Process::ProcessEventData::GetRestartedFromEvent(
4896 event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004897 LLDB_LOGF(
4898 log,
4899 "Process::RunThreadPlan(): didn't get running event after "
4900 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4901 "handle_running_event: %i).",
4902 num_resumes, StateAsCString(stop_state), restarted, do_resume,
4903 handle_running_event);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004904 }
4905
4906 if (restarted) {
4907 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00004908 // should ever get a stopped & restarted event here. But if I do,
4909 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004910 const bool clear_thread_plans = false;
4911 const bool use_run_lock = false;
4912 Halt(clear_thread_plans, use_run_lock);
4913 }
4914
4915 diagnostic_manager.Printf(
4916 eDiagnosticSeverityError,
4917 "didn't get running event after initial resume, got %s instead.",
4918 StateAsCString(stop_state));
4919 return_value = eExpressionSetupError;
4920 break;
4921 }
4922
4923 if (log)
4924 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00004925 // We need to call the function synchronously, so spin waiting for it
4926 // to return. If we get interrupted while executing, we're going to
4927 // lose our context, and won't be able to gather the result at this
4928 // point. We set the timeout AFTER the resume, since the resume takes
4929 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004930 } else {
4931 if (log)
4932 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
4933 }
4934
Kate Stoneb9c1b512016-09-06 20:57:50 +00004935 do_resume = true;
4936 handle_running_event = true;
4937
4938 // Now wait for the process to stop again:
4939 event_sp.reset();
4940
Pavel Labath2ce22162016-12-01 10:57:30 +00004941 Timeout<std::micro> timeout =
4942 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004943 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004944 if (timeout) {
4945 auto now = system_clock::now();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004946 LLDB_LOGF(log,
4947 "Process::RunThreadPlan(): about to wait - now is %s - "
4948 "endpoint is %s",
4949 llvm::to_string(now).c_str(),
4950 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004951 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004952 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00004953 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004954 }
4955
4956#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4957 // See comment above...
4958 if (miss_first_event) {
4959 usleep(1000);
4960 miss_first_event = false;
4961 got_event = false;
4962 } else
4963#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00004964 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004965
4966 if (got_event) {
4967 if (event_sp) {
4968 bool keep_going = false;
4969 if (event_sp->GetType() == eBroadcastBitInterrupt) {
4970 const bool clear_thread_plans = false;
4971 const bool use_run_lock = false;
4972 Halt(clear_thread_plans, use_run_lock);
4973 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00004974 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
4975 "execution halted by user interrupt.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004976 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
4977 "eBroadcastBitInterrupted, exiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004978 break;
4979 } else {
4980 stop_state =
4981 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004982 LLDB_LOGF(log,
4983 "Process::RunThreadPlan(): in while loop, got event: %s.",
4984 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004985
4986 switch (stop_state) {
4987 case lldb::eStateStopped: {
4988 // We stopped, figure out what we are going to do now.
4989 ThreadSP thread_sp =
4990 GetThreadList().FindThreadByIndexID(thread_idx_id);
4991 if (!thread_sp) {
4992 // Ooh, our thread has vanished. Unlikely that this was
4993 // successful execution...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004994 LLDB_LOGF(log,
4995 "Process::RunThreadPlan(): execution completed "
4996 "but our thread (index-id=%u) has vanished.",
4997 thread_idx_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004998 return_value = eExpressionInterrupted;
Pavel Labath45dde232017-05-25 10:50:06 +00004999 } else if (Process::ProcessEventData::GetRestartedFromEvent(
5000 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005001 // If we were restarted, we just need to go back up to fetch
5002 // another event.
Pavel Labath45dde232017-05-25 10:50:06 +00005003 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005004 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5005 "restart, so we'll continue waiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005006 }
Pavel Labath45dde232017-05-25 10:50:06 +00005007 keep_going = true;
5008 do_resume = false;
5009 handle_running_event = true;
5010 } else {
5011 const bool handle_interrupts = true;
5012 return_value = *HandleStoppedEvent(
5013 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5014 event_to_broadcast_sp, options, handle_interrupts);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005015 }
5016 } break;
5017
5018 case lldb::eStateRunning:
5019 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005020 // running events without an intervening stop, and in that case
5021 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005022 do_resume = false;
5023 keep_going = true;
5024 handle_running_event = false;
5025 break;
5026
5027 default:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005028 LLDB_LOGF(log,
5029 "Process::RunThreadPlan(): execution stopped with "
5030 "unexpected state: %s.",
5031 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005032
5033 if (stop_state == eStateExited)
5034 event_to_broadcast_sp = event_sp;
5035
Zachary Turnere2411fa2016-11-12 19:12:56 +00005036 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005037 eDiagnosticSeverityError,
5038 "execution stopped with unexpected state.");
5039 return_value = eExpressionInterrupted;
5040 break;
5041 }
5042 }
5043
5044 if (keep_going)
5045 continue;
5046 else
5047 break;
5048 } else {
5049 if (log)
5050 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5051 "the event pointer was null. How odd...");
5052 return_value = eExpressionInterrupted;
5053 break;
5054 }
5055 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005056 // If we didn't get an event that means we've timed out... We will
5057 // interrupt the process here. Depending on what we were asked to do
5058 // we will either exit, or try with all threads running for the same
5059 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005060
5061 if (log) {
5062 if (options.GetTryAllThreads()) {
5063 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005064 LLDB_LOG(log,
5065 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005066 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005067 LLDB_LOG(log, "Restarting function with all threads enabled and "
5068 "timeout: {0} timed out, abandoning execution.",
5069 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005070 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005071 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5072 "abandoning execution.",
5073 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005074 }
5075
5076 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005077 // around to calling Halt the target could have stopped. That's fine,
5078 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005079 // BUT it is also possible that we stopped & restarted (e.g. hit a
5080 // signal with "stop" set to false.) In
5081 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005082 // back to waiting for the Halt's stopped event. That's what this
5083 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005084
5085 bool back_to_top = true;
5086 uint32_t try_halt_again = 0;
5087 bool do_halt = true;
5088 const uint32_t num_retries = 5;
5089 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005090 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005091 if (do_halt) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005092 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005093 const bool clear_thread_plans = false;
5094 const bool use_run_lock = false;
5095 Halt(clear_thread_plans, use_run_lock);
5096 }
5097 if (halt_error.Success()) {
5098 if (log)
5099 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5100
Pavel Labathd35031e12016-11-30 10:41:42 +00005101 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00005102 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005103
5104 if (got_event) {
5105 stop_state =
5106 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5107 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005108 LLDB_LOGF(log,
5109 "Process::RunThreadPlan(): Stopped with event: %s",
5110 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005111 if (stop_state == lldb::eStateStopped &&
5112 Process::ProcessEventData::GetInterruptedFromEvent(
5113 event_sp.get()))
5114 log->PutCString(" Event was the Halt interruption event.");
5115 }
5116
5117 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005118 if (Process::ProcessEventData::GetRestartedFromEvent(
5119 event_sp.get())) {
5120 if (log)
5121 log->PutCString("Process::RunThreadPlan(): Went to halt "
5122 "but got a restarted event, there must be "
5123 "an un-restarted stopped event so try "
5124 "again... "
5125 "Exiting wait loop.");
5126 try_halt_again++;
5127 do_halt = false;
5128 continue;
5129 }
5130
Pavel Labath45dde232017-05-25 10:50:06 +00005131 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005132 // delivered it, the process could have already finished its
5133 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005134 const bool handle_interrupts = false;
5135 if (auto result = HandleStoppedEvent(
5136 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5137 event_to_broadcast_sp, options, handle_interrupts)) {
5138 return_value = *result;
5139 back_to_top = false;
5140 break;
5141 }
5142
Kate Stoneb9c1b512016-09-06 20:57:50 +00005143 if (!options.GetTryAllThreads()) {
5144 if (log)
5145 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5146 "was false, we stopped so now we're "
5147 "quitting.");
5148 return_value = eExpressionInterrupted;
5149 back_to_top = false;
5150 break;
5151 }
5152
5153 if (before_first_timeout) {
5154 // Set all the other threads to run, and return to the top of
5155 // the loop, which will continue;
5156 before_first_timeout = false;
5157 thread_plan_sp->SetStopOthers(false);
5158 if (log)
5159 log->PutCString(
5160 "Process::RunThreadPlan(): about to resume.");
5161
5162 back_to_top = true;
5163 break;
5164 } else {
5165 // Running all threads failed, so return Interrupted.
5166 if (log)
5167 log->PutCString("Process::RunThreadPlan(): running all "
5168 "threads timed out.");
5169 return_value = eExpressionInterrupted;
5170 back_to_top = false;
5171 break;
5172 }
5173 }
5174 } else {
5175 if (log)
5176 log->PutCString("Process::RunThreadPlan(): halt said it "
5177 "succeeded, but I got no event. "
5178 "I'm getting out of here passing Interrupted.");
5179 return_value = eExpressionInterrupted;
5180 back_to_top = false;
5181 break;
5182 }
5183 } else {
5184 try_halt_again++;
5185 continue;
5186 }
5187 }
5188
5189 if (!back_to_top || try_halt_again > num_retries)
5190 break;
5191 else
5192 continue;
5193 }
5194 } // END WAIT LOOP
5195
Adrian Prantl05097242018-04-30 16:49:04 +00005196 // If we had to start up a temporary private state thread to run this
5197 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005198 if (backup_private_state_thread.IsJoinable()) {
5199 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005200 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005201 m_private_state_thread = backup_private_state_thread;
5202 if (stopper_base_plan_sp) {
5203 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5204 }
5205 if (old_state != eStateInvalid)
5206 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005207 }
5208
Kate Stoneb9c1b512016-09-06 20:57:50 +00005209 if (return_value != eExpressionCompleted && log) {
5210 // Print a backtrace into the log so we can figure out where we are:
5211 StreamString s;
5212 s.PutCString("Thread state after unsuccessful completion: \n");
5213 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005214 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005215 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005216 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005217 // There are three cases where this could happen: 1) The execution
5218 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5219 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005220 bool should_unwind = (return_value == eExpressionInterrupted &&
5221 options.DoesUnwindOnError()) ||
5222 (return_value == eExpressionHitBreakpoint &&
5223 options.DoesIgnoreBreakpoints());
5224
5225 if (return_value == eExpressionCompleted || should_unwind) {
5226 thread_plan_sp->RestoreThreadState();
5227 }
5228
5229 // Now do some processing on the results of the run:
5230 if (return_value == eExpressionInterrupted ||
5231 return_value == eExpressionHitBreakpoint) {
5232 if (log) {
5233 StreamString s;
5234 if (event_sp)
5235 event_sp->Dump(&s);
5236 else {
5237 log->PutCString("Process::RunThreadPlan(): Stop event that "
5238 "interrupted us is NULL.");
5239 }
5240
5241 StreamString ts;
5242
5243 const char *event_explanation = nullptr;
5244
5245 do {
5246 if (!event_sp) {
5247 event_explanation = "<no event>";
5248 break;
5249 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5250 event_explanation = "<user interrupt>";
5251 break;
5252 } else {
5253 const Process::ProcessEventData *event_data =
5254 Process::ProcessEventData::GetEventDataFromEvent(
5255 event_sp.get());
5256
5257 if (!event_data) {
5258 event_explanation = "<no event data>";
5259 break;
5260 }
5261
5262 Process *process = event_data->GetProcessSP().get();
5263
5264 if (!process) {
5265 event_explanation = "<no process>";
5266 break;
5267 }
5268
5269 ThreadList &thread_list = process->GetThreadList();
5270
5271 uint32_t num_threads = thread_list.GetSize();
5272 uint32_t thread_index;
5273
5274 ts.Printf("<%u threads> ", num_threads);
5275
5276 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5277 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5278
5279 if (!thread) {
5280 ts.Printf("<?> ");
5281 continue;
5282 }
5283
5284 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5285 RegisterContext *register_context =
5286 thread->GetRegisterContext().get();
5287
5288 if (register_context)
5289 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5290 else
5291 ts.Printf("[ip unknown] ");
5292
5293 // Show the private stop info here, the public stop info will be
5294 // from the last natural stop.
5295 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5296 if (stop_info_sp) {
5297 const char *stop_desc = stop_info_sp->GetDescription();
5298 if (stop_desc)
5299 ts.PutCString(stop_desc);
5300 }
5301 ts.Printf(">");
5302 }
5303
5304 event_explanation = ts.GetData();
5305 }
Jonas Devlieghere09ad8c82019-05-24 00:44:33 +00005306 } while (false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005307
5308 if (event_explanation)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005309 LLDB_LOGF(log,
5310 "Process::RunThreadPlan(): execution interrupted: %s %s",
5311 s.GetData(), event_explanation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005312 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005313 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
5314 s.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005315 }
5316
5317 if (should_unwind) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005318 LLDB_LOGF(log,
5319 "Process::RunThreadPlan: ExecutionInterrupted - "
5320 "discarding thread plans up to %p.",
5321 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005322 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5323 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005324 LLDB_LOGF(log,
5325 "Process::RunThreadPlan: ExecutionInterrupted - for "
5326 "plan: %p not discarding.",
5327 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005328 }
5329 } else if (return_value == eExpressionSetupError) {
5330 if (log)
5331 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5332
5333 if (options.DoesUnwindOnError()) {
5334 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5335 }
5336 } else {
5337 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5338 if (log)
5339 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5340 return_value = eExpressionCompleted;
5341 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5342 if (log)
5343 log->PutCString(
5344 "Process::RunThreadPlan(): thread plan was discarded");
5345 return_value = eExpressionDiscarded;
5346 } else {
5347 if (log)
5348 log->PutCString(
5349 "Process::RunThreadPlan(): thread plan stopped in mid course");
5350 if (options.DoesUnwindOnError() && thread_plan_sp) {
5351 if (log)
5352 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5353 "'cause unwind_on_error is set.");
5354 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5355 }
5356 }
5357 }
5358
5359 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005360 // target Check that it's still there, and if it is put it back in the
5361 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005362 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5363 if (thread) {
5364 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5365 }
5366
5367 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005368 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005369
5370 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5371 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5372 selected_stack_id.IsValid()) {
5373 // We were able to restore the selected thread, now restore the frame:
5374 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5375 StackFrameSP old_frame_sp =
5376 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5377 selected_stack_id);
5378 if (old_frame_sp)
5379 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5380 old_frame_sp.get());
5381 }
5382 }
5383 }
5384
5385 // If the process exited during the run of the thread plan, notify everyone.
5386
5387 if (event_to_broadcast_sp) {
5388 if (log)
5389 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5390 BroadcastEvent(event_to_broadcast_sp);
5391 }
5392
5393 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005394}
5395
Kate Stoneb9c1b512016-09-06 20:57:50 +00005396const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5397 const char *result_name;
5398
5399 switch (result) {
5400 case eExpressionCompleted:
5401 result_name = "eExpressionCompleted";
5402 break;
5403 case eExpressionDiscarded:
5404 result_name = "eExpressionDiscarded";
5405 break;
5406 case eExpressionInterrupted:
5407 result_name = "eExpressionInterrupted";
5408 break;
5409 case eExpressionHitBreakpoint:
5410 result_name = "eExpressionHitBreakpoint";
5411 break;
5412 case eExpressionSetupError:
5413 result_name = "eExpressionSetupError";
5414 break;
5415 case eExpressionParseError:
5416 result_name = "eExpressionParseError";
5417 break;
5418 case eExpressionResultUnavailable:
5419 result_name = "eExpressionResultUnavailable";
5420 break;
5421 case eExpressionTimedOut:
5422 result_name = "eExpressionTimedOut";
5423 break;
5424 case eExpressionStoppedForDebug:
5425 result_name = "eExpressionStoppedForDebug";
5426 break;
5427 }
5428 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005429}
5430
Kate Stoneb9c1b512016-09-06 20:57:50 +00005431void Process::GetStatus(Stream &strm) {
5432 const StateType state = GetState();
5433 if (StateIsStoppedState(state, false)) {
5434 if (state == eStateExited) {
5435 int exit_status = GetExitStatus();
5436 const char *exit_description = GetExitDescription();
5437 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5438 GetID(), exit_status, exit_status,
5439 exit_description ? exit_description : "");
5440 } else {
5441 if (state == eStateConnected)
5442 strm.Printf("Connected to remote target.\n");
5443 else
5444 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5445 }
5446 } else {
5447 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5448 }
Pavel Labatha933d512016-04-05 13:07:16 +00005449}
5450
Kate Stoneb9c1b512016-09-06 20:57:50 +00005451size_t Process::GetThreadStatus(Stream &strm,
5452 bool only_threads_with_stop_reason,
5453 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005454 uint32_t num_frames_with_source,
5455 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005456 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005457
Kate Stoneb9c1b512016-09-06 20:57:50 +00005458 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005459 // very well might run code (e.g. if we need it to get return values or
5460 // arguments.) For that to work the process has to be able to acquire it.
5461 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005462
5463 uint32_t num_threads;
5464 std::vector<lldb::tid_t> thread_id_array;
5465 // Scope for thread list locker;
5466 {
5467 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5468 ThreadList &curr_thread_list = GetThreadList();
5469 num_threads = curr_thread_list.GetSize();
5470 uint32_t idx;
5471 thread_id_array.resize(num_threads);
5472 for (idx = 0; idx < num_threads; ++idx)
5473 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5474 }
5475
5476 for (uint32_t i = 0; i < num_threads; i++) {
5477 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5478 if (thread_sp) {
5479 if (only_threads_with_stop_reason) {
5480 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5481 if (!stop_info_sp || !stop_info_sp->IsValid())
5482 continue;
5483 }
5484 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005485 num_frames_with_source,
5486 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005487 ++num_thread_infos_dumped;
5488 } else {
5489 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005490 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
5491 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005492 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005493 }
5494 return num_thread_infos_dumped;
5495}
5496
5497void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5498 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5499}
5500
5501bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5502 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5503 region.GetByteSize());
5504}
5505
5506void Process::AddPreResumeAction(PreResumeActionCallback callback,
5507 void *baton) {
5508 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5509}
5510
5511bool Process::RunPreResumeActions() {
5512 bool result = true;
5513 while (!m_pre_resume_actions.empty()) {
5514 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5515 m_pre_resume_actions.pop_back();
5516 bool this_result = action.callback(action.baton);
5517 if (result)
5518 result = this_result;
5519 }
5520 return result;
5521}
5522
5523void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5524
Jim Inghamffd91752016-10-20 22:50:00 +00005525void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5526{
5527 PreResumeCallbackAndBaton element(callback, baton);
5528 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5529 if (found_iter != m_pre_resume_actions.end())
5530 {
5531 m_pre_resume_actions.erase(found_iter);
5532 }
5533}
5534
Kate Stoneb9c1b512016-09-06 20:57:50 +00005535ProcessRunLock &Process::GetRunLock() {
5536 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5537 return m_private_run_lock;
5538 else
5539 return m_public_run_lock;
5540}
5541
5542void Process::Flush() {
5543 m_thread_list.Flush();
5544 m_extended_thread_list.Flush();
5545 m_extended_thread_stop_id = 0;
5546 m_queue_list.Clear();
5547 m_queue_list_stop_id = 0;
5548}
5549
5550void Process::DidExec() {
5551 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005552 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005553
5554 Target &target = GetTarget();
5555 target.CleanupProcess();
5556 target.ClearModules(false);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005557 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005558 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005559 m_system_runtime_up.reset();
5560 m_os_up.reset();
5561 m_dyld_up.reset();
5562 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005563 m_image_tokens.clear();
5564 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +00005565 {
5566 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5567 m_language_runtimes.clear();
5568 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005569 m_instrumentation_runtimes.clear();
5570 m_thread_list.DiscardThreadPlans();
5571 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005572 DoDidExec();
5573 CompleteAttach();
5574 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005575 // CompleteAttach() in case the dynamic loader loaded things in new
5576 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005577 Flush();
5578
Adrian Prantl05097242018-04-30 16:49:04 +00005579 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5580 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005581 target.DidExec();
5582}
5583
Zachary Turner97206d52017-05-12 04:51:55 +00005584addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005585 if (address == nullptr) {
5586 error.SetErrorString("Invalid address argument");
5587 return LLDB_INVALID_ADDRESS;
5588 }
5589
5590 addr_t function_addr = LLDB_INVALID_ADDRESS;
5591
5592 addr_t addr = address->GetLoadAddress(&GetTarget());
5593 std::map<addr_t, addr_t>::const_iterator iter =
5594 m_resolved_indirect_addresses.find(addr);
5595 if (iter != m_resolved_indirect_addresses.end()) {
5596 function_addr = (*iter).second;
5597 } else {
5598 if (!InferiorCall(this, address, function_addr)) {
5599 Symbol *symbol = address->CalculateSymbolContextSymbol();
5600 error.SetErrorStringWithFormat(
5601 "Unable to call resolver for indirect function %s",
5602 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5603 function_addr = LLDB_INVALID_ADDRESS;
5604 } else {
5605 m_resolved_indirect_addresses.insert(
5606 std::pair<addr_t, addr_t>(addr, function_addr));
5607 }
5608 }
5609 return function_addr;
5610}
5611
5612void Process::ModulesDidLoad(ModuleList &module_list) {
5613 SystemRuntime *sys_runtime = GetSystemRuntime();
5614 if (sys_runtime) {
5615 sys_runtime->ModulesDidLoad(module_list);
5616 }
5617
5618 GetJITLoaders().ModulesDidLoad(module_list);
5619
5620 // Give runtimes a chance to be created.
5621 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5622 m_instrumentation_runtimes);
5623
5624 // Tell runtimes about new modules.
5625 for (auto pos = m_instrumentation_runtimes.begin();
5626 pos != m_instrumentation_runtimes.end(); ++pos) {
5627 InstrumentationRuntimeSP runtime = pos->second;
5628 runtime->ModulesDidLoad(module_list);
5629 }
5630
Adrian Prantl05097242018-04-30 16:49:04 +00005631 // Let any language runtimes we have already created know about the modules
5632 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005633
Adrian Prantl05097242018-04-30 16:49:04 +00005634 // Iterate over a copy of this language runtime list in case the language
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005635 // runtime ModulesDidLoad somehow causes the language runtime to be
Adrian Prantl05097242018-04-30 16:49:04 +00005636 // unloaded.
Alex Langford74eb76f2019-05-22 23:01:18 +00005637 {
5638 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5639 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5640 for (const auto &pair : language_runtimes) {
5641 // We must check language_runtime_sp to make sure it is not nullptr as we
5642 // might cache the fact that we didn't have a language runtime for a
5643 // language.
5644 LanguageRuntimeSP language_runtime_sp = pair.second;
5645 if (language_runtime_sp)
5646 language_runtime_sp->ModulesDidLoad(module_list);
5647 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005648 }
5649
5650 // If we don't have an operating system plug-in, try to load one since
5651 // loading shared libraries might cause a new one to try and load
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005652 if (!m_os_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005653 LoadOperatingSystemPlugin(false);
5654
5655 // Give structured-data plugins a chance to see the modified modules.
5656 for (auto pair : m_structured_data_plugin_map) {
5657 if (pair.second)
5658 pair.second->ModulesDidLoad(*this, module_list);
5659 }
5660}
5661
5662void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5663 const char *fmt, ...) {
5664 bool print_warning = true;
5665
5666 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5667 if (!stream_sp)
5668 return;
5669 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5670 return;
5671 }
5672
5673 if (repeat_key != nullptr) {
5674 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5675 if (it == m_warnings_issued.end()) {
5676 m_warnings_issued[warning_type] = WarningsPointerSet();
5677 m_warnings_issued[warning_type].insert(repeat_key);
5678 } else {
5679 if (it->second.find(repeat_key) != it->second.end()) {
5680 print_warning = false;
5681 } else {
5682 it->second.insert(repeat_key);
5683 }
5684 }
5685 }
5686
5687 if (print_warning) {
5688 va_list args;
5689 va_start(args, fmt);
5690 stream_sp->PrintfVarArg(fmt, args);
5691 va_end(args);
5692 }
5693}
5694
5695void Process::PrintWarningOptimization(const SymbolContext &sc) {
5696 if (GetWarningsOptimization() && sc.module_sp &&
5697 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5698 sc.function->GetIsOptimized()) {
5699 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5700 "%s was compiled with optimization - stepping may behave "
5701 "oddly; variables may not be available.\n",
5702 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5703 }
5704}
5705
5706bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5707 info.Clear();
5708
5709 PlatformSP platform_sp = GetTarget().GetPlatform();
5710 if (!platform_sp)
5711 return false;
5712
5713 return platform_sp->GetProcessInfo(GetID(), info);
5714}
5715
5716ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5717 ThreadCollectionSP threads;
5718
5719 const MemoryHistorySP &memory_history =
5720 MemoryHistory::FindPlugin(shared_from_this());
5721
5722 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005723 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005724 }
5725
Jonas Devlieghere796ac802019-02-11 23:13:08 +00005726 threads = std::make_shared<ThreadCollection>(
5727 memory_history->GetHistoryThreads(addr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005728
5729 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005730}
Kuba Brecka63927542014-10-11 01:59:32 +00005731
5732InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005733Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5734 InstrumentationRuntimeCollection::iterator pos;
5735 pos = m_instrumentation_runtimes.find(type);
5736 if (pos == m_instrumentation_runtimes.end()) {
5737 return InstrumentationRuntimeSP();
5738 } else
5739 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005740}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005741
Kate Stoneb9c1b512016-09-06 20:57:50 +00005742bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5743 const ArchSpec &arch, ModuleSpec &module_spec) {
5744 module_spec.Clear();
5745 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005746}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005747
Kate Stoneb9c1b512016-09-06 20:57:50 +00005748size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5749 m_image_tokens.push_back(image_ptr);
5750 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005751}
5752
Kate Stoneb9c1b512016-09-06 20:57:50 +00005753lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5754 if (token < m_image_tokens.size())
5755 return m_image_tokens[token];
5756 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005757}
5758
Kate Stoneb9c1b512016-09-06 20:57:50 +00005759void Process::ResetImageToken(size_t token) {
5760 if (token < m_image_tokens.size())
5761 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005762}
Jason Molendafd4cea52016-01-08 21:40:11 +00005763
5764Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005765Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5766 AddressRange range_bounds) {
5767 Target &target = GetTarget();
5768 DisassemblerSP disassembler_sp;
5769 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005770
Kate Stoneb9c1b512016-09-06 20:57:50 +00005771 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005772
Kate Stoneb9c1b512016-09-06 20:57:50 +00005773 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005774 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005775 if (!default_stop_addr.IsValid())
5776 return retval;
5777
5778 ExecutionContext exe_ctx(this);
5779 const char *plugin_name = nullptr;
5780 const char *flavor = nullptr;
5781 const bool prefer_file_cache = true;
5782 disassembler_sp = Disassembler::DisassembleRange(
5783 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
5784 prefer_file_cache);
5785 if (disassembler_sp)
5786 insn_list = &disassembler_sp->GetInstructionList();
5787
5788 if (insn_list == nullptr) {
5789 return retval;
5790 }
5791
5792 size_t insn_offset =
5793 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5794 if (insn_offset == UINT32_MAX) {
5795 return retval;
5796 }
5797
5798 uint32_t branch_index =
Greg Claytondf225762019-05-09 20:39:34 +00005799 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target,
5800 false /* ignore_calls*/);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005801 if (branch_index == UINT32_MAX) {
5802 return retval;
5803 }
5804
5805 if (branch_index > insn_offset) {
5806 Address next_branch_insn_address =
5807 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5808 if (next_branch_insn_address.IsValid() &&
5809 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5810 retval = next_branch_insn_address;
5811 }
5812 }
5813
5814 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00005815}
Howard Hellyerad007562016-07-07 08:21:28 +00005816
Zachary Turner97206d52017-05-12 04:51:55 +00005817Status
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005818Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00005819
Zachary Turner97206d52017-05-12 04:51:55 +00005820 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00005821
Kate Stoneb9c1b512016-09-06 20:57:50 +00005822 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00005823
Kate Stoneb9c1b512016-09-06 20:57:50 +00005824 region_list.clear();
5825 do {
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005826 lldb_private::MemoryRegionInfo region_info;
5827 error = GetMemoryRegionInfo(range_end, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005828 // GetMemoryRegionInfo should only return an error if it is unimplemented.
5829 if (error.Fail()) {
5830 region_list.clear();
5831 break;
Todd Fiala75930012016-08-19 04:21:48 +00005832 }
5833
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005834 range_end = region_info.GetRange().GetRangeEnd();
5835 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5836 region_list.push_back(std::move(region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005837 }
5838 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00005839
Kate Stoneb9c1b512016-09-06 20:57:50 +00005840 return error;
5841}
5842
Zachary Turner97206d52017-05-12 04:51:55 +00005843Status
Adrian Prantl0e4c4822019-03-06 21:22:25 +00005844Process::ConfigureStructuredData(ConstString type_name,
Zachary Turner97206d52017-05-12 04:51:55 +00005845 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005846 // If you get this, the Process-derived class needs to implement a method to
5847 // enable an already-reported asynchronous structured data feature. See
5848 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00005849 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005850}
5851
5852void Process::MapSupportedStructuredDataPlugins(
5853 const StructuredData::Array &supported_type_names) {
5854 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5855
5856 // Bail out early if there are no type names to map.
5857 if (supported_type_names.GetSize() == 0) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005858 LLDB_LOGF(log, "Process::%s(): no structured data types supported",
5859 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005860 return;
5861 }
Todd Fiala75930012016-08-19 04:21:48 +00005862
Kate Stoneb9c1b512016-09-06 20:57:50 +00005863 // Convert StructuredData type names to ConstString instances.
5864 std::set<ConstString> const_type_names;
5865
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005866 LLDB_LOGF(log,
5867 "Process::%s(): the process supports the following async "
5868 "structured data types:",
5869 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005870
5871 supported_type_names.ForEach(
5872 [&const_type_names, &log](StructuredData::Object *object) {
5873 if (!object) {
5874 // Invalid - shouldn't be null objects in the array.
5875 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005876 }
5877
5878 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005879 if (!type_name) {
5880 // Invalid format - all type names should be strings.
5881 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005882 }
5883
5884 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00005885 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00005886 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005887 });
Todd Fiala75930012016-08-19 04:21:48 +00005888
Adrian Prantl05097242018-04-30 16:49:04 +00005889 // For each StructuredDataPlugin, if the plugin handles any of the types in
5890 // the supported_type_names, map that type name to that plugin. Stop when
5891 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005892 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00005893 // supports?
5894 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
5895 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00005896 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
5897 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00005898 if (!create_instance)
5899 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005900
Kate Stoneb9c1b512016-09-06 20:57:50 +00005901 // Create the plugin.
5902 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
5903 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005904 // This plugin doesn't think it can work with the process. Move on to the
5905 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005906 continue;
Todd Fiala75930012016-08-19 04:21:48 +00005907 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005908
Adrian Prantl05097242018-04-30 16:49:04 +00005909 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005910 std::vector<ConstString> names_to_remove;
5911 for (auto &type_name : const_type_names) {
5912 if (plugin_sp->SupportsStructuredDataType(type_name)) {
5913 m_structured_data_plugin_map.insert(
5914 std::make_pair(type_name, plugin_sp));
5915 names_to_remove.push_back(type_name);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005916 LLDB_LOGF(log,
5917 "Process::%s(): using plugin %s for type name "
5918 "%s",
5919 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
5920 type_name.GetCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005921 }
5922 }
5923
5924 // Remove the type names that were consumed by this plugin.
5925 for (auto &type_name : names_to_remove)
5926 const_type_names.erase(type_name);
5927 }
Todd Fiala75930012016-08-19 04:21:48 +00005928}
5929
Kate Stoneb9c1b512016-09-06 20:57:50 +00005930bool Process::RouteAsyncStructuredData(
5931 const StructuredData::ObjectSP object_sp) {
5932 // Nothing to do if there's no data.
5933 if (!object_sp)
5934 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005935
Adrian Prantl05097242018-04-30 16:49:04 +00005936 // The contract is this must be a dictionary, so we can look up the routing
5937 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005938 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
5939 if (!dictionary)
5940 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005941
Kate Stoneb9c1b512016-09-06 20:57:50 +00005942 // Grab the async structured type name (i.e. the feature/plugin name).
5943 ConstString type_name;
5944 if (!dictionary->GetValueForKeyAsString("type", type_name))
5945 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005946
Kate Stoneb9c1b512016-09-06 20:57:50 +00005947 // Check if there's a plugin registered for this type name.
5948 auto find_it = m_structured_data_plugin_map.find(type_name);
5949 if (find_it == m_structured_data_plugin_map.end()) {
5950 // We don't have a mapping for this structured data type.
5951 return false;
5952 }
Todd Fiala75930012016-08-19 04:21:48 +00005953
Kate Stoneb9c1b512016-09-06 20:57:50 +00005954 // Route the structured data to the plugin.
5955 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
5956 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00005957}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005958
Zachary Turner97206d52017-05-12 04:51:55 +00005959Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005960 // Default implementation does nothign.
5961 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00005962 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00005963}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005964
Frederic Rissd10d3792018-05-11 18:21:11 +00005965UtilityFunction *Process::GetLoadImageUtilityFunction(
5966 Platform *platform,
5967 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005968 if (platform != GetTarget().GetPlatform().get())
5969 return nullptr;
Frederic Rissd10d3792018-05-11 18:21:11 +00005970 std::call_once(m_dlopen_utility_func_flag_once,
5971 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00005972 return m_dlopen_utility_func_up.get();
5973}