blob: 7bd53af985d45b7d968755eaf9b7eb5221e08974 [file] [log] [blame]
Raphael Isemann80814282020-01-24 08:23:27 +01001//===-- Process.cpp -------------------------------------------------------===//
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Greg Clayton5cc45e02016-02-26 19:41:49 +00009#include <atomic>
Jonas Devlieghere796ac802019-02-11 23:13:08 +000010#include <memory>
Greg Clayton04df8ee2016-02-26 19:38:18 +000011#include <mutex>
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +000012
Pavel Labath2ce22162016-12-01 10:57:30 +000013#include "llvm/Support/ScopedPrinter.h"
Zachary Turner777de772017-03-04 16:42:25 +000014#include "llvm/Support/Threading.h"
15
Chris Lattner30fdc8d2010-06-08 16:52:24 +000016#include "lldb/Breakpoint/BreakpointLocation.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000017#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Greg Clayton1f746072012-08-29 21:13:06 +000019#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000020#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000022#include "lldb/Core/StreamFile.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000023#include "lldb/Expression/DiagnosticManager.h"
Alex Langfordbab7e3d2019-07-12 00:58:02 +000024#include "lldb/Expression/DynamicCheckerFunctions.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000025#include "lldb/Expression/UserExpression.h"
Jim Ingham1ecb34f2018-04-17 20:44:47 +000026#include "lldb/Expression/UtilityFunction.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000027#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000028#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000030#include "lldb/Host/HostInfo.h"
Zachary Turner3eb2b442017-03-22 23:33:16 +000031#include "lldb/Host/OptionParser.h"
Greg Clayton100eb932014-07-02 21:10:39 +000032#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000033#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000034#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000035#include "lldb/Interpreter/CommandInterpreter.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000036#include "lldb/Interpreter/OptionArgParser.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000037#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000038#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000039#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Target/ABI.h"
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +010041#include "lldb/Target/AssertFrameRecognizer.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000042#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000043#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000044#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000045#include "lldb/Target/JITLoaderList.h"
Alex Langford03e1a822019-05-29 18:08:22 +000046#include "lldb/Target/Language.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000047#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000048#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000049#include "lldb/Target/MemoryRegionInfo.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000050#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000051#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000052#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000054#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000055#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000056#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057#include "lldb/Target/Target.h"
58#include "lldb/Target/TargetList.h"
59#include "lldb/Target/Thread.h"
60#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000061#include "lldb/Target/ThreadPlanBase.h"
Alex Langford5b2b38e2019-09-13 00:02:05 +000062#include "lldb/Target/ThreadPlanCallFunction.h"
Jim Ingham61e8e682020-03-10 16:18:11 -070063#include "lldb/Target/ThreadPlanStack.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000064#include "lldb/Target/UnixSignals.h"
Pavel Labath181b8232018-12-14 15:59:49 +000065#include "lldb/Utility/Event.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000066#include "lldb/Utility/Log.h"
Zachary Turner50232572015-03-18 21:31:45 +000067#include "lldb/Utility/NameMatches.h"
Zachary Turner805e7102019-03-04 21:51:03 +000068#include "lldb/Utility/ProcessInfo.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000069#include "lldb/Utility/SelectHelper.h"
Pavel Labathd821c992018-08-07 11:07:21 +000070#include "lldb/Utility/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071
72using namespace lldb;
73using namespace lldb_private;
Pavel Labathe3e21cf2016-11-30 11:56:32 +000074using namespace std::chrono;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075
Kate Stoneb9c1b512016-09-06 20:57:50 +000076// Comment out line below to disable memory caching, overriding the process
Pavel Labath43d35412016-12-06 11:24:51 +000077// setting target.process.disable-memory-cache
Greg Clayton67cc0632012-08-22 17:17:09 +000078#define ENABLE_MEMORY_CACHING
79
80#ifdef ENABLE_MEMORY_CACHING
81#define DISABLE_MEM_CACHE_DEFAULT false
82#else
83#define DISABLE_MEM_CACHE_DEFAULT true
84#endif
85
Kate Stoneb9c1b512016-09-06 20:57:50 +000086class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000087public:
Adrian Prantl0e4c4822019-03-06 21:22:25 +000088 ProcessOptionValueProperties(ConstString name)
Kate Stoneb9c1b512016-09-06 20:57:50 +000089 : OptionValueProperties(name) {}
90
Adrian Prantl05097242018-04-30 16:49:04 +000091 // This constructor is used when creating ProcessOptionValueProperties when
92 // it is part of a new lldb_private::Process instance. It will copy all
93 // current global property values as needed
Kate Stoneb9c1b512016-09-06 20:57:50 +000094 ProcessOptionValueProperties(ProcessProperties *global_properties)
95 : OptionValueProperties(*global_properties->GetValueProperties()) {}
96
97 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
98 bool will_modify,
99 uint32_t idx) const override {
Adrian Prantl05097242018-04-30 16:49:04 +0000100 // When getting the value for a key from the process options, we will
101 // always try and grab the setting from the current process if there is
102 // one. Else we just use the one from this instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103 if (exe_ctx) {
104 Process *process = exe_ctx->GetProcessPtr();
105 if (process) {
106 ProcessOptionValueProperties *instance_properties =
107 static_cast<ProcessOptionValueProperties *>(
108 process->GetValueProperties().get());
109 if (this != instance_properties)
110 return instance_properties->ProtectedGetPropertyAtIndex(idx);
111 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000112 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113 return ProtectedGetPropertyAtIndex(idx);
114 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000115};
116
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000117#define LLDB_PROPERTIES_process
Jordan Rupprecht6a253d32019-07-29 17:22:10 +0000118#include "TargetProperties.inc"
Greg Clayton67cc0632012-08-22 17:17:09 +0000119
120enum {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000121#define LLDB_PROPERTIES_process
Jordan Rupprecht6a253d32019-07-29 17:22:10 +0000122#include "TargetPropertiesEnum.inc"
Jonas Devlieghere018e5a92020-05-19 11:16:57 -0700123 ePropertyExperimental,
Greg Clayton67cc0632012-08-22 17:17:09 +0000124};
125
Jonas Devlieghere018e5a92020-05-19 11:16:57 -0700126#define LLDB_PROPERTIES_process_experimental
127#include "TargetProperties.inc"
128
129enum {
130#define LLDB_PROPERTIES_process_experimental
131#include "TargetPropertiesEnum.inc"
132};
133
134class ProcessExperimentalOptionValueProperties : public OptionValueProperties {
135public:
136 ProcessExperimentalOptionValueProperties()
137 : OptionValueProperties(
138 ConstString(Properties::GetExperimentalSettingsName())) {}
139};
140
141ProcessExperimentalProperties::ProcessExperimentalProperties()
142 : Properties(OptionValuePropertiesSP(
143 new ProcessExperimentalOptionValueProperties())) {
144 m_collection_sp->Initialize(g_process_experimental_properties);
145}
146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147ProcessProperties::ProcessProperties(lldb_private::Process *process)
148 : Properties(),
149 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000150{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 if (process == nullptr) {
152 // Global process properties, set them up one time
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000153 m_collection_sp =
154 std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000155 m_collection_sp->Initialize(g_process_properties);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156 m_collection_sp->AppendProperty(
157 ConstString("thread"), ConstString("Settings specific to threads."),
158 true, Thread::GetGlobalProperties()->GetValueProperties());
159 } else {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000160 m_collection_sp = std::make_shared<ProcessOptionValueProperties>(
161 Process::GetGlobalProperties().get());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 m_collection_sp->SetValueChangedCallback(
163 ePropertyPythonOSPluginPath,
Pavel Labath5c4661b2020-01-09 14:14:54 +0100164 [this] { m_process->LoadOperatingSystemPlugin(true); });
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165 }
Jonas Devlieghere018e5a92020-05-19 11:16:57 -0700166
167 m_experimental_properties_up.reset(new ProcessExperimentalProperties());
168 m_collection_sp->AppendProperty(
169 ConstString(Properties::GetExperimentalSettingsName()),
170 ConstString("Experimental settings - setting these won't produce "
171 "errors if the setting is not present."),
172 true, m_experimental_properties_up->GetValueProperties());
Greg Clayton67cc0632012-08-22 17:17:09 +0000173}
174
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000175ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000176
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177bool ProcessProperties::GetDisableMemoryCache() const {
178 const uint32_t idx = ePropertyDisableMemCache;
179 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000180 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000181}
182
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
184 const uint32_t idx = ePropertyMemCacheLineSize;
185 return m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000186 nullptr, idx, g_process_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000187}
188
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189Args ProcessProperties::GetExtraStartupCommands() const {
190 Args args;
191 const uint32_t idx = ePropertyExtraStartCommand;
192 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
193 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000194}
195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196void ProcessProperties::SetExtraStartupCommands(const Args &args) {
197 const uint32_t idx = ePropertyExtraStartCommand;
198 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000199}
200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201FileSpec ProcessProperties::GetPythonOSPluginPath() const {
202 const uint32_t idx = ePropertyPythonOSPluginPath;
203 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000204}
205
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
207 const uint32_t idx = ePropertyPythonOSPluginPath;
208 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000209}
210
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
212 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
213 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000214 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000215}
216
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
218 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
219 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000220}
221
Kate Stoneb9c1b512016-09-06 20:57:50 +0000222bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
223 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
224 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000225 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000226}
227
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
229 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
230 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000231}
232
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
234 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
235 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000236 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000237}
238
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
240 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
241 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
242}
243
244bool ProcessProperties::GetDetachKeepsStopped() const {
245 const uint32_t idx = ePropertyDetachKeepsStopped;
246 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000247 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248}
249
250void ProcessProperties::SetDetachKeepsStopped(bool stop) {
251 const uint32_t idx = ePropertyDetachKeepsStopped;
252 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
253}
254
255bool ProcessProperties::GetWarningsOptimization() const {
256 const uint32_t idx = ePropertyWarningOptimization;
257 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000258 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259}
260
Jim Inghamba205c12017-12-05 02:50:45 +0000261bool ProcessProperties::GetStopOnExec() const {
262 const uint32_t idx = ePropertyStopOnExec;
263 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000264 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Inghamba205c12017-12-05 02:50:45 +0000265}
266
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000267std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
268 const uint32_t idx = ePropertyUtilityExpressionTimeout;
269 uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000270 nullptr, idx, g_process_properties[idx].default_uint_value);
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000271 return std::chrono::seconds(value);
272}
273
Jonas Devlieghere018e5a92020-05-19 11:16:57 -0700274bool ProcessProperties::GetOSPluginReportsAllThreads() const {
275 const bool fail_value = true;
276 const Property *exp_property =
277 m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental);
278 OptionValueProperties *exp_values =
279 exp_property->GetValue()->GetAsProperties();
280 if (!exp_values)
281 return fail_value;
282
283 return exp_values->GetPropertyAtIndexAsBoolean(
284 nullptr, ePropertyOSPluginReportsAllThreads, fail_value);
285}
286
287void ProcessProperties::SetOSPluginReportsAllThreads(bool does_report) {
288 const Property *exp_property =
289 m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental);
290 OptionValueProperties *exp_values =
291 exp_property->GetValue()->GetAsProperties();
292 if (exp_values)
293 exp_values->SetPropertyAtIndexAsBoolean(
294 nullptr, ePropertyOSPluginReportsAllThreads, does_report);
295}
296
Zachary Turner97206d52017-05-12 04:51:55 +0000297Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000298 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000300 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 const int short_option = m_getopt_table[option_idx].val;
302
303 switch (short_option) {
304 case 's': // Stop at program entry point
305 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
306 break;
307
308 case 'i': // STDIN for read only
309 {
310 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000311 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312 launch_info.AppendFileAction(action);
313 break;
314 }
315
316 case 'o': // Open STDOUT for write only
317 {
318 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000319 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 launch_info.AppendFileAction(action);
321 break;
322 }
323
324 case 'e': // STDERR for write only
325 {
326 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000327 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 launch_info.AppendFileAction(action);
329 break;
330 }
331
332 case 'p': // Process plug-in name
333 launch_info.SetProcessPluginName(option_arg);
334 break;
335
336 case 'n': // Disable STDIO
337 {
338 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000339 const FileSpec dev_null(FileSystem::DEV_NULL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 if (action.Open(STDIN_FILENO, dev_null, true, false))
341 launch_info.AppendFileAction(action);
342 if (action.Open(STDOUT_FILENO, dev_null, false, true))
343 launch_info.AppendFileAction(action);
344 if (action.Open(STDERR_FILENO, dev_null, false, true))
345 launch_info.AppendFileAction(action);
346 break;
347 }
348
349 case 'w':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000350 launch_info.SetWorkingDirectory(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 break;
352
353 case 't': // Open process in new terminal window
354 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
355 break;
356
357 case 'a': {
358 TargetSP target_sp =
359 execution_context ? execution_context->GetTargetSP() : TargetSP();
360 PlatformSP platform_sp =
361 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000362 launch_info.GetArchitecture() =
363 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 } break;
365
366 case 'A': // Disable ASLR.
367 {
368 bool success;
369 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000370 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 if (success)
372 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000373 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 error.SetErrorStringWithFormat(
375 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000376 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 break;
378 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000379
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380 case 'X': // shell expand args.
381 {
382 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000383 const bool expand_args =
384 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 if (success)
386 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000387 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 error.SetErrorStringWithFormat(
389 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000390 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391 break;
392 }
393
394 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000395 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000396 launch_info.SetShell(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 else
398 launch_info.SetShell(HostInfo::GetDefaultShell());
399 break;
400
401 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000402 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 break;
404
405 default:
406 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
407 short_option);
408 break;
409 }
410 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000411}
412
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000413static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000415 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416 "Stop at the entry point of the program when launching a process."},
417 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000418 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 "Set whether to disable address space layout randomization when launching "
420 "a process."},
421 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000422 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 "Name of the process plugin you want to use."},
424 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000425 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426 eArgTypeDirectoryName,
427 "Set the current working directory to <path> when running the inferior."},
428 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000429 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 "Set the architecture for the process to launch when ambiguous."},
431 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000432 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 "Specify an environment variable name/value string (--environment "
434 "NAME=VALUE). Can be specified multiple times for subsequent environment "
435 "entries."},
436 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000437 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000439
Kate Stoneb9c1b512016-09-06 20:57:50 +0000440 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000441 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 "Redirect stdin for the process to <filename>."},
443 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000444 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445 "Redirect stdout for the process to <filename>."},
446 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000447 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000449
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000451 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000453
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000455 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 "Do not set up for terminal I/O to go to running process."},
457 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000458 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000460};
461
462llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000463 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000464}
Greg Clayton32e0a752011-03-30 18:16:51 +0000465
Zachary Turner31659452016-11-17 21:15:14 +0000466ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
467 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 ListenerSP listener_sp,
469 const FileSpec *crash_file_path) {
470 static uint32_t g_process_unique_id = 0;
471
472 ProcessSP process_sp;
473 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000474 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000475 ConstString const_plugin_name(plugin_name);
476 create_callback =
477 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
478 if (create_callback) {
479 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
480 if (process_sp) {
481 if (process_sp->CanDebug(target_sp, true)) {
482 process_sp->m_process_unique_id = ++g_process_unique_id;
483 } else
484 process_sp.reset();
485 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000486 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487 } else {
488 for (uint32_t idx = 0;
489 (create_callback =
490 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
491 ++idx) {
492 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
493 if (process_sp) {
494 if (process_sp->CanDebug(target_sp, false)) {
495 process_sp->m_process_unique_id = ++g_process_unique_id;
496 break;
497 } else
498 process_sp.reset();
499 }
500 }
501 }
502 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000503}
504
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505ConstString &Process::GetStaticBroadcasterClass() {
506 static ConstString class_name("lldb.process");
507 return class_name;
508}
509
510Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
511 : Process(target_sp, listener_sp,
512 UnixSignals::Create(HostInfo::GetArchitecture())) {
513 // This constructor just delegates to the full Process constructor,
514 // defaulting to using the Host's UnixSignals.
515}
516
517Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
518 const UnixSignalsSP &unix_signals_sp)
519 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
520 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
521 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000522 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523 m_private_state(eStateUnloaded),
524 m_private_state_broadcaster(nullptr,
525 "lldb.process.internal_state_broadcaster"),
526 m_private_state_control_broadcaster(
527 nullptr, "lldb.process.internal_state_control_broadcaster"),
528 m_private_state_listener_sp(
529 Listener::MakeListener("lldb.process.internal_state_listener")),
530 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
531 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
532 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
Jim Ingham18930652020-03-18 12:05:08 -0700533 m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
535 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000536 m_breakpoint_site_list(), m_dynamic_checkers_up(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
538 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
539 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
540 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
541 m_memory_cache(*this), m_allocated_memory_cache(*this),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000542 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000543 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
545 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
546 m_can_interpret_function_calls(false), m_warnings_issued(),
547 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
548 CheckInWithManager();
549
550 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000551 LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552
553 if (!m_unix_signals_sp)
554 m_unix_signals_sp = std::make_shared<UnixSignals>();
555
556 SetEventName(eBroadcastBitStateChanged, "state-changed");
557 SetEventName(eBroadcastBitInterrupt, "interrupt");
558 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
559 SetEventName(eBroadcastBitSTDERR, "stderr-available");
560 SetEventName(eBroadcastBitProfileData, "profile-data-available");
561 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
562
563 m_private_state_control_broadcaster.SetEventName(
564 eBroadcastInternalStateControlStop, "control-stop");
565 m_private_state_control_broadcaster.SetEventName(
566 eBroadcastInternalStateControlPause, "control-pause");
567 m_private_state_control_broadcaster.SetEventName(
568 eBroadcastInternalStateControlResume, "control-resume");
569
570 m_listener_sp->StartListeningForEvents(
571 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
572 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
573 eBroadcastBitProfileData | eBroadcastBitStructuredData);
574
575 m_private_state_listener_sp->StartListeningForEvents(
576 &m_private_state_broadcaster,
577 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
578
579 m_private_state_listener_sp->StartListeningForEvents(
580 &m_private_state_control_broadcaster,
581 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
582 eBroadcastInternalStateControlResume);
583 // We need something valid here, even if just the default UnixSignalsSP.
584 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
585
586 // Allow the platform to override the default cache line size
587 OptionValueSP value_sp =
588 m_collection_sp
589 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
590 ->GetValue();
591 uint32_t platform_cache_line_size =
592 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
593 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
594 value_sp->SetUInt64Value(platform_cache_line_size);
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100595
596 RegisterAssertFrameRecognizer(this);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597}
598
599Process::~Process() {
600 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000601 LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602 StopPrivateStateThread();
603
604 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000605 // explicitly clear the thread list here to ensure that the mutex is not
606 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607 m_thread_list.Clear();
608}
609
610const ProcessPropertiesSP &Process::GetGlobalProperties() {
611 // NOTE: intentional leak so we don't crash if global destructor chain gets
612 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000613 static ProcessPropertiesSP *g_settings_sp_ptr =
614 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 return *g_settings_sp_ptr;
616}
617
618void Process::Finalize() {
619 m_finalizing = true;
620
621 // Destroy this process if needed
622 switch (GetPrivateState()) {
623 case eStateConnected:
624 case eStateAttaching:
625 case eStateLaunching:
626 case eStateStopped:
627 case eStateRunning:
628 case eStateStepping:
629 case eStateCrashed:
630 case eStateSuspended:
631 Destroy(false);
632 break;
633
634 case eStateInvalid:
635 case eStateUnloaded:
636 case eStateDetached:
637 case eStateExited:
638 break;
639 }
640
641 // Clear our broadcaster before we proceed with destroying
642 Broadcaster::Clear();
643
Adrian Prantl05097242018-04-30 16:49:04 +0000644 // Do any cleanup needed prior to being destructed... Subclasses that
645 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646
647 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000648 // destroyed since it is very likely that undoing the loader will require
649 // access to the real process.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000650 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000652 m_os_up.reset();
653 m_system_runtime_up.reset();
654 m_dyld_up.reset();
655 m_jit_loaders_up.reset();
Jim Ingham61e8e682020-03-10 16:18:11 -0700656 m_thread_plans.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 m_thread_list_real.Destroy();
658 m_thread_list.Destroy();
659 m_extended_thread_list.Destroy();
660 m_queue_list.Clear();
661 m_queue_list_stop_id = 0;
662 std::vector<Notifications> empty_notifications;
663 m_notifications.swap(empty_notifications);
664 m_image_tokens.clear();
665 m_memory_cache.Clear();
666 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +0000667 {
668 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
669 m_language_runtimes.clear();
670 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671 m_instrumentation_runtimes.clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000672 m_next_event_action_up.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000673 // Clear the last natural stop ID since it has a strong reference to this
674 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
676 //#ifdef LLDB_CONFIGURATION_DEBUG
677 // StreamFile s(stdout, false);
678 // EventSP event_sp;
679 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
680 // {
681 // event_sp->Dump (&s);
682 // s.EOL();
683 // }
684 //#endif
685 // We have to be very careful here as the m_private_state_listener might
686 // contain events that have ProcessSP values in them which can keep this
687 // process around forever. These events need to be cleared out.
688 m_private_state_listener_sp->Clear();
689 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
690 m_public_run_lock.SetStopped();
691 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
692 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000693 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000694 m_finalize_called = true;
695}
696
697void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
698 m_notifications.push_back(callbacks);
699 if (callbacks.initialize != nullptr)
700 callbacks.initialize(callbacks.baton, this);
701}
702
703bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
704 std::vector<Notifications>::iterator pos, end = m_notifications.end();
705 for (pos = m_notifications.begin(); pos != end; ++pos) {
706 if (pos->baton == callbacks.baton &&
707 pos->initialize == callbacks.initialize &&
708 pos->process_state_changed == callbacks.process_state_changed) {
709 m_notifications.erase(pos);
710 return true;
711 }
712 }
713 return false;
714}
715
716void Process::SynchronouslyNotifyStateChanged(StateType state) {
717 std::vector<Notifications>::iterator notification_pos,
718 notification_end = m_notifications.end();
719 for (notification_pos = m_notifications.begin();
720 notification_pos != notification_end; ++notification_pos) {
721 if (notification_pos->process_state_changed)
722 notification_pos->process_state_changed(notification_pos->baton, this,
723 state);
724 }
725}
726
727// FIXME: We need to do some work on events before the general Listener sees
728// them.
729// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000730// we do the little "insert real insn, step & stop" trick. But we can't do
731// that when the event is delivered by the broadcaster - since that is done on
732// the thread that is waiting for new events, so if we needed more than one
733// event for our handling, we would stall. So instead we do it when we fetch
734// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735//
736
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737StateType Process::GetNextEvent(EventSP &event_sp) {
738 StateType state = eStateInvalid;
739
Pavel Labathd35031e12016-11-30 10:41:42 +0000740 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
741 std::chrono::seconds(0)) &&
742 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
744
745 return state;
746}
747
Pavel Labath3879fe02018-05-09 14:29:30 +0000748void Process::SyncIOHandler(uint32_t iohandler_id,
749 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750 // don't sync (potentially context switch) in case where there is no process
751 // IO
752 if (!m_process_input_reader)
753 return;
754
Pavel Labath3879fe02018-05-09 14:29:30 +0000755 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756
757 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000758 if (Result) {
759 LLDB_LOG(
760 log,
761 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
762 iohandler_id, *Result);
763 } else {
764 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
765 iohandler_id);
766 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767}
768
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000769StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
770 EventSP *event_sp_ptr, bool wait_always,
771 ListenerSP hijack_listener_sp,
772 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000773 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000774 // have restarted the target. We have to actually check each event, and in
775 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 if (event_sp_ptr)
777 event_sp_ptr->reset();
778 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000779 // If we are exited or detached, we won't ever get back to any other valid
780 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000782 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000783
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000785 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000786
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 if (!wait_always && StateIsStoppedState(state, true) &&
788 StateIsStoppedState(GetPrivateState(), true)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000789 LLDB_LOGF(log,
790 "Process::%s returning without waiting for events; process "
791 "private and public states are already 'stopped'.",
792 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000793 // We need to toggle the run lock as this won't get done in
794 // SetPublicState() if the process is hijacked.
795 if (hijack_listener_sp && use_run_lock)
796 m_public_run_lock.SetStopped();
797 return state;
798 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 while (state != eStateInvalid) {
801 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000802 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803 if (event_sp_ptr && event_sp)
804 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +0000805
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
807 Process::HandleProcessStateChangedEvent(event_sp, stream,
808 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +0000809
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 switch (state) {
811 case eStateCrashed:
812 case eStateDetached:
813 case eStateExited:
814 case eStateUnloaded:
815 // We need to toggle the run lock as this won't get done in
816 // SetPublicState() if the process is hijacked.
817 if (hijack_listener_sp && use_run_lock)
818 m_public_run_lock.SetStopped();
819 return state;
820 case eStateStopped:
821 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
822 continue;
823 else {
Pavel Labath78521ef2015-03-06 10:52:47 +0000824 // We need to toggle the run lock as this won't get done in
825 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +0000826 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 m_public_run_lock.SetStopped();
828 return state;
829 }
830 default:
831 continue;
832 }
833 }
834 return state;
835}
836
837bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
838 Stream *stream,
839 bool &pop_process_io_handler) {
840 const bool handle_pop = pop_process_io_handler;
841
842 pop_process_io_handler = false;
843 ProcessSP process_sp =
844 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
845
846 if (!process_sp)
847 return false;
848
849 StateType event_state =
850 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
851 if (event_state == eStateInvalid)
852 return false;
853
854 switch (event_state) {
855 case eStateInvalid:
856 case eStateUnloaded:
857 case eStateAttaching:
858 case eStateLaunching:
859 case eStateStepping:
860 case eStateDetached:
861 if (stream)
862 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
863 StateAsCString(event_state));
864 if (event_state == eStateDetached)
865 pop_process_io_handler = true;
866 break;
867
868 case eStateConnected:
869 case eStateRunning:
870 // Don't be chatty when we run...
871 break;
872
873 case eStateExited:
874 if (stream)
875 process_sp->GetStatus(*stream);
876 pop_process_io_handler = true;
877 break;
878
879 case eStateStopped:
880 case eStateCrashed:
881 case eStateSuspended:
882 // Make sure the program hasn't been auto-restarted:
883 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
884 if (stream) {
885 size_t num_reasons =
886 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
887 if (num_reasons > 0) {
888 // FIXME: Do we want to report this, or would that just be annoyingly
889 // chatty?
890 if (num_reasons == 1) {
891 const char *reason =
892 Process::ProcessEventData::GetRestartedReasonAtIndex(
893 event_sp.get(), 0);
894 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
895 process_sp->GetID(),
896 reason ? reason : "<UNKNOWN REASON>");
897 } else {
898 stream->Printf("Process %" PRIu64
899 " stopped and restarted, reasons:\n",
900 process_sp->GetID());
901
902 for (size_t i = 0; i < num_reasons; i++) {
903 const char *reason =
904 Process::ProcessEventData::GetRestartedReasonAtIndex(
905 event_sp.get(), i);
906 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
907 }
908 }
909 }
910 }
911 } else {
912 StopInfoSP curr_thread_stop_info_sp;
913 // Lock the thread list so it doesn't change on us, this is the scope for
914 // the locker:
915 {
916 ThreadList &thread_list = process_sp->GetThreadList();
917 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
918
919 ThreadSP curr_thread(thread_list.GetSelectedThread());
920 ThreadSP thread;
921 StopReason curr_thread_stop_reason = eStopReasonInvalid;
922 if (curr_thread) {
923 curr_thread_stop_reason = curr_thread->GetStopReason();
924 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
925 }
926 if (!curr_thread || !curr_thread->IsValid() ||
927 curr_thread_stop_reason == eStopReasonInvalid ||
928 curr_thread_stop_reason == eStopReasonNone) {
929 // Prefer a thread that has just completed its plan over another
930 // thread as current thread.
931 ThreadSP plan_thread;
932 ThreadSP other_thread;
933
934 const size_t num_threads = thread_list.GetSize();
935 size_t i;
936 for (i = 0; i < num_threads; ++i) {
937 thread = thread_list.GetThreadAtIndex(i);
938 StopReason thread_stop_reason = thread->GetStopReason();
939 switch (thread_stop_reason) {
940 case eStopReasonInvalid:
941 case eStopReasonNone:
942 break;
943
944 case eStopReasonSignal: {
945 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +0000946 // that signal. We have to have had another reason for stopping
947 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 uint64_t signo = thread->GetStopInfo()->GetValue();
949 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
950 if (!other_thread)
951 other_thread = thread;
952 }
953 break;
954 }
955 case eStopReasonTrace:
956 case eStopReasonBreakpoint:
957 case eStopReasonWatchpoint:
958 case eStopReasonException:
959 case eStopReasonExec:
960 case eStopReasonThreadExiting:
961 case eStopReasonInstrumentation:
962 if (!other_thread)
963 other_thread = thread;
964 break;
965 case eStopReasonPlanComplete:
966 if (!plan_thread)
967 plan_thread = thread;
968 break;
969 }
970 }
971 if (plan_thread)
972 thread_list.SetSelectedThreadByID(plan_thread->GetID());
973 else if (other_thread)
974 thread_list.SetSelectedThreadByID(other_thread->GetID());
975 else {
976 if (curr_thread && curr_thread->IsValid())
977 thread = curr_thread;
978 else
979 thread = thread_list.GetThreadAtIndex(0);
980
981 if (thread)
982 thread_list.SetSelectedThreadByID(thread->GetID());
983 }
984 }
985 }
986 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +0000987 // have to run code, e.g. for Data formatters, and if we hold the
988 // ThreadList mutex, then the process is going to have a hard time
989 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 if (stream) {
991 Debugger &debugger = process_sp->GetTarget().GetDebugger();
992 if (debugger.GetTargetList().GetSelectedTarget().get() ==
993 &process_sp->GetTarget()) {
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100994 ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
995
996 if (!thread_sp || !thread_sp->IsValid())
997 return false;
998
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 const bool only_threads_with_stop_reason = true;
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +01001000 const uint32_t start_frame = thread_sp->GetSelectedFrameIndex();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 const uint32_t num_frames = 1;
1002 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001003 const bool stop_format = true;
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +01001004
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005 process_sp->GetStatus(*stream);
1006 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1007 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001008 num_frames_with_source,
1009 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 if (curr_thread_stop_info_sp) {
1011 lldb::addr_t crashing_address;
1012 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1013 curr_thread_stop_info_sp, &crashing_address);
1014 if (valobj_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 const ValueObject::GetExpressionPathFormat format =
1016 ValueObject::GetExpressionPathFormat::
1017 eGetExpressionPathFormatHonorPointers;
1018 stream->PutCString("Likely cause: ");
Alex Langford3014efe2020-02-02 14:17:02 -08001019 valobj_sp->GetExpressionPath(*stream, format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1021 }
1022 }
1023 } else {
1024 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1025 process_sp->GetTarget().shared_from_this());
1026 if (target_idx != UINT32_MAX)
1027 stream->Printf("Target %d: (", target_idx);
1028 else
1029 stream->Printf("Target <unknown index>: (");
1030 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1031 stream->Printf(") stopped.\n");
1032 }
1033 }
1034
1035 // Pop the process IO handler
1036 pop_process_io_handler = true;
1037 }
1038 break;
1039 }
1040
1041 if (handle_pop && pop_process_io_handler)
1042 process_sp->PopProcessIOHandler();
1043
1044 return true;
1045}
1046
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1048 if (listener_sp) {
1049 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1050 eBroadcastBitInterrupt);
1051 } else
1052 return false;
1053}
Greg Claytondc6224e2014-10-21 01:00:42 +00001054
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001056
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001057StateType Process::GetStateChangedEvents(EventSP &event_sp,
1058 const Timeout<std::micro> &timeout,
1059 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001061 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001062
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063 ListenerSP listener_sp = hijack_listener_sp;
1064 if (!listener_sp)
1065 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001066
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001068 if (listener_sp->GetEventForBroadcasterWithType(
1069 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001070 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1072 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001073 else
1074 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001076
Pavel Labathd02b1c82017-02-10 11:49:33 +00001077 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 return state;
1079}
Greg Claytondc6224e2014-10-21 01:00:42 +00001080
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081Event *Process::PeekAtStateChangedEvents() {
1082 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001083
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001084 LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001085
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 Event *event_ptr;
1087 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1088 this, eBroadcastBitStateChanged);
1089 if (log) {
1090 if (event_ptr) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001091 LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
1092 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001094 LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001095 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001096 }
1097 return event_ptr;
1098}
Greg Claytondc6224e2014-10-21 01:00:42 +00001099
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001100StateType
1101Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1102 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001104 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001105
1106 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001107 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1108 &m_private_state_broadcaster,
1109 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001110 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001111 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1112 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1113
Pavel Labathd02b1c82017-02-10 11:49:33 +00001114 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1115 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 return state;
1117}
1118
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001119bool Process::GetEventsPrivate(EventSP &event_sp,
1120 const Timeout<std::micro> &timeout,
1121 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001123 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124
1125 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001126 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001127 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001129 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130}
1131
1132bool Process::IsRunning() const {
1133 return StateIsRunningState(m_public_state.GetValue());
1134}
1135
1136int Process::GetExitStatus() {
1137 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1138
1139 if (m_public_state.GetValue() == eStateExited)
1140 return m_exit_status;
1141 return -1;
1142}
1143
1144const char *Process::GetExitDescription() {
1145 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1146
1147 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1148 return m_exit_string.c_str();
1149 return nullptr;
1150}
1151
1152bool Process::SetExitStatus(int status, const char *cstr) {
1153 // Use a mutex to protect setting the exit status.
1154 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1155
1156 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1157 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001158 LLDB_LOGF(
1159 log, "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1160 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", cstr ? "\"" : "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161
1162 // We were already in the exited state
1163 if (m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001164 LLDB_LOGF(log, "Process::SetExitStatus () ignoring exit status because "
1165 "state was already set to eStateExited");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166 return false;
1167 }
1168
1169 m_exit_status = status;
1170 if (cstr)
1171 m_exit_string = cstr;
1172 else
1173 m_exit_string.clear();
1174
Adrian Prantl05097242018-04-30 16:49:04 +00001175 // Clear the last natural stop ID since it has a strong reference to this
1176 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001177 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1178
1179 SetPrivateState(eStateExited);
1180
1181 // Allow subclasses to do some cleanup
1182 DidExit();
1183
1184 return true;
1185}
1186
1187bool Process::IsAlive() {
1188 switch (m_private_state.GetValue()) {
1189 case eStateConnected:
1190 case eStateAttaching:
1191 case eStateLaunching:
1192 case eStateStopped:
1193 case eStateRunning:
1194 case eStateStepping:
1195 case eStateCrashed:
1196 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001197 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001198 default:
1199 return false;
1200 }
Jason Molendaa814f702015-11-05 23:03:44 +00001201}
1202
Adrian Prantl05097242018-04-30 16:49:04 +00001203// This static callback can be used to watch for local child processes on the
1204// current host. The child process exits, the process will be found in the
1205// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001206// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001207bool Process::SetProcessExitStatus(
1208 lldb::pid_t pid, bool exited,
1209 int signo, // Zero for no signal
1210 int exit_status // Exit value of process if signal is zero
1211 ) {
1212 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001213 LLDB_LOGF(log,
1214 "Process::SetProcessExitStatus (pid=%" PRIu64
1215 ", exited=%i, signal=%i, exit_status=%i)\n",
1216 pid, exited, signo, exit_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217
1218 if (exited) {
1219 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1220 if (target_sp) {
1221 ProcessSP process_sp(target_sp->GetProcessSP());
1222 if (process_sp) {
1223 const char *signal_cstr = nullptr;
1224 if (signo)
1225 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1226
1227 process_sp->SetExitStatus(exit_status, signal_cstr);
1228 }
1229 }
1230 return true;
1231 }
1232 return false;
1233}
1234
1235void Process::UpdateThreadListIfNeeded() {
1236 const uint32_t stop_id = GetStopID();
1237 if (m_thread_list.GetSize(false) == 0 ||
1238 stop_id != m_thread_list.GetStopID()) {
Jim Ingham18930652020-03-18 12:05:08 -07001239 bool clear_unused_threads = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240 const StateType state = GetPrivateState();
1241 if (StateIsStoppedState(state, true)) {
1242 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Jim Ingham18930652020-03-18 12:05:08 -07001243 m_thread_list.SetStopID(stop_id);
1244
Adrian Prantl05097242018-04-30 16:49:04 +00001245 // m_thread_list does have its own mutex, but we need to hold onto the
1246 // mutex between the call to UpdateThreadList(...) and the
1247 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001248 ThreadList &old_thread_list = m_thread_list;
1249 ThreadList real_thread_list(this);
1250 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001251 // Always update the thread list with the protocol specific thread list,
1252 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1254 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001255 // are shutting down, since that may call back into the SBAPI's,
1256 // requiring the API lock which is already held by whoever is shutting
1257 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 OperatingSystem *os = GetOperatingSystem();
1259 if (os && !m_destroy_in_process) {
1260 // Clear any old backing threads where memory threads might have been
1261 // backed by actual threads from the lldb_private::Process subclass
1262 size_t num_old_threads = old_thread_list.GetSize(false);
1263 for (size_t i = 0; i < num_old_threads; ++i)
1264 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Jim Ingham18930652020-03-18 12:05:08 -07001265 // See if the OS plugin reports all threads. If it does, then
1266 // it is safe to clear unseen thread's plans here. Otherwise we
1267 // should preserve them in case they show up again:
Jonas Devlieghere018e5a92020-05-19 11:16:57 -07001268 clear_unused_threads = GetOSPluginReportsAllThreads();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269
1270 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001271 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001272 // dynamic type or not and we need to avoid this. OperatingSystem
1273 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274
1275 Target &target = GetTarget();
1276 const lldb::DynamicValueType saved_prefer_dynamic =
1277 target.GetPreferDynamicValue();
1278 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1279 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1280
1281 // Now let the OperatingSystem plug-in update the thread list
1282
1283 os->UpdateThreadList(
1284 old_thread_list, // Old list full of threads created by OS plug-in
1285 real_thread_list, // The actual thread list full of threads
1286 // created by each lldb_private::Process
1287 // subclass
1288 new_thread_list); // The new thread list that we will show to the
1289 // user that gets filled in
1290
1291 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1292 target.SetPreferDynamicValue(saved_prefer_dynamic);
1293 } else {
1294 // No OS plug-in, the new thread list is the same as the real thread
Jim Ingham18930652020-03-18 12:05:08 -07001295 // list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296 new_thread_list = real_thread_list;
1297 }
1298
1299 m_thread_list_real.Update(real_thread_list);
1300 m_thread_list.Update(new_thread_list);
1301 m_thread_list.SetStopID(stop_id);
1302
1303 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1304 // Clear any extended threads that we may have accumulated previously
1305 m_extended_thread_list.Clear();
1306 m_extended_thread_stop_id = GetLastNaturalStopID();
1307
1308 m_queue_list.Clear();
1309 m_queue_list_stop_id = GetLastNaturalStopID();
1310 }
1311 }
Jim Ingham18930652020-03-18 12:05:08 -07001312 // Now update the plan stack map.
1313 // If we do have an OS plugin, any absent real threads in the
1314 // m_thread_list have already been removed from the ThreadPlanStackMap.
1315 // So any remaining threads are OS Plugin threads, and those we want to
1316 // preserve in case they show up again.
1317 m_thread_plans.Update(m_thread_list, clear_unused_threads);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001318 }
1319 }
1320}
1321
Jim Ingham61e8e682020-03-10 16:18:11 -07001322ThreadPlanStack *Process::FindThreadPlans(lldb::tid_t tid) {
1323 return m_thread_plans.Find(tid);
1324}
1325
Jim Ingham18930652020-03-18 12:05:08 -07001326bool Process::PruneThreadPlansForTID(lldb::tid_t tid) {
1327 return m_thread_plans.PrunePlansForTID(tid);
Jim Ingham61e8e682020-03-10 16:18:11 -07001328}
1329
Jim Ingham18930652020-03-18 12:05:08 -07001330void Process::PruneThreadPlans() {
1331 m_thread_plans.Update(GetThreadList(), true, false);
1332}
1333
1334bool Process::DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid,
1335 lldb::DescriptionLevel desc_level,
1336 bool internal, bool condense_trivial,
1337 bool skip_unreported_plans) {
1338 return m_thread_plans.DumpPlansForTID(
1339 strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
1340}
1341void Process::DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,
1342 bool internal, bool condense_trivial,
1343 bool skip_unreported_plans) {
1344 m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
1345 skip_unreported_plans);
Jim Ingham61e8e682020-03-10 16:18:11 -07001346}
1347
Kate Stoneb9c1b512016-09-06 20:57:50 +00001348void Process::UpdateQueueListIfNeeded() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001349 if (m_system_runtime_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350 if (m_queue_list.GetSize() == 0 ||
1351 m_queue_list_stop_id != GetLastNaturalStopID()) {
1352 const StateType state = GetPrivateState();
1353 if (StateIsStoppedState(state, true)) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001354 m_system_runtime_up->PopulateQueueList(m_queue_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001355 m_queue_list_stop_id = GetLastNaturalStopID();
1356 }
1357 }
1358 }
1359}
1360
1361ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1362 OperatingSystem *os = GetOperatingSystem();
1363 if (os)
1364 return os->CreateThread(tid, context);
1365 return ThreadSP();
1366}
1367
1368uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1369 return AssignIndexIDToThread(thread_id);
1370}
1371
1372bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1373 return (m_thread_id_to_index_id_map.find(thread_id) !=
1374 m_thread_id_to_index_id_map.end());
1375}
1376
1377uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1378 uint32_t result = 0;
1379 std::map<uint64_t, uint32_t>::iterator iterator =
1380 m_thread_id_to_index_id_map.find(thread_id);
1381 if (iterator == m_thread_id_to_index_id_map.end()) {
1382 result = ++m_thread_index_id;
1383 m_thread_id_to_index_id_map[thread_id] = result;
1384 } else {
1385 result = iterator->second;
1386 }
1387
1388 return result;
1389}
1390
1391StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001392 return m_public_state.GetValue();
1393}
1394
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395void Process::SetPublicState(StateType new_state, bool restarted) {
1396 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1397 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001398 LLDB_LOGF(log, "Process::SetPublicState (state = %s, restarted = %i)",
1399 StateAsCString(new_state), restarted);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001400 const StateType old_state = m_public_state.GetValue();
1401 m_public_state.SetValue(new_state);
1402
Adrian Prantl05097242018-04-30 16:49:04 +00001403 // On the transition from Run to Stopped, we unlock the writer end of the run
1404 // lock. The lock gets locked in Resume, which is the public API to tell the
1405 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 if (!StateChangedIsExternallyHijacked()) {
1407 if (new_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001408 LLDB_LOGF(log,
1409 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1410 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001411 m_public_run_lock.SetStopped();
1412 } else {
1413 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1414 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1415 if ((old_state_is_stopped != new_state_is_stopped)) {
1416 if (new_state_is_stopped && !restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001417 LLDB_LOGF(log, "Process::SetPublicState (%s) -- unlocking run lock",
1418 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001419 m_public_run_lock.SetStopped();
1420 }
1421 }
1422 }
1423 }
1424}
1425
Zachary Turner97206d52017-05-12 04:51:55 +00001426Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001427 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1428 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001429 LLDB_LOGF(log, "Process::Resume -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001431 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001432 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001433 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001435 Status error = PrivateResume();
1436 if (!error.Success()) {
1437 // Undo running state change
1438 m_public_run_lock.SetStopped();
1439 }
1440 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001441}
1442
Jim Ingham3139fc92019-03-01 18:13:38 +00001443static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1444
Zachary Turner97206d52017-05-12 04:51:55 +00001445Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1447 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001448 LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001450 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001451 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452 return error;
1453 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001454
Kate Stoneb9c1b512016-09-06 20:57:50 +00001455 ListenerSP listener_sp(
Jim Ingham3139fc92019-03-01 18:13:38 +00001456 Listener::MakeListener(g_resume_sync_name));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001457 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001458
Zachary Turner97206d52017-05-12 04:51:55 +00001459 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001460 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001461 StateType state =
Konrad Kleine248a1302019-05-23 11:14:47 +00001462 WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 const bool must_be_alive =
1464 false; // eStateExited is ok, so this must be false
1465 if (!StateIsStoppedState(state, must_be_alive))
1466 error.SetErrorStringWithFormat(
1467 "process not in stopped state after synchronous resume: %s",
1468 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001469 } else {
1470 // Undo running state change
1471 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001472 }
Ed Mastec29693f2013-07-02 16:35:47 +00001473
Kate Stoneb9c1b512016-09-06 20:57:50 +00001474 // Undo the hijacking of process events...
1475 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001476
Kate Stoneb9c1b512016-09-06 20:57:50 +00001477 return error;
1478}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001479
Jim Ingham3139fc92019-03-01 18:13:38 +00001480bool Process::StateChangedIsExternallyHijacked() {
1481 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1482 const char *hijacking_name = GetHijackingListenerName();
1483 if (hijacking_name &&
1484 strcmp(hijacking_name, g_resume_sync_name))
1485 return true;
1486 }
1487 return false;
1488}
1489
1490bool Process::StateChangedIsHijackedForSynchronousResume() {
1491 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1492 const char *hijacking_name = GetHijackingListenerName();
1493 if (hijacking_name &&
1494 strcmp(hijacking_name, g_resume_sync_name) == 0)
1495 return true;
1496 }
1497 return false;
1498}
1499
Kate Stoneb9c1b512016-09-06 20:57:50 +00001500StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001501
Kate Stoneb9c1b512016-09-06 20:57:50 +00001502void Process::SetPrivateState(StateType new_state) {
1503 if (m_finalize_called)
1504 return;
1505
1506 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1507 LIBLLDB_LOG_PROCESS));
1508 bool state_changed = false;
1509
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001510 LLDB_LOGF(log, "Process::SetPrivateState (%s)", StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001511
1512 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1513 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1514
1515 const StateType old_state = m_private_state.GetValueNoLock();
1516 state_changed = old_state != new_state;
1517
1518 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1519 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1520 if (old_state_is_stopped != new_state_is_stopped) {
1521 if (new_state_is_stopped)
1522 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001523 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001524 m_private_run_lock.SetRunning();
1525 }
1526
1527 if (state_changed) {
1528 m_private_state.SetValueNoLock(new_state);
1529 EventSP event_sp(
1530 new Event(eBroadcastBitStateChanged,
1531 new ProcessEventData(shared_from_this(), new_state)));
1532 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001533 // Note, this currently assumes that all threads in the list stop when
1534 // the process stops. In the future we will want to support a debugging
1535 // model where some threads continue to run while others are stopped.
1536 // When that happens we will either need a way for the thread list to
1537 // identify which threads are stopping or create a special thread list
1538 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001539 //
Adrian Prantl05097242018-04-30 16:49:04 +00001540 // The process plugin is responsible for managing the actual behavior of
1541 // the threads and should have stopped any threads that are going to stop
1542 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001543 m_thread_list.DidStop();
1544
1545 m_mod_id.BumpStopID();
1546 if (!m_mod_id.IsLastResumeForUserExpression())
1547 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1548 m_memory_cache.Clear();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001549 LLDB_LOGF(log, "Process::SetPrivateState (%s) stop_id = %u",
1550 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001551 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001552
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553 // Use our target to get a shared pointer to ourselves...
1554 if (m_finalize_called && !PrivateStateThreadIsValid())
1555 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001556 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001557 m_private_state_broadcaster.BroadcastEvent(event_sp);
1558 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001559 LLDB_LOGF(log,
1560 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1561 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001562 }
Jim Ingham22777012010-09-23 02:01:19 +00001563}
1564
Kate Stoneb9c1b512016-09-06 20:57:50 +00001565void Process::SetRunningUserExpression(bool on) {
1566 m_mod_id.SetRunningUserExpression(on);
1567}
1568
Raphael Isemannc01783a2018-08-29 22:50:54 +00001569void Process::SetRunningUtilityFunction(bool on) {
1570 m_mod_id.SetRunningUtilityFunction(on);
1571}
1572
Kate Stoneb9c1b512016-09-06 20:57:50 +00001573addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1574
1575const lldb::ABISP &Process::GetABI() {
1576 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001577 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001578 return m_abi_sp;
1579}
1580
Davide Italianocec82632019-12-03 16:54:04 -08001581std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
Alex Langford03e1a822019-05-29 18:08:22 +00001582 std::vector<LanguageRuntime *> language_runtimes;
1583
1584 if (m_finalizing)
1585 return language_runtimes;
1586
1587 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1588 // Before we pass off a copy of the language runtimes, we must make sure that
1589 // our collection is properly populated. It's possible that some of the
1590 // language runtimes were not loaded yet, either because nobody requested it
1591 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1592 // hadn't been loaded).
1593 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
Davide Italianocec82632019-12-03 16:54:04 -08001594 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
Alex Langford03e1a822019-05-29 18:08:22 +00001595 language_runtimes.emplace_back(runtime);
1596 }
1597
1598 return language_runtimes;
1599}
1600
Davide Italianocec82632019-12-03 16:54:04 -08001601LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001602 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001603 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001604
Alex Langford7d3e97f2019-05-29 21:07:53 +00001605 LanguageRuntime *runtime = nullptr;
1606
Alex Langford74eb76f2019-05-22 23:01:18 +00001607 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001608 LanguageRuntimeCollection::iterator pos;
1609 pos = m_language_runtimes.find(language);
Davide Italianocec82632019-12-03 16:54:04 -08001610 if (pos == m_language_runtimes.end() || !pos->second) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611 lldb::LanguageRuntimeSP runtime_sp(
1612 LanguageRuntime::FindPlugin(this, language));
1613
1614 m_language_runtimes[language] = runtime_sp;
Alex Langford7d3e97f2019-05-29 21:07:53 +00001615 runtime = runtime_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001616 } else
Alex Langford7d3e97f2019-05-29 21:07:53 +00001617 runtime = pos->second.get();
1618
1619 if (runtime)
1620 // It's possible that a language runtime can support multiple LanguageTypes,
1621 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1622 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1623 // primary language type and make sure that our runtime supports it.
1624 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1625
1626 return runtime;
Jim Ingham22777012010-09-23 02:01:19 +00001627}
1628
Kate Stoneb9c1b512016-09-06 20:57:50 +00001629bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1630 if (m_finalizing)
1631 return false;
1632
1633 if (in_value.IsDynamic())
1634 return false;
1635 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1636
1637 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1638 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1639 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1640 }
1641
Alex Langford41dc5522019-05-30 21:03:53 +00001642 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1643 if (runtime->CouldHaveDynamicValue(in_value))
1644 return true;
1645 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646
Alex Langford41dc5522019-05-30 21:03:53 +00001647 return false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001648}
1649
Kate Stoneb9c1b512016-09-06 20:57:50 +00001650void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001651 m_dynamic_checkers_up.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001652}
1653
Kate Stoneb9c1b512016-09-06 20:57:50 +00001654BreakpointSiteList &Process::GetBreakpointSiteList() {
1655 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001656}
1657
Kate Stoneb9c1b512016-09-06 20:57:50 +00001658const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1659 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001660}
1661
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662void Process::DisableAllBreakpointSites() {
1663 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1664 // bp_site->SetEnabled(true);
1665 DisableBreakpointSite(bp_site);
1666 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001667}
1668
Zachary Turner97206d52017-05-12 04:51:55 +00001669Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1670 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001671
Kate Stoneb9c1b512016-09-06 20:57:50 +00001672 if (error.Success())
1673 m_breakpoint_site_list.Remove(break_id);
1674
1675 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001676}
1677
Zachary Turner97206d52017-05-12 04:51:55 +00001678Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1679 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001680 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1681 if (bp_site_sp) {
1682 if (bp_site_sp->IsEnabled())
1683 error = DisableBreakpointSite(bp_site_sp.get());
1684 } else {
1685 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1686 break_id);
1687 }
1688
1689 return error;
1690}
1691
Zachary Turner97206d52017-05-12 04:51:55 +00001692Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1693 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001694 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1695 if (bp_site_sp) {
1696 if (!bp_site_sp->IsEnabled())
1697 error = EnableBreakpointSite(bp_site_sp.get());
1698 } else {
1699 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1700 break_id);
1701 }
1702 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001703}
1704
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001705lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001706Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1707 bool use_hardware) {
1708 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001709
Kate Stoneb9c1b512016-09-06 20:57:50 +00001710 bool show_error = true;
1711 switch (GetState()) {
1712 case eStateInvalid:
1713 case eStateUnloaded:
1714 case eStateConnected:
1715 case eStateAttaching:
1716 case eStateLaunching:
1717 case eStateDetached:
1718 case eStateExited:
1719 show_error = false;
1720 break;
1721
1722 case eStateStopped:
1723 case eStateRunning:
1724 case eStateStepping:
1725 case eStateCrashed:
1726 case eStateSuspended:
1727 show_error = IsAlive();
1728 break;
1729 }
1730
Adrian Prantl05097242018-04-30 16:49:04 +00001731 // Reset the IsIndirect flag here, in case the location changes from pointing
1732 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001733 owner->SetIsIndirect(false);
1734
1735 if (owner->ShouldResolveIndirectFunctions()) {
1736 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1737 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001738 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001739 Address symbol_address = symbol->GetAddress();
1740 load_addr = ResolveIndirectFunction(&symbol_address, error);
1741 if (!error.Success() && show_error) {
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001742 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001743 "warning: failed to resolve indirect function at 0x%" PRIx64
1744 " for breakpoint %i.%i: %s\n",
1745 symbol->GetLoadAddress(&GetTarget()),
1746 owner->GetBreakpoint().GetID(), owner->GetID(),
1747 error.AsCString() ? error.AsCString() : "unknown error");
1748 return LLDB_INVALID_BREAK_ID;
1749 }
1750 Address resolved_address(load_addr);
1751 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1752 owner->SetIsIndirect(true);
1753 } else
1754 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1755 } else
1756 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1757
1758 if (load_addr != LLDB_INVALID_ADDRESS) {
1759 BreakpointSiteSP bp_site_sp;
1760
1761 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001762 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001763
1764 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1765
1766 if (bp_site_sp) {
1767 bp_site_sp->AddOwner(owner);
1768 owner->SetBreakpointSite(bp_site_sp);
1769 return bp_site_sp->GetID();
1770 } else {
1771 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1772 load_addr, use_hardware));
1773 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001774 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001775 if (error.Success()) {
1776 owner->SetBreakpointSite(bp_site_sp);
1777 return m_breakpoint_site_list.Add(bp_site_sp);
1778 } else {
Jonas Devliegheree103ae92018-11-15 01:18:15 +00001779 if (show_error || use_hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001780 // Report error for setting breakpoint...
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001781 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001782 "warning: failed to set breakpoint site at 0x%" PRIx64
1783 " for breakpoint %i.%i: %s\n",
1784 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1785 error.AsCString() ? error.AsCString() : "unknown error");
1786 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001787 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001788 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001789 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001790 }
1791 // We failed to enable the breakpoint
1792 return LLDB_INVALID_BREAK_ID;
1793}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001794
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1796 lldb::user_id_t owner_loc_id,
1797 BreakpointSiteSP &bp_site_sp) {
1798 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1799 if (num_owners == 0) {
1800 // Don't try to disable the site if we don't have a live process anymore.
1801 if (IsAlive())
1802 DisableBreakpointSite(bp_site_sp.get());
1803 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1804 }
1805}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001806
Kate Stoneb9c1b512016-09-06 20:57:50 +00001807size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1808 uint8_t *buf) const {
1809 size_t bytes_removed = 0;
1810 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001811
Kate Stoneb9c1b512016-09-06 20:57:50 +00001812 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1813 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001814 bp_sites_in_range.ForEach([bp_addr, size,
1815 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001816 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1817 addr_t intersect_addr;
1818 size_t intersect_size;
1819 size_t opcode_offset;
1820 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1821 &intersect_size, &opcode_offset)) {
1822 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1823 assert(bp_addr < intersect_addr + intersect_size &&
1824 intersect_addr + intersect_size <= bp_addr + size);
1825 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1826 size_t buf_offset = intersect_addr - bp_addr;
1827 ::memcpy(buf + buf_offset,
1828 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1829 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001831 }
1832 });
1833 }
1834 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835}
1836
Kate Stoneb9c1b512016-09-06 20:57:50 +00001837size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1838 PlatformSP platform_sp(GetTarget().GetPlatform());
1839 if (platform_sp)
1840 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1841 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001842}
1843
Zachary Turner97206d52017-05-12 04:51:55 +00001844Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1845 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001846 assert(bp_site != nullptr);
1847 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1848 const addr_t bp_addr = bp_site->GetLoadAddress();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001849 LLDB_LOGF(
1850 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1851 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001852 if (bp_site->IsEnabled()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001853 LLDB_LOGF(
1854 log,
1855 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1856 " -- already enabled",
1857 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001858 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001859 }
1860
1861 if (bp_addr == LLDB_INVALID_ADDRESS) {
1862 error.SetErrorString("BreakpointSite contains an invalid load address.");
1863 return error;
1864 }
1865 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1866 // trap for the breakpoint site
1867 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1868
1869 if (bp_opcode_size == 0) {
1870 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1871 "returned zero, unable to get breakpoint "
1872 "trap for address 0x%" PRIx64,
1873 bp_addr);
1874 } else {
1875 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1876
1877 if (bp_opcode_bytes == nullptr) {
1878 error.SetErrorString(
1879 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1880 return error;
1881 }
1882
1883 // Save the original opcode by reading it
1884 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1885 error) == bp_opcode_size) {
1886 // Write a software breakpoint in place of the original opcode
1887 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1888 bp_opcode_size) {
1889 uint8_t verify_bp_opcode_bytes[64];
1890 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1891 error) == bp_opcode_size) {
1892 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1893 bp_opcode_size) == 0) {
1894 bp_site->SetEnabled(true);
1895 bp_site->SetType(BreakpointSite::eSoftware);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001896 LLDB_LOGF(log,
1897 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1898 "addr = 0x%" PRIx64 " -- SUCCESS",
1899 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001900 } else
1901 error.SetErrorString(
1902 "failed to verify the breakpoint trap in memory.");
1903 } else
1904 error.SetErrorString(
1905 "Unable to read memory to verify breakpoint trap.");
1906 } else
1907 error.SetErrorString("Unable to write breakpoint trap to memory.");
1908 } else
1909 error.SetErrorString("Unable to read memory at breakpoint address.");
1910 }
1911 if (log && error.Fail())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001912 LLDB_LOGF(
1913 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001914 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1915 " -- FAILED: %s",
1916 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1917 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001918}
1919
Zachary Turner97206d52017-05-12 04:51:55 +00001920Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1921 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001922 assert(bp_site != nullptr);
1923 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1924 addr_t bp_addr = bp_site->GetLoadAddress();
1925 lldb::user_id_t breakID = bp_site->GetID();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001926 LLDB_LOGF(log,
1927 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1928 ") addr = 0x%" PRIx64,
1929 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001930
Kate Stoneb9c1b512016-09-06 20:57:50 +00001931 if (bp_site->IsHardware()) {
1932 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1933 } else if (bp_site->IsEnabled()) {
1934 const size_t break_op_size = bp_site->GetByteSize();
1935 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1936 if (break_op_size > 0) {
1937 // Clear a software breakpoint instruction
1938 uint8_t curr_break_op[8];
1939 assert(break_op_size <= sizeof(curr_break_op));
1940 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001941
Kate Stoneb9c1b512016-09-06 20:57:50 +00001942 // Read the breakpoint opcode
1943 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1944 break_op_size) {
1945 bool verify = false;
1946 // Make sure the breakpoint opcode exists at this address
1947 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1948 break_op_found = true;
1949 // We found a valid breakpoint opcode at this address, now restore
1950 // the saved opcode.
1951 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1952 break_op_size, error) == break_op_size) {
1953 verify = true;
1954 } else
1955 error.SetErrorString(
1956 "Memory write failed when restoring original opcode.");
1957 } else {
1958 error.SetErrorString(
1959 "Original breakpoint trap is no longer in memory.");
1960 // Set verify to true and so we can check if the original opcode has
1961 // already been restored
1962 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001963 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001964
Kate Stoneb9c1b512016-09-06 20:57:50 +00001965 if (verify) {
1966 uint8_t verify_opcode[8];
1967 assert(break_op_size < sizeof(verify_opcode));
1968 // Verify that our original opcode made it back to the inferior
1969 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1970 break_op_size) {
1971 // compare the memory we just read with the original opcode
1972 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1973 break_op_size) == 0) {
1974 // SUCCESS
1975 bp_site->SetEnabled(false);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001976 LLDB_LOGF(log,
1977 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1978 "addr = 0x%" PRIx64 " -- SUCCESS",
1979 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001980 return error;
1981 } else {
1982 if (break_op_found)
1983 error.SetErrorString("Failed to restore original opcode.");
1984 }
1985 } else
1986 error.SetErrorString("Failed to read memory to verify that "
1987 "breakpoint trap was restored.");
1988 }
1989 } else
1990 error.SetErrorString(
1991 "Unable to read memory that should contain the breakpoint trap.");
1992 }
1993 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001994 LLDB_LOGF(
1995 log,
1996 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1997 " -- already disabled",
1998 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001999 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002000 }
2001
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002002 LLDB_LOGF(
2003 log,
2004 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2005 " -- FAILED: %s",
2006 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002007 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002008}
2009
Adrian Prantl05097242018-04-30 16:49:04 +00002010// Uncomment to verify memory caching works after making changes to caching
2011// code
Greg Clayton58be07b2011-01-07 06:08:19 +00002012//#define VERIFY_MEMORY_READS
2013
Zachary Turner97206d52017-05-12 04:51:55 +00002014size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002015 error.Clear();
2016 if (!GetDisableMemoryCache()) {
2017#if defined(VERIFY_MEMORY_READS)
2018 // Memory caching is enabled, with debug verification
2019
2020 if (buf && size) {
2021 // Uncomment the line below to make sure memory caching is working.
2022 // I ran this through the test suite and got no assertions, so I am
2023 // pretty confident this is working well. If any changes are made to
2024 // memory caching, uncomment the line below and test your changes!
2025
2026 // Verify all memory reads by using the cache first, then redundantly
2027 // reading the same memory from the inferior and comparing to make sure
2028 // everything is exactly the same.
2029 std::string verify_buf(size, '\0');
2030 assert(verify_buf.size() == size);
2031 const size_t cache_bytes_read =
2032 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00002033 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002034 const size_t verify_bytes_read =
2035 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2036 verify_buf.size(), verify_error);
2037 assert(cache_bytes_read == verify_bytes_read);
2038 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2039 assert(verify_error.Success() == error.Success());
2040 return cache_bytes_read;
2041 }
2042 return 0;
2043#else // !defined(VERIFY_MEMORY_READS)
2044 // Memory caching is enabled, without debug verification
2045
2046 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002047#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002048 } else {
2049 // Memory caching is disabled
2050
2051 return ReadMemoryFromInferior(addr, buf, size, error);
2052 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002053}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002054
2055size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00002056 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002057 char buf[256];
2058 out_str.clear();
2059 addr_t curr_addr = addr;
2060 while (true) {
2061 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2062 if (length == 0)
2063 break;
2064 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00002065 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2066 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00002067 if (length == sizeof(buf) - 1)
2068 curr_addr += length;
2069 else
2070 break;
2071 }
2072 return out_str.size();
2073}
2074
2075size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00002076 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002077 size_t total_bytes_read = 0;
2078 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00002079 // Ensure a null terminator independent of the number of bytes that is
2080 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002081 memset(dst, 0, max_bytes);
2082 size_t bytes_left = max_bytes - type_width;
2083
2084 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2085 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2086 "string with more than 4 bytes "
2087 "per character!");
2088
Greg Clayton4c82d422012-05-18 23:20:01 +00002089 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002090 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2091 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002092
Kate Stoneb9c1b512016-09-06 20:57:50 +00002093 error.Clear();
2094 while (bytes_left > 0 && error.Success()) {
2095 addr_t cache_line_bytes_left =
2096 cache_line_size - (curr_addr % cache_line_size);
2097 addr_t bytes_to_read =
2098 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2099 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002100
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101 if (bytes_read == 0)
2102 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002103
Kate Stoneb9c1b512016-09-06 20:57:50 +00002104 // Search for a null terminator of correct size and alignment in
2105 // bytes_read
2106 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2107 for (size_t i = aligned_start;
2108 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2109 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2110 error.Clear();
2111 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002112 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002113
2114 total_bytes_read += bytes_read;
2115 curr_dst += bytes_read;
2116 curr_addr += bytes_read;
2117 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002118 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002119 } else {
2120 if (max_bytes)
2121 error.SetErrorString("invalid arguments");
2122 }
2123 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002124}
2125
Kate Stoneb9c1b512016-09-06 20:57:50 +00002126// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002127// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002129 size_t dst_max_len,
2130 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002131 size_t total_cstr_len = 0;
2132 if (dst && dst_max_len) {
2133 result_error.Clear();
2134 // NULL out everything just to be safe
2135 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002136 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002137 addr_t curr_addr = addr;
2138 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2139 size_t bytes_left = dst_max_len - 1;
2140 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002141
Kate Stoneb9c1b512016-09-06 20:57:50 +00002142 while (bytes_left > 0) {
2143 addr_t cache_line_bytes_left =
2144 cache_line_size - (curr_addr % cache_line_size);
2145 addr_t bytes_to_read =
2146 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2147 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002148
Kate Stoneb9c1b512016-09-06 20:57:50 +00002149 if (bytes_read == 0) {
2150 result_error = error;
2151 dst[total_cstr_len] = '\0';
2152 break;
2153 }
2154 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002155
Kate Stoneb9c1b512016-09-06 20:57:50 +00002156 total_cstr_len += len;
2157
2158 if (len < bytes_to_read)
2159 break;
2160
2161 curr_dst += bytes_read;
2162 curr_addr += bytes_read;
2163 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002164 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002165 } else {
2166 if (dst == nullptr)
2167 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002168 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 result_error.Clear();
2170 }
2171 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002172}
2173
Kate Stoneb9c1b512016-09-06 20:57:50 +00002174size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002175 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002176 if (buf == nullptr || size == 0)
2177 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002178
Kate Stoneb9c1b512016-09-06 20:57:50 +00002179 size_t bytes_read = 0;
2180 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002181
Kate Stoneb9c1b512016-09-06 20:57:50 +00002182 while (bytes_read < size) {
2183 const size_t curr_size = size - bytes_read;
2184 const size_t curr_bytes_read =
2185 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2186 bytes_read += curr_bytes_read;
2187 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2188 break;
2189 }
2190
2191 // Replace any software breakpoint opcodes that fall into this range back
2192 // into "buf" before we return
2193 if (bytes_read > 0)
2194 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2195 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002196}
2197
Kate Stoneb9c1b512016-09-06 20:57:50 +00002198uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2199 size_t integer_byte_size,
2200 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002201 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002202 Scalar scalar;
2203 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2204 error))
2205 return scalar.ULongLong(fail_value);
2206 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002207}
2208
Kate Stoneb9c1b512016-09-06 20:57:50 +00002209int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2210 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002211 int64_t fail_value,
2212 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002213 Scalar scalar;
2214 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2215 error))
2216 return scalar.SLongLong(fail_value);
2217 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002218}
2219
Zachary Turner97206d52017-05-12 04:51:55 +00002220addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002221 Scalar scalar;
2222 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2223 error))
2224 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2225 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002226}
2227
Kate Stoneb9c1b512016-09-06 20:57:50 +00002228bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002229 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002230 Scalar scalar;
2231 const uint32_t addr_byte_size = GetAddressByteSize();
2232 if (addr_byte_size <= 4)
2233 scalar = (uint32_t)ptr_value;
2234 else
2235 scalar = ptr_value;
2236 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2237 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002238}
2239
Kate Stoneb9c1b512016-09-06 20:57:50 +00002240size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002241 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002242 size_t bytes_written = 0;
2243 const uint8_t *bytes = (const uint8_t *)buf;
2244
2245 while (bytes_written < size) {
2246 const size_t curr_size = size - bytes_written;
2247 const size_t curr_bytes_written = DoWriteMemory(
2248 addr + bytes_written, bytes + bytes_written, curr_size, error);
2249 bytes_written += curr_bytes_written;
2250 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2251 break;
2252 }
2253 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002254}
2255
Kate Stoneb9c1b512016-09-06 20:57:50 +00002256size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002257 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002258#if defined(ENABLE_MEMORY_CACHING)
2259 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002260#endif
2261
Kate Stoneb9c1b512016-09-06 20:57:50 +00002262 if (buf == nullptr || size == 0)
2263 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002264
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002266
Kate Stoneb9c1b512016-09-06 20:57:50 +00002267 // We need to write any data that would go where any current software traps
2268 // (enabled software breakpoints) any software traps (breakpoints) that we
2269 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002270
Kate Stoneb9c1b512016-09-06 20:57:50 +00002271 BreakpointSiteList bp_sites_in_range;
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002272 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273 return WriteMemoryPrivate(addr, buf, size, error);
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002274
2275 // No breakpoint sites overlap
2276 if (bp_sites_in_range.IsEmpty())
2277 return WriteMemoryPrivate(addr, buf, size, error);
2278
2279 const uint8_t *ubuf = (const uint8_t *)buf;
2280 uint64_t bytes_written = 0;
2281
2282 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2283 &error](BreakpointSite *bp) -> void {
2284 if (error.Fail())
2285 return;
2286
2287 addr_t intersect_addr;
2288 size_t intersect_size;
2289 size_t opcode_offset;
2290 const bool intersects = bp->IntersectsRange(
2291 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2292 UNUSED_IF_ASSERT_DISABLED(intersects);
2293 assert(intersects);
2294 assert(addr <= intersect_addr && intersect_addr < addr + size);
2295 assert(addr < intersect_addr + intersect_size &&
2296 intersect_addr + intersect_size <= addr + size);
2297 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2298
2299 // Check for bytes before this breakpoint
2300 const addr_t curr_addr = addr + bytes_written;
2301 if (intersect_addr > curr_addr) {
2302 // There are some bytes before this breakpoint that we need to just
2303 // write to memory
2304 size_t curr_size = intersect_addr - curr_addr;
2305 size_t curr_bytes_written =
2306 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2307 bytes_written += curr_bytes_written;
2308 if (curr_bytes_written != curr_size) {
2309 // We weren't able to write all of the requested bytes, we are
2310 // done looping and will return the number of bytes that we have
2311 // written so far.
2312 if (error.Success())
2313 error.SetErrorToGenericError();
2314 }
2315 }
2316 // Now write any bytes that would cover up any software breakpoints
2317 // directly into the breakpoint opcode buffer
2318 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2319 intersect_size);
2320 bytes_written += intersect_size;
2321 });
Kate Stoneb9c1b512016-09-06 20:57:50 +00002322
2323 // Write any remaining bytes after the last breakpoint if we have any left
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002324 if (bytes_written < size)
2325 bytes_written +=
2326 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2327 size - bytes_written, error);
2328
2329 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002331
Kate Stoneb9c1b512016-09-06 20:57:50 +00002332size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002333 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002334 if (byte_size == UINT32_MAX)
2335 byte_size = scalar.GetByteSize();
2336 if (byte_size > 0) {
2337 uint8_t buf[32];
2338 const size_t mem_size =
2339 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2340 if (mem_size > 0)
2341 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002342 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002343 error.SetErrorString("failed to get scalar as memory data");
2344 } else {
2345 error.SetErrorString("invalid scalar value");
2346 }
2347 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002348}
2349
Kate Stoneb9c1b512016-09-06 20:57:50 +00002350size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2351 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002352 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002353 uint64_t uval = 0;
2354 if (byte_size == 0) {
2355 error.SetErrorString("byte size is zero");
2356 } else if (byte_size & (byte_size - 1)) {
2357 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2358 byte_size);
2359 } else if (byte_size <= sizeof(uval)) {
2360 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2361 if (bytes_read == byte_size) {
2362 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2363 GetAddressByteSize());
2364 lldb::offset_t offset = 0;
2365 if (byte_size <= 4)
2366 scalar = data.GetMaxU32(&offset, byte_size);
2367 else
2368 scalar = data.GetMaxU64(&offset, byte_size);
2369 if (is_signed)
2370 scalar.SignExtend(byte_size * 8);
2371 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002372 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002373 } else {
2374 error.SetErrorStringWithFormat(
2375 "byte size of %u is too large for integer scalar type", byte_size);
2376 }
2377 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002378}
2379
Pavel Labath16064d32018-03-20 11:56:24 +00002380Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2381 Status error;
2382 for (const auto &Entry : entries) {
2383 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2384 error);
2385 if (!error.Success())
2386 break;
2387 }
2388 return error;
2389}
2390
Greg Claytond495c532011-05-17 03:37:42 +00002391#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002392addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002393 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002394 if (GetPrivateState() != eStateStopped) {
2395 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002396 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002397 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002398
2399#if defined(USE_ALLOCATE_MEMORY_CACHE)
2400 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002401#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2403 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002404 LLDB_LOGF(log,
2405 "Process::AllocateMemory(size=%" PRIu64
2406 ", permissions=%s) => 0x%16.16" PRIx64
2407 " (m_stop_id = %u m_memory_id = %u)",
2408 (uint64_t)size, GetPermissionsAsCString(permissions),
2409 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2410 m_mod_id.GetMemoryID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002411 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002412#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413}
2414
Kate Stoneb9c1b512016-09-06 20:57:50 +00002415addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002416 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002417 addr_t return_addr = AllocateMemory(size, permissions, error);
2418 if (error.Success()) {
2419 std::string buffer(size, 0);
2420 WriteMemory(return_addr, buffer.c_str(), size, error);
2421 }
2422 return return_addr;
2423}
2424
2425bool Process::CanJIT() {
2426 if (m_can_jit == eCanJITDontKnow) {
2427 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002428 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002429
2430 uint64_t allocated_memory = AllocateMemory(
2431 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2432 err);
2433
2434 if (err.Success()) {
2435 m_can_jit = eCanJITYes;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002436 LLDB_LOGF(log,
2437 "Process::%s pid %" PRIu64
2438 " allocation test passed, CanJIT () is true",
2439 __FUNCTION__, GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002440 } else {
2441 m_can_jit = eCanJITNo;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002442 LLDB_LOGF(log,
2443 "Process::%s pid %" PRIu64
2444 " allocation test failed, CanJIT () is false: %s",
2445 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002446 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447
2448 DeallocateMemory(allocated_memory);
2449 }
2450
2451 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002452}
2453
Kate Stoneb9c1b512016-09-06 20:57:50 +00002454void Process::SetCanJIT(bool can_jit) {
2455 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002456}
2457
Kate Stoneb9c1b512016-09-06 20:57:50 +00002458void Process::SetCanRunCode(bool can_run_code) {
2459 SetCanJIT(can_run_code);
2460 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002461}
2462
Zachary Turner97206d52017-05-12 04:51:55 +00002463Status Process::DeallocateMemory(addr_t ptr) {
2464 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002465#if defined(USE_ALLOCATE_MEMORY_CACHE)
2466 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2467 error.SetErrorStringWithFormat(
2468 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2469 }
Greg Claytond495c532011-05-17 03:37:42 +00002470#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002471 error = DoDeallocateMemory(ptr);
2472
2473 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002474 LLDB_LOGF(log,
2475 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2476 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2477 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2478 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002479#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002480 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002481}
2482
Kate Stoneb9c1b512016-09-06 20:57:50 +00002483ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2484 lldb::addr_t header_addr,
2485 size_t size_to_read) {
2486 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2487 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002488 LLDB_LOGF(log,
2489 "Process::ReadModuleFromMemory reading %s binary from memory",
2490 file_spec.GetPath().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002491 }
2492 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2493 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002494 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002495 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2496 shared_from_this(), header_addr, error, size_to_read);
2497 if (objfile)
2498 return module_sp;
2499 }
2500 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501}
2502
Kate Stoneb9c1b512016-09-06 20:57:50 +00002503bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2504 uint32_t &permissions) {
2505 MemoryRegionInfo range_info;
2506 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002507 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002508 if (!error.Success())
2509 return false;
2510 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2511 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2512 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2513 return false;
2514 }
2515
2516 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2517 permissions |= lldb::ePermissionsReadable;
2518
2519 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2520 permissions |= lldb::ePermissionsWritable;
2521
2522 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2523 permissions |= lldb::ePermissionsExecutable;
2524
2525 return true;
2526}
2527
Zachary Turner97206d52017-05-12 04:51:55 +00002528Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2529 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002530 error.SetErrorString("watchpoints are not supported");
2531 return error;
2532}
2533
Zachary Turner97206d52017-05-12 04:51:55 +00002534Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2535 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002536 error.SetErrorString("watchpoints are not supported");
2537 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002538}
2539
2540StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002541Process::WaitForProcessStopPrivate(EventSP &event_sp,
2542 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002543 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002544
Kate Stoneb9c1b512016-09-06 20:57:50 +00002545 while (true) {
2546 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002547 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002548
Kate Stoneb9c1b512016-09-06 20:57:50 +00002549 if (StateIsStoppedState(state, false))
2550 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002551
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552 // If state is invalid, then we timed out
2553 if (state == eStateInvalid)
2554 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002555
Kate Stoneb9c1b512016-09-06 20:57:50 +00002556 if (event_sp)
2557 HandlePrivateEvent(event_sp);
2558 }
2559 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002560}
2561
Kate Stoneb9c1b512016-09-06 20:57:50 +00002562void Process::LoadOperatingSystemPlugin(bool flush) {
2563 if (flush)
2564 m_thread_list.Clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002565 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002566 if (flush)
2567 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002568}
2569
Zachary Turner97206d52017-05-12 04:51:55 +00002570Status Process::Launch(ProcessLaunchInfo &launch_info) {
2571 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002572 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002573 m_dyld_up.reset();
2574 m_jit_loaders_up.reset();
2575 m_system_runtime_up.reset();
2576 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002577 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002578
Kate Stoneb9c1b512016-09-06 20:57:50 +00002579 Module *exe_module = GetTarget().GetExecutableModulePointer();
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002580 if (!exe_module) {
2581 error.SetErrorString("executable module does not exist");
2582 return error;
2583 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002584
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002585 char local_exec_file_path[PATH_MAX];
2586 char platform_exec_file_path[PATH_MAX];
2587 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2588 sizeof(local_exec_file_path));
2589 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2590 sizeof(platform_exec_file_path));
2591 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2592 // Install anything that might need to be installed prior to launching.
2593 // For host systems, this will do nothing, but if we are connected to a
2594 // remote platform it will install any needed binaries
2595 error = GetTarget().Install(&launch_info);
2596 if (error.Fail())
2597 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002598
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002599 if (PrivateStateThreadIsValid())
2600 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002601
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002602 error = WillLaunch(exe_module);
2603 if (error.Success()) {
2604 const bool restarted = false;
2605 SetPublicState(eStateLaunching, restarted);
2606 m_should_detach = false;
2607
2608 if (m_public_run_lock.TrySetRunning()) {
2609 // Now launch using these arguments.
2610 error = DoLaunch(exe_module, launch_info);
2611 } else {
2612 // This shouldn't happen
2613 error.SetErrorString("failed to acquire process run lock");
2614 }
2615
2616 if (error.Fail()) {
2617 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2618 SetID(LLDB_INVALID_PROCESS_ID);
2619 const char *error_string = error.AsCString();
2620 if (error_string == nullptr)
2621 error_string = "launch failed";
2622 SetExitStatus(-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002623 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002624 } else {
2625 EventSP event_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002626
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002627 // Now wait for the process to launch and return control to us, and then
2628 // call DidLaunch:
2629 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Stella Stamenova36d457c2018-06-01 19:14:53 +00002630
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002631 if (state == eStateInvalid || !event_sp) {
2632 // We were able to launch the process, but we failed to catch the
2633 // initial stop.
2634 error.SetErrorString("failed to catch stop after launch");
2635 SetExitStatus(0, "failed to catch stop after launch");
2636 Destroy(false);
2637 } else if (state == eStateStopped || state == eStateCrashed) {
2638 DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002639
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002640 DynamicLoader *dyld = GetDynamicLoader();
2641 if (dyld)
2642 dyld->DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002643
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002644 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002645
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002646 SystemRuntime *system_runtime = GetSystemRuntime();
2647 if (system_runtime)
2648 system_runtime->DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002649
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002650 if (!m_os_up)
2651 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002652
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002653 // We successfully launched the process and stopped, now it the
2654 // right time to set up signal filters before resuming.
2655 UpdateAutomaticSignalFiltering();
Greg Clayton35824e32015-02-20 20:59:47 +00002656
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002657 // Note, the stop event was consumed above, but not handled. This
2658 // was done to give DidLaunch a chance to run. The target is either
2659 // stopped or crashed. Directly set the state. This is done to
2660 // prevent a stop message with a bunch of spurious output on thread
2661 // status, as well as not pop a ProcessIOHandler.
2662 SetPublicState(state, false);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002663
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002664 if (PrivateStateThreadIsValid())
2665 ResumePrivateStateThread();
2666 else
2667 StartPrivateStateThread();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002668
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002669 // Target was stopped at entry as was intended. Need to notify the
2670 // listeners about it.
2671 if (state == eStateStopped &&
2672 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002673 HandlePrivateEvent(event_sp);
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002674 } else if (state == eStateExited) {
2675 // We exited while trying to launch somehow. Don't call DidLaunch
2676 // as that's not likely to work, and return an invalid pid.
2677 HandlePrivateEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002678 }
2679 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002680 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002681 } else {
2682 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2683 local_exec_file_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002684 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002685
Kate Stoneb9c1b512016-09-06 20:57:50 +00002686 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002687}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002688
Zachary Turner97206d52017-05-12 04:51:55 +00002689Status Process::LoadCore() {
2690 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002691 if (error.Success()) {
2692 ListenerSP listener_sp(
2693 Listener::MakeListener("lldb.process.load_core_listener"));
2694 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002695
Kate Stoneb9c1b512016-09-06 20:57:50 +00002696 if (PrivateStateThreadIsValid())
2697 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002698 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002699 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002700
Kate Stoneb9c1b512016-09-06 20:57:50 +00002701 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002702 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002703 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002704
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002705 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002706
Kate Stoneb9c1b512016-09-06 20:57:50 +00002707 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002708 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002709 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002710
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002711 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00002712 LoadOperatingSystemPlugin(false);
2713
Kate Stoneb9c1b512016-09-06 20:57:50 +00002714 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002715 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002716 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002717
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002718 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002719 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002720 StateType state =
Pavel Labath7ada1c52019-06-25 07:14:29 +00002721 WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002722
2723 if (!StateIsStoppedState(state, false)) {
2724 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002725 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2726 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002727 error.SetErrorString(
2728 "Did not get stopped event after loading the core file.");
2729 }
2730 RestoreProcessEvents();
2731 }
2732 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002733}
2734
Kate Stoneb9c1b512016-09-06 20:57:50 +00002735DynamicLoader *Process::GetDynamicLoader() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002736 if (!m_dyld_up)
2737 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2738 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002739}
2740
Antonio Afonso943faef2019-06-11 20:16:13 +00002741DataExtractor Process::GetAuxvData() { return DataExtractor(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742
2743JITLoaderList &Process::GetJITLoaders() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002744 if (!m_jit_loaders_up) {
2745 m_jit_loaders_up.reset(new JITLoaderList());
2746 JITLoader::LoadPlugins(this, *m_jit_loaders_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002747 }
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002748 return *m_jit_loaders_up;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749}
2750
2751SystemRuntime *Process::GetSystemRuntime() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002752 if (!m_system_runtime_up)
2753 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2754 return m_system_runtime_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002755}
2756
2757Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2758 uint32_t exec_count)
2759 : NextEventAction(process), m_exec_count(exec_count) {
2760 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002761 LLDB_LOGF(
2762 log,
2763 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2764 __FUNCTION__, static_cast<void *>(process), exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002765}
2766
2767Process::NextEventAction::EventActionResult
2768Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2769 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2770
2771 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002772 LLDB_LOGF(log,
2773 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2774 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002775
2776 switch (state) {
2777 case eStateAttaching:
2778 return eEventActionSuccess;
2779
2780 case eStateRunning:
2781 case eStateConnected:
2782 return eEventActionRetry;
2783
2784 case eStateStopped:
2785 case eStateCrashed:
2786 // During attach, prior to sending the eStateStopped event,
2787 // lldb_private::Process subclasses must set the new process ID.
2788 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002789 // We don't want these events to be reported, so go set the
2790 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2792
2793 if (m_exec_count > 0) {
2794 --m_exec_count;
2795
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002796 LLDB_LOGF(log,
2797 "Process::AttachCompletionHandler::%s state %s: reduced "
2798 "remaining exec count to %" PRIu32 ", requesting resume",
2799 __FUNCTION__, StateAsCString(state), m_exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800
2801 RequestResume();
2802 return eEventActionRetry;
2803 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002804 LLDB_LOGF(log,
2805 "Process::AttachCompletionHandler::%s state %s: no more "
2806 "execs expected to start, continuing with attach",
2807 __FUNCTION__, StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002808
2809 m_process->CompleteAttach();
2810 return eEventActionSuccess;
2811 }
2812 break;
2813
2814 default:
2815 case eStateExited:
2816 case eStateInvalid:
2817 break;
2818 }
2819
2820 m_exit_string.assign("No valid Process");
2821 return eEventActionExit;
2822}
2823
2824Process::NextEventAction::EventActionResult
2825Process::AttachCompletionHandler::HandleBeingInterrupted() {
2826 return eEventActionSuccess;
2827}
2828
2829const char *Process::AttachCompletionHandler::GetExitString() {
2830 return m_exit_string.c_str();
2831}
2832
2833ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2834 if (m_listener_sp)
2835 return m_listener_sp;
2836 else
2837 return debugger.GetListener();
2838}
2839
Zachary Turner97206d52017-05-12 04:51:55 +00002840Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 m_abi_sp.reset();
2842 m_process_input_reader.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002843 m_dyld_up.reset();
2844 m_jit_loaders_up.reset();
2845 m_system_runtime_up.reset();
2846 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002847
2848 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002849 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002850 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2851 char process_name[PATH_MAX];
2852
2853 if (attach_info.GetExecutableFile().GetPath(process_name,
2854 sizeof(process_name))) {
2855 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2856
2857 if (wait_for_launch) {
2858 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2859 if (error.Success()) {
2860 if (m_public_run_lock.TrySetRunning()) {
2861 m_should_detach = true;
2862 const bool restarted = false;
2863 SetPublicState(eStateAttaching, restarted);
2864 // Now attach using these arguments.
2865 error = DoAttachToProcessWithName(process_name, attach_info);
2866 } else {
2867 // This shouldn't happen
2868 error.SetErrorString("failed to acquire process run lock");
2869 }
2870
2871 if (error.Fail()) {
2872 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2873 SetID(LLDB_INVALID_PROCESS_ID);
2874 if (error.AsCString() == nullptr)
2875 error.SetErrorString("attach failed");
2876
2877 SetExitStatus(-1, error.AsCString());
2878 }
2879 } else {
2880 SetNextEventAction(new Process::AttachCompletionHandler(
2881 this, attach_info.GetResumeCount()));
2882 StartPrivateStateThread();
2883 }
2884 return error;
2885 }
2886 } else {
2887 ProcessInstanceInfoList process_infos;
2888 PlatformSP platform_sp(GetTarget().GetPlatform());
2889
2890 if (platform_sp) {
2891 ProcessInstanceInfoMatch match_info;
2892 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00002893 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002894 platform_sp->FindProcesses(match_info, process_infos);
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002895 const uint32_t num_matches = process_infos.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002896 if (num_matches == 1) {
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002897 attach_pid = process_infos[0].GetProcessID();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002898 // Fall through and attach using the above process ID
2899 } else {
2900 match_info.GetProcessInfo().GetExecutableFile().GetPath(
2901 process_name, sizeof(process_name));
2902 if (num_matches > 1) {
2903 StreamString s;
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002904 ProcessInstanceInfo::DumpTableHeader(s, true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002905 for (size_t i = 0; i < num_matches; i++) {
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002906 process_infos[i].DumpAsTableRow(
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002907 s, platform_sp->GetUserIDResolver(), true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002908 }
2909 error.SetErrorStringWithFormat(
2910 "more than one process named %s:\n%s", process_name,
2911 s.GetData());
2912 } else
2913 error.SetErrorStringWithFormat(
2914 "could not find a process named %s", process_name);
2915 }
2916 } else {
2917 error.SetErrorString(
2918 "invalid platform, can't find processes by name");
2919 return error;
2920 }
2921 }
2922 } else {
2923 error.SetErrorString("invalid process name");
2924 }
2925 }
2926
2927 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2928 error = WillAttachToProcessWithID(attach_pid);
2929 if (error.Success()) {
2930
2931 if (m_public_run_lock.TrySetRunning()) {
2932 // Now attach using these arguments.
2933 m_should_detach = true;
2934 const bool restarted = false;
2935 SetPublicState(eStateAttaching, restarted);
2936 error = DoAttachToProcessWithID(attach_pid, attach_info);
2937 } else {
2938 // This shouldn't happen
2939 error.SetErrorString("failed to acquire process run lock");
2940 }
2941
2942 if (error.Success()) {
2943 SetNextEventAction(new Process::AttachCompletionHandler(
2944 this, attach_info.GetResumeCount()));
2945 StartPrivateStateThread();
2946 } else {
Greg Clayton71337622011-02-24 22:24:29 +00002947 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002949
Kate Stoneb9c1b512016-09-06 20:57:50 +00002950 const char *error_string = error.AsCString();
2951 if (error_string == nullptr)
2952 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00002953
Kate Stoneb9c1b512016-09-06 20:57:50 +00002954 SetExitStatus(-1, error_string);
2955 }
Greg Claytonb766a732011-02-04 01:58:07 +00002956 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002957 }
2958 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00002959}
2960
Kate Stoneb9c1b512016-09-06 20:57:50 +00002961void Process::CompleteAttach() {
2962 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2963 LIBLLDB_LOG_TARGET));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002964 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002965
2966 // Let the process subclass figure out at much as it can about the process
2967 // before we go looking for a dynamic loader plug-in.
2968 ArchSpec process_arch;
2969 DidAttach(process_arch);
2970
2971 if (process_arch.IsValid()) {
2972 GetTarget().SetArchitecture(process_arch);
2973 if (log) {
2974 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002975 LLDB_LOGF(log,
2976 "Process::%s replacing process architecture with DidAttach() "
2977 "architecture: %s",
2978 __FUNCTION__, triple_str ? triple_str : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002979 }
2980 }
2981
2982 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00002983 // architecture, and if it isn't the same as the one we've already set,
2984 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002985 PlatformSP platform_sp(GetTarget().GetPlatform());
2986 assert(platform_sp);
2987 if (platform_sp) {
2988 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2989 if (target_arch.IsValid() &&
2990 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2991 ArchSpec platform_arch;
2992 platform_sp =
2993 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2994 if (platform_sp) {
2995 GetTarget().SetPlatform(platform_sp);
2996 GetTarget().SetArchitecture(platform_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002997 LLDB_LOGF(log,
2998 "Process::%s switching platform to %s and architecture "
2999 "to %s based on info from attach",
3000 __FUNCTION__, platform_sp->GetName().AsCString(""),
3001 platform_arch.GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003002 }
3003 } else if (!process_arch.IsValid()) {
3004 ProcessInstanceInfo process_info;
3005 GetProcessInfo(process_info);
3006 const ArchSpec &process_arch = process_info.GetArchitecture();
3007 if (process_arch.IsValid() &&
3008 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3009 GetTarget().SetArchitecture(process_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003010 LLDB_LOGF(log,
3011 "Process::%s switching architecture to %s based on info "
3012 "the platform retrieved for pid %" PRIu64,
3013 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
3014 GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003015 }
3016 }
3017 }
3018
3019 // We have completed the attach, now it is time to find the dynamic loader
3020 // plug-in
3021 DynamicLoader *dyld = GetDynamicLoader();
3022 if (dyld) {
3023 dyld->DidAttach();
3024 if (log) {
3025 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003026 LLDB_LOGF(log,
3027 "Process::%s after DynamicLoader::DidAttach(), target "
3028 "executable is %s (using %s plugin)",
3029 __FUNCTION__,
3030 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3031 : "<none>",
3032 dyld->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003033 }
3034 }
3035
3036 GetJITLoaders().DidAttach();
3037
3038 SystemRuntime *system_runtime = GetSystemRuntime();
3039 if (system_runtime) {
3040 system_runtime->DidAttach();
3041 if (log) {
3042 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003043 LLDB_LOGF(log,
3044 "Process::%s after SystemRuntime::DidAttach(), target "
3045 "executable is %s (using %s plugin)",
3046 __FUNCTION__,
3047 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3048 : "<none>",
3049 system_runtime->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003050 }
3051 }
3052
Jim Ingham8864b432019-06-28 17:57:19 +00003053 if (!m_os_up) {
Greg Clayton29eeea02017-02-09 18:55:41 +00003054 LoadOperatingSystemPlugin(false);
Jim Ingham8864b432019-06-28 17:57:19 +00003055 if (m_os_up) {
3056 // Somebody might have gotten threads before now, but we need to force the
3057 // update after we've loaded the OperatingSystem plugin or it won't get a
3058 // chance to process the threads.
3059 m_thread_list.Clear();
3060 UpdateThreadListIfNeeded();
3061 }
3062 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003063 // Figure out which one is the executable, and set that in our target:
3064 const ModuleList &target_modules = GetTarget().GetImages();
3065 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3066 size_t num_modules = target_modules.GetSize();
3067 ModuleSP new_executable_module_sp;
3068
3069 for (size_t i = 0; i < num_modules; i++) {
3070 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3071 if (module_sp && module_sp->IsExecutable()) {
3072 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3073 new_executable_module_sp = module_sp;
3074 break;
3075 }
3076 }
3077 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00003078 GetTarget().SetExecutableModule(new_executable_module_sp,
3079 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003080 if (log) {
3081 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003082 LLDB_LOGF(
3083 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003084 "Process::%s after looping through modules, target executable is %s",
3085 __FUNCTION__,
3086 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3087 : "<none>");
3088 }
3089 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003090}
3091
Zachary Turner97206d52017-05-12 04:51:55 +00003092Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 m_abi_sp.reset();
3094 m_process_input_reader.reset();
3095
3096 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003097 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003098
Zachary Turner97206d52017-05-12 04:51:55 +00003099 Status error(DoConnectRemote(strm, remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003100 if (error.Success()) {
3101 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3102 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003103 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003104
3105 if (state == eStateStopped || state == eStateCrashed) {
3106 // If we attached and actually have a process on the other end, then
3107 // this ended up being the equivalent of an attach.
3108 CompleteAttach();
3109
3110 // This delays passing the stopped event to listeners till
3111 // CompleteAttach gets a chance to complete...
3112 HandlePrivateEvent(event_sp);
3113 }
3114 }
3115
3116 if (PrivateStateThreadIsValid())
3117 ResumePrivateStateThread();
3118 else
3119 StartPrivateStateThread();
3120 }
3121 return error;
3122}
3123
Zachary Turner97206d52017-05-12 04:51:55 +00003124Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003125 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3126 LIBLLDB_LOG_STEP));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003127 LLDB_LOGF(log,
3128 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3129 "private state: %s",
3130 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3131 StateAsCString(m_private_state.GetValue()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003132
Adrian Prantl05097242018-04-30 16:49:04 +00003133 // If signals handing status changed we might want to update our signal
3134 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003135 UpdateAutomaticSignalFiltering();
3136
Zachary Turner97206d52017-05-12 04:51:55 +00003137 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003138 // Tell the process it is about to resume before the thread list
3139 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003140 // Now let the thread list know we are about to resume so it can let all of
3141 // our threads know that they are about to be resumed. Threads will each be
3142 // called with Thread::WillResume(StateType) where StateType contains the
3143 // state that they are supposed to have when the process is resumed
3144 // (suspended/running/stepping). Threads should also check their resume
3145 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3146 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003147 if (m_thread_list.WillResume()) {
3148 // Last thing, do the PreResumeActions.
3149 if (!RunPreResumeActions()) {
3150 error.SetErrorStringWithFormat(
3151 "Process::PrivateResume PreResumeActions failed, not resuming.");
3152 } else {
3153 m_mod_id.BumpResumeID();
3154 error = DoResume();
3155 if (error.Success()) {
3156 DidResume();
3157 m_thread_list.DidResume();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003158 LLDB_LOGF(log, "Process thinks the process has resumed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003159 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003160 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003161 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003162 }
3163 }
3164 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003165 // Somebody wanted to run without running (e.g. we were faking a step
3166 // from one frame of a set of inlined frames that share the same PC to
3167 // another.) So generate a continue & a stopped event, and let the world
3168 // handle them.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003169 LLDB_LOGF(log,
3170 "Process::PrivateResume() asked to simulate a start & stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003171
3172 SetPrivateState(eStateRunning);
3173 SetPrivateState(eStateStopped);
3174 }
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003175 } else
3176 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3177 error.AsCString("<unknown error>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003178 return error;
3179}
3180
Zachary Turner97206d52017-05-12 04:51:55 +00003181Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003182 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003183 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003184
Adrian Prantl05097242018-04-30 16:49:04 +00003185 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3186 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003187 m_clear_thread_plans_on_stop |= clear_thread_plans;
3188
3189 ListenerSP halt_listener_sp(
3190 Listener::MakeListener("lldb.process.halt_listener"));
3191 HijackProcessEvents(halt_listener_sp);
3192
3193 EventSP event_sp;
3194
3195 SendAsyncInterrupt();
3196
3197 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003198 // Don't hijack and eat the eStateExited as the code that was doing the
3199 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003200 RestoreProcessEvents();
3201 SetExitStatus(SIGKILL, "Cancelled async attach.");
3202 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003203 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003204 }
3205
3206 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003207 StateType state = WaitForProcessToStop(
3208 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003209 RestoreProcessEvents();
3210
3211 if (state == eStateInvalid || !event_sp) {
3212 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003213 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003214 }
3215
3216 BroadcastEvent(event_sp);
3217
Zachary Turner97206d52017-05-12 04:51:55 +00003218 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003219}
3220
Zachary Turner97206d52017-05-12 04:51:55 +00003221Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3222 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003223
3224 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003225 // expression, for instance, then the public state will be stopped, but we
3226 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003227 if (m_public_state.GetValue() == eStateRunning ||
3228 m_private_state.GetValue() == eStateRunning) {
3229 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003230 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003231
Kate Stoneb9c1b512016-09-06 20:57:50 +00003232 ListenerSP listener_sp(
3233 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3234 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003235
Pavel Labath19da1f12015-12-07 12:36:52 +00003236 SendAsyncInterrupt();
3237
Kate Stoneb9c1b512016-09-06 20:57:50 +00003238 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003239 StateType state =
3240 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003241
Pavel Labath19da1f12015-12-07 12:36:52 +00003242 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003243
Kate Stoneb9c1b512016-09-06 20:57:50 +00003244 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003245 // exited event into the shared pointer passed in and return. Our caller
3246 // doesn't need to do anything else, since they don't have a process
3247 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003248
3249 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003250 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3251 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003252 return error;
3253 } else
3254 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3255
3256 if (state != eStateStopped) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003257 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3258 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003259 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003260 // here, but if the lower levels just bobbled sending the event and we
3261 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003262 StateType private_state = m_private_state.GetValue();
3263 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003264 return Status(
3265 "Attempt to stop the target in order to detach timed out. "
3266 "State = %s",
3267 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003268 }
3269 }
3270 }
3271 return error;
3272}
3273
Zachary Turner97206d52017-05-12 04:51:55 +00003274Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003275 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003276 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003277 m_destroy_in_process = true;
3278
3279 error = WillDetach();
3280
3281 if (error.Success()) {
3282 if (DetachRequiresHalt()) {
3283 error = StopForDestroyOrDetach(exit_event_sp);
3284 if (!error.Success()) {
3285 m_destroy_in_process = false;
3286 return error;
3287 } else if (exit_event_sp) {
3288 // We shouldn't need to do anything else here. There's no process left
3289 // to detach from...
3290 StopPrivateStateThread();
3291 m_destroy_in_process = false;
3292 return error;
3293 }
3294 }
3295
3296 m_thread_list.DiscardThreadPlans();
3297 DisableAllBreakpointSites();
3298
3299 error = DoDetach(keep_stopped);
3300 if (error.Success()) {
3301 DidDetach();
3302 StopPrivateStateThread();
3303 } else {
3304 return error;
3305 }
3306 }
3307 m_destroy_in_process = false;
3308
Adrian Prantl05097242018-04-30 16:49:04 +00003309 // If we exited when we were waiting for a process to stop, then forward the
3310 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003311 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003312 // Directly broadcast our exited event because we shut down our private
3313 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003314 BroadcastEvent(exit_event_sp);
3315 }
3316
3317 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003318 // not end up propagating the last events through the event system, in which
3319 // case we might strand the write lock. Unlock it here so when we do to tear
3320 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003321
3322 m_public_run_lock.SetStopped();
3323 return error;
3324}
3325
Zachary Turner97206d52017-05-12 04:51:55 +00003326Status Process::Destroy(bool force_kill) {
Jim Ingham61e8e682020-03-10 16:18:11 -07003327 // If we've already called Process::Finalize then there's nothing useful to
3328 // be done here. Finalize has actually called Destroy already.
3329 if (m_finalize_called)
3330 return {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003331
3332 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003333 // don't do any unnecessary work that might hinder the destruction. Remember
3334 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003335 // failed and the process stays around for some reason it won't be in a
3336 // confused state.
3337
3338 if (force_kill)
3339 m_should_detach = false;
3340
3341 if (GetShouldDetach()) {
3342 // FIXME: This will have to be a process setting:
3343 bool keep_stopped = false;
3344 Detach(keep_stopped);
3345 }
3346
3347 m_destroy_in_process = true;
3348
Zachary Turner97206d52017-05-12 04:51:55 +00003349 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003350 if (error.Success()) {
3351 EventSP exit_event_sp;
3352 if (DestroyRequiresHalt()) {
3353 error = StopForDestroyOrDetach(exit_event_sp);
3354 }
3355
3356 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003357 // Ditch all thread plans, and remove all our breakpoints: in case we
3358 // have to restart the target to kill it, we don't want it hitting a
3359 // breakpoint... Only do this if we've stopped, however, since if we
3360 // didn't manage to halt it above, then we're not going to have much luck
3361 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003362 m_thread_list.DiscardThreadPlans();
3363 DisableAllBreakpointSites();
3364 }
3365
3366 error = DoDestroy();
3367 if (error.Success()) {
3368 DidDestroy();
3369 StopPrivateStateThread();
3370 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003371 m_stdio_communication.StopReadThread();
Pavel Labath93212552020-04-23 16:27:01 +02003372 m_stdio_communication.Disconnect();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003373 m_stdin_forward = false;
3374
3375 if (m_process_input_reader) {
3376 m_process_input_reader->SetIsDone(true);
3377 m_process_input_reader->Cancel();
3378 m_process_input_reader.reset();
3379 }
3380
Adrian Prantl05097242018-04-30 16:49:04 +00003381 // If we exited when we were waiting for a process to stop, then forward
3382 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003383 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003384 // Directly broadcast our exited event because we shut down our private
3385 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003386 BroadcastEvent(exit_event_sp);
3387 }
3388
Adrian Prantl05097242018-04-30 16:49:04 +00003389 // If we have been interrupted (to kill us) in the middle of running, we
3390 // may not end up propagating the last events through the event system, in
3391 // which case we might strand the write lock. Unlock it here so when we do
3392 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003393 m_public_run_lock.SetStopped();
3394 }
3395
3396 m_destroy_in_process = false;
3397
3398 return error;
3399}
3400
Zachary Turner97206d52017-05-12 04:51:55 +00003401Status Process::Signal(int signal) {
3402 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003403 if (error.Success()) {
3404 error = DoSignal(signal);
3405 if (error.Success())
3406 DidSignal();
3407 }
3408 return error;
3409}
3410
3411void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3412 assert(signals_sp && "null signals_sp");
3413 m_unix_signals_sp = signals_sp;
3414}
3415
3416const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3417 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3418 return m_unix_signals_sp;
3419}
3420
3421lldb::ByteOrder Process::GetByteOrder() const {
3422 return GetTarget().GetArchitecture().GetByteOrder();
3423}
3424
3425uint32_t Process::GetAddressByteSize() const {
3426 return GetTarget().GetArchitecture().GetAddressByteSize();
3427}
3428
3429bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3430 const StateType state =
3431 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3432 bool return_value = true;
3433 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3434 LIBLLDB_LOG_PROCESS));
3435
3436 switch (state) {
3437 case eStateDetached:
3438 case eStateExited:
3439 case eStateUnloaded:
3440 m_stdio_communication.SynchronizeWithReadThread();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003441 m_stdio_communication.StopReadThread();
Jonas Devlieghereb424b0b2020-04-22 16:51:56 -07003442 m_stdio_communication.Disconnect();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003443 m_stdin_forward = false;
3444
3445 LLVM_FALLTHROUGH;
3446 case eStateConnected:
3447 case eStateAttaching:
3448 case eStateLaunching:
3449 // These events indicate changes in the state of the debugging session,
3450 // always report them.
3451 return_value = true;
3452 break;
3453 case eStateInvalid:
3454 // We stopped for no apparent reason, don't report it.
3455 return_value = false;
3456 break;
3457 case eStateRunning:
3458 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003459 // If we've started the target running, we handle the cases where we are
3460 // already running and where there is a transition from stopped to running
3461 // differently. running -> running: Automatically suppress extra running
3462 // events stopped -> running: Report except when there is one or more no
3463 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003464 // and no yes votes.
3465 SynchronouslyNotifyStateChanged(state);
3466 if (m_force_next_event_delivery)
3467 return_value = true;
3468 else {
3469 switch (m_last_broadcast_state) {
3470 case eStateRunning:
3471 case eStateStepping:
3472 // We always suppress multiple runnings with no PUBLIC stop in between.
3473 return_value = false;
3474 break;
3475 default:
3476 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003477 // run if we aren't running so we don't miss any running events. If I
3478 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3479 // and hit the breakpoints on multiple threads, then somehow during the
3480 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003481
3482 // This is a transition from stop to run.
3483 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3484 case eVoteYes:
3485 case eVoteNoOpinion:
3486 return_value = true;
3487 break;
3488 case eVoteNo:
3489 return_value = false;
3490 break;
3491 }
3492 break;
3493 }
3494 }
3495 break;
3496 case eStateStopped:
3497 case eStateCrashed:
3498 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003499 // We've stopped. First see if we're going to restart the target. If we
3500 // are going to stop, then we always broadcast the event. If we aren't
3501 // going to stop, let the thread plans decide if we're going to report this
3502 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003503
3504 m_stdio_communication.SynchronizeWithReadThread();
3505 RefreshStateAfterStop();
3506 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003507 LLDB_LOGF(log,
3508 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3509 "interrupt, state: %s",
3510 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003511 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003512 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003513 m_thread_list.ShouldStop(event_ptr);
3514 return_value = true;
3515 } else {
3516 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3517 bool should_resume = false;
3518
3519 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003520 // restarted... Asking the thread list is also not likely to go well,
3521 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003522
3523 if (!was_restarted)
3524 should_resume = !m_thread_list.ShouldStop(event_ptr);
3525
3526 if (was_restarted || should_resume || m_resume_requested) {
3527 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003528 LLDB_LOGF(log,
3529 "Process::ShouldBroadcastEvent: should_resume: %i state: "
3530 "%s was_restarted: %i stop_vote: %d.",
3531 should_resume, StateAsCString(state), was_restarted,
3532 stop_vote);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003533
3534 switch (stop_vote) {
3535 case eVoteYes:
3536 return_value = true;
3537 break;
3538 case eVoteNoOpinion:
3539 case eVoteNo:
3540 return_value = false;
3541 break;
3542 }
3543
3544 if (!was_restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003545 LLDB_LOGF(log,
3546 "Process::ShouldBroadcastEvent (%p) Restarting process "
3547 "from state: %s",
3548 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003549 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3550 PrivateResume();
3551 }
3552 } else {
3553 return_value = true;
3554 SynchronouslyNotifyStateChanged(state);
3555 }
3556 }
3557 break;
3558 }
3559
3560 // Forcing the next event delivery is a one shot deal. So reset it here.
3561 m_force_next_event_delivery = false;
3562
3563 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003564 // events get coalesced.) But we only coalesce against events we actually
3565 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3566 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3567 // done, because the PublicState reflects the last event pulled off the
3568 // queue, and there may be several events stacked up on the queue unserviced.
3569 // So the PublicState may not reflect the last broadcasted event yet.
3570 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003571
3572 if (return_value)
3573 m_last_broadcast_state = state;
3574
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003575 LLDB_LOGF(log,
3576 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3577 "broadcast state: %s - %s",
3578 static_cast<void *>(event_ptr), StateAsCString(state),
3579 StateAsCString(m_last_broadcast_state),
3580 return_value ? "YES" : "NO");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003581 return return_value;
3582}
3583
3584bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3585 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3586
3587 bool already_running = PrivateStateThreadIsValid();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003588 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
3589 already_running ? " already running"
3590 : " starting private state thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003591
3592 if (!is_secondary_thread && already_running)
3593 return true;
3594
Adrian Prantl05097242018-04-30 16:49:04 +00003595 // Create a thread that watches our internal state and controls which events
3596 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003597 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003598 uint32_t max_len = llvm::get_max_thread_name_length();
3599 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003600 // On platforms with abbreviated thread name lengths, choose thread names
3601 // that fit within the limit.
3602 if (already_running)
3603 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3604 else
3605 snprintf(thread_name, sizeof(thread_name), "intern-state");
3606 } else {
3607 if (already_running)
3608 snprintf(thread_name, sizeof(thread_name),
3609 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3610 GetID());
3611 else
3612 snprintf(thread_name, sizeof(thread_name),
3613 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3614 }
3615
3616 // Create the private state thread, and start it running.
3617 PrivateStateThreadArgs *args_ptr =
3618 new PrivateStateThreadArgs(this, is_secondary_thread);
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003619 llvm::Expected<HostThread> private_state_thread =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003620 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003621 (void *)args_ptr, 8 * 1024 * 1024);
3622 if (!private_state_thread) {
3623 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3624 "failed to launch host thread: {}",
3625 llvm::toString(private_state_thread.takeError()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003626 return false;
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003627 }
3628
3629 assert(private_state_thread->IsJoinable());
3630 m_private_state_thread = *private_state_thread;
3631 ResumePrivateStateThread();
3632 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003633}
3634
3635void Process::PausePrivateStateThread() {
3636 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3637}
3638
3639void Process::ResumePrivateStateThread() {
3640 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3641}
3642
3643void Process::StopPrivateStateThread() {
3644 if (m_private_state_thread.IsJoinable())
3645 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3646 else {
3647 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003648 LLDB_LOGF(
3649 log,
3650 "Went to stop the private state thread, but it was already invalid.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003651 }
3652}
3653
3654void Process::ControlPrivateStateThread(uint32_t signal) {
3655 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3656
3657 assert(signal == eBroadcastInternalStateControlStop ||
3658 signal == eBroadcastInternalStateControlPause ||
3659 signal == eBroadcastInternalStateControlResume);
3660
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003661 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003662
3663 // Signal the private state thread
3664 if (m_private_state_thread.IsJoinable()) {
3665 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003666 // It is important to do this outside of the if below, because it's
3667 // possible that the thread state is invalid but that the thread is waiting
3668 // on a control event instead of simply being on its way out (this should
3669 // not happen, but it apparently can).
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003670 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003671 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3672 m_private_state_control_broadcaster.BroadcastEvent(signal,
3673 event_receipt_sp);
3674
3675 // Wait for the event receipt or for the private state thread to exit
3676 bool receipt_received = false;
3677 if (PrivateStateThreadIsValid()) {
3678 while (!receipt_received) {
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003679 // Check for a receipt for n seconds and then check if the private
Adrian Prantl05097242018-04-30 16:49:04 +00003680 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003681 receipt_received =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003682 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003683 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003684 // Check if the private state thread is still around. If it isn't
3685 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003686 if (!PrivateStateThreadIsValid())
3687 break; // Private state thread exited or is exiting, we are done
3688 }
3689 }
3690 }
3691
3692 if (signal == eBroadcastInternalStateControlStop) {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003693 thread_result_t result = {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003694 m_private_state_thread.Join(&result);
3695 m_private_state_thread.Reset();
3696 }
3697 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003698 LLDB_LOGF(
3699 log,
3700 "Private state thread already dead, no need to signal it to stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003701 }
3702}
3703
3704void Process::SendAsyncInterrupt() {
3705 if (PrivateStateThreadIsValid())
3706 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3707 nullptr);
3708 else
3709 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3710}
3711
3712void Process::HandlePrivateEvent(EventSP &event_sp) {
3713 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3714 m_resume_requested = false;
3715
3716 const StateType new_state =
3717 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3718
3719 // First check to see if anybody wants a shot at this event:
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003720 if (m_next_event_action_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003721 NextEventAction::EventActionResult action_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003722 m_next_event_action_up->PerformAction(event_sp);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003723 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003724
3725 switch (action_result) {
3726 case NextEventAction::eEventActionSuccess:
3727 SetNextEventAction(nullptr);
3728 break;
3729
3730 case NextEventAction::eEventActionRetry:
3731 break;
3732
3733 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003734 // Handle Exiting Here. If we already got an exited event, we should
3735 // just propagate it. Otherwise, swallow this event, and set our state
3736 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003737 if (new_state != eStateExited) {
3738 // FIXME: should cons up an exited event, and discard this one.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003739 SetExitStatus(0, m_next_event_action_up->GetExitString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003740 SetNextEventAction(nullptr);
3741 return;
3742 }
3743 SetNextEventAction(nullptr);
3744 break;
3745 }
3746 }
3747
3748 // See if we should broadcast this state to external clients?
3749 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3750
3751 if (should_broadcast) {
3752 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3753 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003754 LLDB_LOGF(log,
3755 "Process::%s (pid = %" PRIu64
3756 ") broadcasting new state %s (old state %s) to %s",
3757 __FUNCTION__, GetID(), StateAsCString(new_state),
3758 StateAsCString(GetState()),
3759 is_hijacked ? "hijacked" : "public");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003760 }
3761 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3762 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003763 // Only push the input handler if we aren't fowarding events, as this
3764 // means the curses GUI is in use... Or don't push it if we are launching
3765 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003766 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3767 new_state != eStateLaunching && new_state != eStateAttaching) {
3768 PushProcessIOHandler();
3769 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3770 eBroadcastAlways);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003771 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
3772 __FUNCTION__, m_iohandler_sync.GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003773 }
3774 } else if (StateIsStoppedState(new_state, false)) {
3775 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003776 // If the lldb_private::Debugger is handling the events, we don't want
3777 // to pop the process IOHandler here, we want to do it when we receive
3778 // the stopped event so we can carefully control when the process
3779 // IOHandler is popped because when we stop we want to display some
3780 // text stating how and why we stopped, then maybe some
3781 // process/thread/frame info, and then we want the "(lldb) " prompt to
3782 // show up. If we pop the process IOHandler here, then we will cause
3783 // the command interpreter to become the top IOHandler after the
3784 // process pops off and it will update its prompt right away... See the
3785 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003786 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3787 // Otherwise we end up getting overlapping "(lldb) " prompts and
3788 // garbled output.
3789 //
3790 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003791 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3792 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003793 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003794 // thread plans, or when commands want to run in synchronous mode and
3795 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003796 // that will hijack the events is a simple expression:
3797 //
3798 // (lldb) expr (int)puts("hello")
3799 //
3800 // This will cause the internal process state thread to resume and halt
3801 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3802 // events) and we do need the IO handler to be pushed and popped
3803 // correctly.
3804
3805 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3806 PopProcessIOHandler();
3807 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003808 }
3809
3810 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003811 } else {
3812 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003813 LLDB_LOGF(
3814 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003815 "Process::%s (pid = %" PRIu64
3816 ") suppressing state %s (old state %s): should_broadcast == false",
3817 __FUNCTION__, GetID(), StateAsCString(new_state),
3818 StateAsCString(GetState()));
3819 }
3820 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003821}
3822
Zachary Turner97206d52017-05-12 04:51:55 +00003823Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003824 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003825 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003826 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003827 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003828
3829 // Ask the process subclass to actually halt our process
3830 bool caused_stop;
3831 error = DoHalt(caused_stop);
3832
3833 DidHalt();
3834 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003835}
3836
Kate Stoneb9c1b512016-09-06 20:57:50 +00003837thread_result_t Process::PrivateStateThread(void *arg) {
3838 std::unique_ptr<PrivateStateThreadArgs> args_up(
3839 static_cast<PrivateStateThreadArgs *>(arg));
3840 thread_result_t result =
3841 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3842 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003843}
3844
Kate Stoneb9c1b512016-09-06 20:57:50 +00003845thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3846 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003847
Kate Stoneb9c1b512016-09-06 20:57:50 +00003848 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003849 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3850 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003851
Kate Stoneb9c1b512016-09-06 20:57:50 +00003852 bool exit_now = false;
3853 bool interrupt_requested = false;
3854 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003855 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003856 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003857 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003858 LLDB_LOGF(log,
3859 "Process::%s (arg = %p, pid = %" PRIu64
3860 ") got a control event: %d",
3861 __FUNCTION__, static_cast<void *>(this), GetID(),
3862 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003863
Kate Stoneb9c1b512016-09-06 20:57:50 +00003864 switch (event_sp->GetType()) {
3865 case eBroadcastInternalStateControlStop:
3866 exit_now = true;
3867 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003868
Kate Stoneb9c1b512016-09-06 20:57:50 +00003869 case eBroadcastInternalStateControlPause:
3870 control_only = true;
3871 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003872
Kate Stoneb9c1b512016-09-06 20:57:50 +00003873 case eBroadcastInternalStateControlResume:
3874 control_only = false;
3875 break;
3876 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003877
Kate Stoneb9c1b512016-09-06 20:57:50 +00003878 continue;
3879 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3880 if (m_public_state.GetValue() == eStateAttaching) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003881 LLDB_LOGF(log,
3882 "Process::%s (arg = %p, pid = %" PRIu64
3883 ") woke up with an interrupt while attaching - "
3884 "forwarding interrupt.",
3885 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003886 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3887 } else if (StateIsRunningState(m_last_broadcast_state)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003888 LLDB_LOGF(log,
3889 "Process::%s (arg = %p, pid = %" PRIu64
3890 ") woke up with an interrupt - Halting.",
3891 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00003892 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003893 if (error.Fail() && log)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003894 LLDB_LOGF(log,
3895 "Process::%s (arg = %p, pid = %" PRIu64
3896 ") failed to halt the process: %s",
3897 __FUNCTION__, static_cast<void *>(this), GetID(),
3898 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00003899 // Halt should generate a stopped event. Make a note of the fact that
3900 // we were doing the interrupt, so we can set the interrupted flag
3901 // after we receive the event. We deliberately set this to true even if
3902 // HaltPrivate failed, so that we can interrupt on the next natural
3903 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003904 interrupt_requested = true;
3905 } else {
3906 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00003907 // running and sends an interrupt request, but the process actually
3908 // stops before we receive it. In that case, we can just ignore the
3909 // request. We use m_last_broadcast_state, because the Stopped event
3910 // may not have been popped of the event queue yet, which is when the
3911 // public state gets updated.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003912 LLDB_LOGF(log,
3913 "Process::%s ignoring interrupt as we have already stopped.",
3914 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003915 }
3916 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003917 }
3918
Kate Stoneb9c1b512016-09-06 20:57:50 +00003919 const StateType internal_state =
3920 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003921
Kate Stoneb9c1b512016-09-06 20:57:50 +00003922 if (internal_state != eStateInvalid) {
3923 if (m_clear_thread_plans_on_stop &&
3924 StateIsStoppedState(internal_state, true)) {
3925 m_clear_thread_plans_on_stop = false;
3926 m_thread_list.DiscardThreadPlans();
3927 }
3928
3929 if (interrupt_requested) {
3930 if (StateIsStoppedState(internal_state, true)) {
3931 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00003932 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00003933 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3934 interrupt_requested = false;
3935 } else if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003936 LLDB_LOGF(log,
3937 "Process::%s interrupt_requested, but a non-stopped "
3938 "state '%s' received.",
3939 __FUNCTION__, StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003940 }
3941 }
3942
3943 HandlePrivateEvent(event_sp);
3944 }
3945
3946 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3947 internal_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003948 LLDB_LOGF(log,
3949 "Process::%s (arg = %p, pid = %" PRIu64
3950 ") about to exit with internal state %s...",
3951 __FUNCTION__, static_cast<void *>(this), GetID(),
3952 StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003953
3954 break;
3955 }
3956 }
3957
3958 // Verify log is still enabled before attempting to write to it...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003959 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3960 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003961
3962 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00003963 // will have already acquired the public_run_lock, and isn't done with what
3964 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003965 if (!is_secondary_thread)
3966 m_public_run_lock.SetStopped();
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003967 return {};
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003968}
3969
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003970// Process Event Data
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003971
Kate Stoneb9c1b512016-09-06 20:57:50 +00003972Process::ProcessEventData::ProcessEventData()
3973 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3974 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003975
Kate Stoneb9c1b512016-09-06 20:57:50 +00003976Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3977 StateType state)
3978 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3979 m_update_state(0), m_interrupted(false) {
3980 if (process_sp)
3981 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003982}
3983
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003984Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003985
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003986ConstString Process::ProcessEventData::GetFlavorString() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003987 static ConstString g_flavor("Process::ProcessEventData");
3988 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003989}
3990
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003991ConstString Process::ProcessEventData::GetFlavor() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003992 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003993}
3994
Kate Stoneb9c1b512016-09-06 20:57:50 +00003995void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
3996 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00003997
Kate Stoneb9c1b512016-09-06 20:57:50 +00003998 if (!process_sp)
3999 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004000
Kate Stoneb9c1b512016-09-06 20:57:50 +00004001 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00004002 // pulled off of the private process event queue, and then any number of
4003 // times, first when it gets pulled off of the public event queue, then other
4004 // times when we're pretending that this is where we stopped at the end of
4005 // expression evaluation. m_update_state is used to distinguish these three
4006 // cases; it is 0 when we're just pulling it off for private handling, and >
4007 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00004008 // command handling then.
4009 if (m_update_state != 1)
4010 return;
4011
4012 process_sp->SetPublicState(
4013 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4014
Jason Molendab3a3cd12016-12-08 06:27:29 +00004015 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00004016 // Let process subclasses know we are about to do a public stop and do
4017 // anything they might need to in order to speed up register and memory
4018 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00004019 process_sp->WillPublicStop();
4020 }
4021
Kate Stoneb9c1b512016-09-06 20:57:50 +00004022 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00004023 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4024 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00004025 // end up restarting the process.
4026 if (m_interrupted)
4027 return;
4028
4029 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4030 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004031 ThreadList &curr_thread_list = process_sp->GetThreadList();
4032 uint32_t num_threads = curr_thread_list.GetSize();
4033 uint32_t idx;
4034
4035 // The actions might change one of the thread's stop_info's opinions about
Adrian Prantl05097242018-04-30 16:49:04 +00004036 // whether we should stop the process, so we need to query that as we go.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004037
4038 // One other complication here, is that we try to catch any case where the
Adrian Prantl05097242018-04-30 16:49:04 +00004039 // target has run (except for expressions) and immediately exit, but if we
4040 // get that wrong (which is possible) then the thread list might have
4041 // changed, and that would cause our iteration here to crash. We could
4042 // make a copy of the thread list, but we'd really like to also know if it
4043 // has changed at all, so we make up a vector of the thread ID's and check
4044 // what we get back against this list & bag out if anything differs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004045 std::vector<uint32_t> thread_index_array(num_threads);
4046 for (idx = 0; idx < num_threads; ++idx)
4047 thread_index_array[idx] =
4048 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4049
4050 // Use this to track whether we should continue from here. We will only
Adrian Prantl05097242018-04-30 16:49:04 +00004051 // continue the target running if no thread says we should stop. Of course
4052 // if some thread's PerformAction actually sets the target running, then it
4053 // doesn't matter what the other threads say...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004054
4055 bool still_should_stop = false;
4056
4057 // Sometimes - for instance if we have a bug in the stub we are talking to,
Adrian Prantl05097242018-04-30 16:49:04 +00004058 // we stop but no thread has a valid stop reason. In that case we should
4059 // just stop, because we have no way of telling what the right thing to do
4060 // is, and it's better to let the user decide than continue behind their
4061 // backs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004062
4063 bool does_anybody_have_an_opinion = false;
4064
4065 for (idx = 0; idx < num_threads; ++idx) {
4066 curr_thread_list = process_sp->GetThreadList();
4067 if (curr_thread_list.GetSize() != num_threads) {
4068 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4069 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004070 LLDB_LOGF(
4071 log,
4072 "Number of threads changed from %u to %u while processing event.",
4073 num_threads, curr_thread_list.GetSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004074 break;
4075 }
4076
4077 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4078
4079 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4080 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4081 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004082 LLDB_LOGF(log,
4083 "The thread at position %u changed from %u to %u while "
4084 "processing event.",
4085 idx, thread_index_array[idx], thread_sp->GetIndexID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004086 break;
4087 }
4088
4089 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4090 if (stop_info_sp && stop_info_sp->IsValid()) {
4091 does_anybody_have_an_opinion = true;
4092 bool this_thread_wants_to_stop;
4093 if (stop_info_sp->GetOverrideShouldStop()) {
4094 this_thread_wants_to_stop =
4095 stop_info_sp->GetOverriddenShouldStopValue();
4096 } else {
4097 stop_info_sp->PerformAction(event_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +00004098 // The stop action might restart the target. If it does, then we
4099 // want to mark that in the event so that whoever is receiving it
4100 // will know to wait for the running event and reflect that state
4101 // appropriately. We also need to stop processing actions, since they
4102 // aren't expecting the target to be running.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004103
4104 // FIXME: we might have run.
4105 if (stop_info_sp->HasTargetRunSinceMe()) {
4106 SetRestarted(true);
4107 break;
4108 }
4109
4110 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004111 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004112
4113 if (!still_should_stop)
4114 still_should_stop = this_thread_wants_to_stop;
4115 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004116 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004117
4118 if (!GetRestarted()) {
4119 if (!still_should_stop && does_anybody_have_an_opinion) {
4120 // We've been asked to continue, so do that here.
4121 SetRestarted(true);
Adrian Prantl05097242018-04-30 16:49:04 +00004122 // Use the public resume method here, since this is just extending a
4123 // public resume.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004124 process_sp->PrivateResume();
4125 } else {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004126 bool hijacked =
4127 process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4128 !process_sp->StateChangedIsHijackedForSynchronousResume();
Jim Ingham3139fc92019-03-01 18:13:38 +00004129
4130 if (!hijacked) {
4131 // If we didn't restart, run the Stop Hooks here.
4132 // Don't do that if state changed events aren't hooked up to the
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004133 // public (or SyncResume) broadcasters. StopHooks are just for
4134 // real public stops. They might also restart the target,
Jim Ingham3139fc92019-03-01 18:13:38 +00004135 // so watch for that.
4136 process_sp->GetTarget().RunStopHooks();
4137 if (process_sp->GetPrivateState() == eStateRunning)
4138 SetRestarted(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004139 }
4140 }
4141 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004142}
Zachary Turner805e7102019-03-04 21:51:03 +00004143}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004144
Kate Stoneb9c1b512016-09-06 20:57:50 +00004145void Process::ProcessEventData::Dump(Stream *s) const {
4146 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004147
Kate Stoneb9c1b512016-09-06 20:57:50 +00004148 if (process_sp)
4149 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4150 static_cast<void *>(process_sp.get()), process_sp->GetID());
4151 else
4152 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004153
Kate Stoneb9c1b512016-09-06 20:57:50 +00004154 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004155}
4156
4157const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004158Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4159 if (event_ptr) {
4160 const EventData *event_data = event_ptr->GetData();
4161 if (event_data &&
4162 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4163 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4164 }
4165 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004166}
4167
4168ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004169Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4170 ProcessSP process_sp;
4171 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4172 if (data)
4173 process_sp = data->GetProcessSP();
4174 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004175}
4176
Kate Stoneb9c1b512016-09-06 20:57:50 +00004177StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4178 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4179 if (data == nullptr)
4180 return eStateInvalid;
4181 else
4182 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004183}
4184
Kate Stoneb9c1b512016-09-06 20:57:50 +00004185bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4186 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4187 if (data == nullptr)
4188 return false;
4189 else
4190 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004191}
4192
Kate Stoneb9c1b512016-09-06 20:57:50 +00004193void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4194 bool new_value) {
4195 ProcessEventData *data =
4196 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4197 if (data != nullptr)
4198 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004199}
4200
Jim Ingham0161b492013-02-09 01:29:05 +00004201size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004202Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4203 ProcessEventData *data =
4204 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4205 if (data != nullptr)
4206 return data->GetNumRestartedReasons();
4207 else
4208 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004209}
4210
4211const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004212Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4213 size_t idx) {
4214 ProcessEventData *data =
4215 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4216 if (data != nullptr)
4217 return data->GetRestartedReasonAtIndex(idx);
4218 else
4219 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004220}
4221
Kate Stoneb9c1b512016-09-06 20:57:50 +00004222void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4223 const char *reason) {
4224 ProcessEventData *data =
4225 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4226 if (data != nullptr)
4227 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004228}
4229
Kate Stoneb9c1b512016-09-06 20:57:50 +00004230bool Process::ProcessEventData::GetInterruptedFromEvent(
4231 const Event *event_ptr) {
4232 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4233 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004234 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004235 else
4236 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004237}
4238
Kate Stoneb9c1b512016-09-06 20:57:50 +00004239void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4240 bool new_value) {
4241 ProcessEventData *data =
4242 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4243 if (data != nullptr)
4244 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004245}
4246
Kate Stoneb9c1b512016-09-06 20:57:50 +00004247bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4248 ProcessEventData *data =
4249 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4250 if (data) {
4251 data->SetUpdateStateOnRemoval();
4252 return true;
4253 }
4254 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004255}
4256
Jim Inghamb87b9e62018-06-26 23:38:58 +00004257lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004258
4259void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4260 exe_ctx.SetTargetPtr(&GetTarget());
4261 exe_ctx.SetProcessPtr(this);
4262 exe_ctx.SetThreadPtr(nullptr);
4263 exe_ctx.SetFramePtr(nullptr);
4264}
4265
4266// uint32_t
4267// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4268// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004269//{
4270// return 0;
4271//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004272//
4273// ArchSpec
4274// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004275//{
4276// return Host::GetArchSpecForExistingProcess (pid);
4277//}
4278//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004279// ArchSpec
4280// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004281//{
4282// return Host::GetArchSpecForExistingProcess (process_name);
4283//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004284
Kate Stoneb9c1b512016-09-06 20:57:50 +00004285void Process::AppendSTDOUT(const char *s, size_t len) {
4286 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4287 m_stdout_data.append(s, len);
4288 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4289 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004290}
4291
Kate Stoneb9c1b512016-09-06 20:57:50 +00004292void Process::AppendSTDERR(const char *s, size_t len) {
4293 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4294 m_stderr_data.append(s, len);
4295 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4296 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004297}
4298
Kate Stoneb9c1b512016-09-06 20:57:50 +00004299void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4300 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4301 m_profile_data.push_back(one_profile_data);
4302 BroadcastEventIfUnique(eBroadcastBitProfileData,
4303 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004304}
4305
Kate Stoneb9c1b512016-09-06 20:57:50 +00004306void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4307 const StructuredDataPluginSP &plugin_sp) {
4308 BroadcastEvent(
4309 eBroadcastBitStructuredData,
4310 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004311}
4312
4313StructuredDataPluginSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004314Process::GetStructuredDataPlugin(ConstString type_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004315 auto find_it = m_structured_data_plugin_map.find(type_name);
4316 if (find_it != m_structured_data_plugin_map.end())
4317 return find_it->second;
4318 else
4319 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004320}
4321
Zachary Turner97206d52017-05-12 04:51:55 +00004322size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004323 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4324 if (m_profile_data.empty())
4325 return 0;
4326
4327 std::string &one_profile_data = m_profile_data.front();
4328 size_t bytes_available = one_profile_data.size();
4329 if (bytes_available > 0) {
4330 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004331 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4332 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004333 if (bytes_available > buf_size) {
4334 memcpy(buf, one_profile_data.c_str(), buf_size);
4335 one_profile_data.erase(0, buf_size);
4336 bytes_available = buf_size;
4337 } else {
4338 memcpy(buf, one_profile_data.c_str(), bytes_available);
4339 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004340 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004341 }
4342 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004343}
4344
Greg Clayton93e86192011-11-13 04:45:22 +00004345// Process STDIO
Greg Clayton93e86192011-11-13 04:45:22 +00004346
Zachary Turner97206d52017-05-12 04:51:55 +00004347size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004348 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4349 size_t bytes_available = m_stdout_data.size();
4350 if (bytes_available > 0) {
4351 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004352 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4353 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004354 if (bytes_available > buf_size) {
4355 memcpy(buf, m_stdout_data.c_str(), buf_size);
4356 m_stdout_data.erase(0, buf_size);
4357 bytes_available = buf_size;
4358 } else {
4359 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4360 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004361 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004362 }
4363 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004364}
4365
Zachary Turner97206d52017-05-12 04:51:55 +00004366size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004367 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4368 size_t bytes_available = m_stderr_data.size();
4369 if (bytes_available > 0) {
4370 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004371 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4372 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004373 if (bytes_available > buf_size) {
4374 memcpy(buf, m_stderr_data.c_str(), buf_size);
4375 m_stderr_data.erase(0, buf_size);
4376 bytes_available = buf_size;
4377 } else {
4378 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4379 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004380 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004381 }
4382 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004383}
4384
Kate Stoneb9c1b512016-09-06 20:57:50 +00004385void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4386 size_t src_len) {
4387 Process *process = (Process *)baton;
4388 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004389}
4390
Kate Stoneb9c1b512016-09-06 20:57:50 +00004391class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004392public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004393 IOHandlerProcessSTDIO(Process *process, int write_fd)
4394 : IOHandler(process->GetTarget().GetDebugger(),
4395 IOHandler::Type::ProcessIO),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004396 m_process(process),
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00004397 m_read_file(GetInputFD(), File::eOpenOptionRead, false),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004398 m_write_file(write_fd, File::eOpenOptionWrite, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004399 m_pipe.CreateNew(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004400 }
4401
4402 ~IOHandlerProcessSTDIO() override = default;
4403
Adrian Prantl05097242018-04-30 16:49:04 +00004404 // Each IOHandler gets to run until it is done. It should read data from the
4405 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004406 void Run() override {
4407 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4408 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4409 SetIsDone(true);
4410 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004411 }
4412
Kate Stoneb9c1b512016-09-06 20:57:50 +00004413 SetIsDone(false);
4414 const int read_fd = m_read_file.GetDescriptor();
4415 TerminalState terminal_state;
4416 terminal_state.Save(read_fd, false);
4417 Terminal terminal(read_fd);
4418 terminal.SetCanonical(false);
4419 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004420// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004421#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004422 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4423 m_is_running = true;
4424 while (!GetIsDone()) {
4425 SelectHelper select_helper;
4426 select_helper.FDSetRead(read_fd);
4427 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004428 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004429
Kate Stoneb9c1b512016-09-06 20:57:50 +00004430 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004431 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004432 } else {
4433 char ch = 0;
4434 size_t n;
4435 if (select_helper.FDIsSetRead(read_fd)) {
4436 n = 1;
4437 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4438 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4439 SetIsDone(true);
4440 } else
4441 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004442 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004443 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4444 size_t bytes_read;
4445 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004446 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004447 if (error.Success()) {
4448 switch (ch) {
4449 case 'q':
4450 SetIsDone(true);
4451 break;
4452 case 'i':
4453 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004454 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004455 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004456 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004457 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004458 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004459 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004460 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004461 m_is_running = false;
4462#endif
4463 terminal_state.Restore();
4464 }
4465
4466 void Cancel() override {
4467 SetIsDone(true);
4468 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004469 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4470 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004471 //
4472 // (lldb) step_process_thousands_of_times
4473 //
4474 // In this case the command interpreter will be in the middle of handling
4475 // the command and if the process pushes and pops the IOHandler thousands
4476 // of times, we can end up writing to m_pipe without ever consuming the
4477 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4478 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4479 if (m_is_running) {
4480 char ch = 'q'; // Send 'q' for quit
4481 size_t bytes_written = 0;
4482 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004483 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004484 }
4485
4486 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004487 // Do only things that are safe to do in an interrupt context (like in a
4488 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004489 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4490 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004491 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004492 if (m_active) {
4493 char ch = 'i'; // Send 'i' for interrupt
4494 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004495 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004496 return result.Success();
4497 } else {
4498 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004499 // currently so do the right thing if we aren't actively watching for
4500 // STDIN by sending the interrupt to the process. Otherwise the write to
4501 // the pipe above would do nothing. This can happen when the command
4502 // interpreter is running and gets a "expression ...". It will be on the
4503 // IOHandler thread and sending the input is complete to the delegate
4504 // which will cause the expression to run, which will push the process IO
4505 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004506
4507 if (StateIsRunningState(m_process->GetState())) {
4508 m_process->SendAsyncInterrupt();
4509 return true;
4510 }
4511 }
4512 return false;
4513 }
4514
4515 void GotEOF() override {}
4516
Greg Clayton44d93782014-01-27 23:43:24 +00004517protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004518 Process *m_process;
Lawrence D'Annaf913fd62019-10-03 04:31:46 +00004519 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
4520 NativeFile m_write_file; // Write to this file (usually the master pty for
4521 // getting io to debuggee)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004522 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004523 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004524};
4525
Kate Stoneb9c1b512016-09-06 20:57:50 +00004526void Process::SetSTDIOFileDescriptor(int fd) {
4527 // First set up the Read Thread for reading/handling process I/O
Pavel Labath451741a2020-04-02 14:40:59 +02004528 m_stdio_communication.SetConnection(
4529 std::make_unique<ConnectionFileDescriptor>(fd, true));
4530 if (m_stdio_communication.IsConnected()) {
4531 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4532 STDIOReadThreadBytesReceived, this);
4533 m_stdio_communication.StartReadThread();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004534
Pavel Labath451741a2020-04-02 14:40:59 +02004535 // Now read thread is set up, set up input reader.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004536
Pavel Labath451741a2020-04-02 14:40:59 +02004537 if (!m_process_input_reader)
4538 m_process_input_reader =
4539 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004540 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004541}
4542
Kate Stoneb9c1b512016-09-06 20:57:50 +00004543bool Process::ProcessIOHandlerIsActive() {
4544 IOHandlerSP io_handler_sp(m_process_input_reader);
4545 if (io_handler_sp)
4546 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4547 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004548}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004549bool Process::PushProcessIOHandler() {
4550 IOHandlerSP io_handler_sp(m_process_input_reader);
4551 if (io_handler_sp) {
4552 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004553 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004554
Kate Stoneb9c1b512016-09-06 20:57:50 +00004555 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004556 // If we evaluate an utility function, then we don't cancel the current
4557 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4558 // existing IOHandler that potentially provides the user interface (e.g.
4559 // the IOHandler for Editline).
4560 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004561 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
4562 cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004563 return true;
4564 }
4565 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004566}
4567
Kate Stoneb9c1b512016-09-06 20:57:50 +00004568bool Process::PopProcessIOHandler() {
4569 IOHandlerSP io_handler_sp(m_process_input_reader);
4570 if (io_handler_sp)
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004571 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004572 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004573}
4574
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004575// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004576void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004577
Kate Stoneb9c1b512016-09-06 20:57:50 +00004578void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004579
Kate Stoneb9c1b512016-09-06 20:57:50 +00004580namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004581// RestorePlanState is used to record the "is private", "is master" and "okay
4582// to discard" fields of the plan we are running, and reset it on Clean or on
4583// destruction. It will only reset the state once, so you can call Clean and
4584// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004585
Kate Stoneb9c1b512016-09-06 20:57:50 +00004586class RestorePlanState {
4587public:
4588 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4589 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4590 if (m_thread_plan_sp) {
4591 m_private = m_thread_plan_sp->GetPrivate();
4592 m_is_master = m_thread_plan_sp->IsMasterPlan();
4593 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4594 }
4595 }
4596
4597 ~RestorePlanState() { Clean(); }
4598
4599 void Clean() {
4600 if (!m_already_reset && m_thread_plan_sp) {
4601 m_already_reset = true;
4602 m_thread_plan_sp->SetPrivate(m_private);
4603 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4604 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4605 }
4606 }
4607
4608private:
4609 lldb::ThreadPlanSP m_thread_plan_sp;
4610 bool m_already_reset;
4611 bool m_private;
4612 bool m_is_master;
4613 bool m_okay_to_discard;
4614};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004615} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004616
Pavel Labath2ce22162016-12-01 10:57:30 +00004617static microseconds
4618GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4619 const milliseconds default_one_thread_timeout(250);
4620
4621 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004622 if (!options.GetTimeout()) {
4623 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4624 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004625 }
4626
4627 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004628 if (options.GetOneThreadTimeout())
4629 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004630
4631 // Otherwise use half the total timeout, bounded by the
4632 // default_one_thread_timeout.
4633 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004634 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004635}
4636
4637static Timeout<std::micro>
4638GetExpressionTimeout(const EvaluateExpressionOptions &options,
4639 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004640 // If we are going to run all threads the whole time, or if we are only going
4641 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004642 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004643 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004644
4645 if (before_first_timeout)
4646 return GetOneThreadExpressionTimeout(options);
4647
Pavel Labath43d35412016-12-06 11:24:51 +00004648 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004649 return llvm::None;
4650 else
Pavel Labath43d35412016-12-06 11:24:51 +00004651 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004652}
4653
Pavel Labath45dde232017-05-25 10:50:06 +00004654static llvm::Optional<ExpressionResults>
4655HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4656 RestorePlanState &restorer, const EventSP &event_sp,
4657 EventSP &event_to_broadcast_sp,
4658 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4659 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4660
4661 ThreadPlanSP plan = thread.GetCompletedPlan();
4662 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4663 LLDB_LOG(log, "execution completed successfully");
4664
4665 // Restore the plan state so it will get reported as intended when we are
4666 // done.
4667 restorer.Clean();
4668 return eExpressionCompleted;
4669 }
4670
4671 StopInfoSP stop_info_sp = thread.GetStopInfo();
4672 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4673 stop_info_sp->ShouldNotify(event_sp.get())) {
4674 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4675 if (!options.DoesIgnoreBreakpoints()) {
4676 // Restore the plan state and then force Private to false. We are going
4677 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004678 // it won't report correctly when we continue to its termination later
4679 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004680 restorer.Clean();
4681 thread_plan_sp->SetPrivate(false);
4682 event_to_broadcast_sp = event_sp;
4683 }
4684 return eExpressionHitBreakpoint;
4685 }
4686
4687 if (!handle_interrupts &&
4688 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4689 return llvm::None;
4690
4691 LLDB_LOG(log, "thread plan did not successfully complete");
4692 if (!options.DoesUnwindOnError())
4693 event_to_broadcast_sp = event_sp;
4694 return eExpressionInterrupted;
4695}
4696
Jim Ingham1624a2d2014-05-05 02:26:40 +00004697ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004698Process::RunThreadPlan(ExecutionContext &exe_ctx,
4699 lldb::ThreadPlanSP &thread_plan_sp,
4700 const EvaluateExpressionOptions &options,
4701 DiagnosticManager &diagnostic_manager) {
4702 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004703
Kate Stoneb9c1b512016-09-06 20:57:50 +00004704 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4705
4706 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004707 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004708 eDiagnosticSeverityError,
4709 "RunThreadPlan called with empty thread plan.");
4710 return eExpressionSetupError;
4711 }
4712
4713 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004714 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004715 eDiagnosticSeverityError,
4716 "RunThreadPlan called with an invalid thread plan.");
4717 return eExpressionSetupError;
4718 }
4719
4720 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004721 diagnostic_manager.PutString(eDiagnosticSeverityError,
4722 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004723 return eExpressionSetupError;
4724 }
4725
4726 Thread *thread = exe_ctx.GetThreadPtr();
4727 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004728 diagnostic_manager.PutString(eDiagnosticSeverityError,
4729 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004730 return eExpressionSetupError;
4731 }
4732
4733 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004734 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004735
4736 RestorePlanState thread_plan_restorer(thread_plan_sp);
4737
Adrian Prantl05097242018-04-30 16:49:04 +00004738 // We rely on the thread plan we are running returning "PlanCompleted" if
4739 // when it successfully completes. For that to be true the plan can't be
4740 // private - since private plans suppress themselves in the GetCompletedPlan
4741 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004742
4743 thread_plan_sp->SetPrivate(false);
4744
4745 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004746 // when they are done we will end up asking the plan above us whether we
4747 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004748
4749 thread_plan_sp->SetIsMasterPlan(true);
4750 thread_plan_sp->SetOkayToDiscard(false);
4751
Raphael Isemannc01783a2018-08-29 22:50:54 +00004752 // If we are running some utility expression for LLDB, we now have to mark
4753 // this in the ProcesModID of this process. This RAII takes care of marking
4754 // and reverting the mark it once we are done running the expression.
4755 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4756
Kate Stoneb9c1b512016-09-06 20:57:50 +00004757 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004758 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004759 eDiagnosticSeverityError,
4760 "RunThreadPlan called while the private state was not stopped.");
4761 return eExpressionSetupError;
4762 }
4763
4764 // Save the thread & frame from the exe_ctx for restoration after we run
4765 const uint32_t thread_idx_id = thread->GetIndexID();
4766 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4767 if (!selected_frame_sp) {
4768 thread->SetSelectedFrame(nullptr);
4769 selected_frame_sp = thread->GetSelectedFrame();
4770 if (!selected_frame_sp) {
4771 diagnostic_manager.Printf(
4772 eDiagnosticSeverityError,
4773 "RunThreadPlan called without a selected frame on thread %d",
4774 thread_idx_id);
4775 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004776 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004777 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004778
Adrian Prantl05097242018-04-30 16:49:04 +00004779 // Make sure the timeout values make sense. The one thread timeout needs to
4780 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004781 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4782 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004783 diagnostic_manager.PutString(eDiagnosticSeverityError,
4784 "RunThreadPlan called with one thread "
4785 "timeout greater than total timeout");
4786 return eExpressionSetupError;
4787 }
4788
Kate Stoneb9c1b512016-09-06 20:57:50 +00004789 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004790
Kate Stoneb9c1b512016-09-06 20:57:50 +00004791 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004792 // We don't want to do that either, so we should arrange to reset them as
4793 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004794
Kate Stoneb9c1b512016-09-06 20:57:50 +00004795 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004796
Kate Stoneb9c1b512016-09-06 20:57:50 +00004797 uint32_t selected_tid;
4798 StackID selected_stack_id;
4799 if (selected_thread_sp) {
4800 selected_tid = selected_thread_sp->GetIndexID();
4801 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4802 } else {
4803 selected_tid = LLDB_INVALID_THREAD_ID;
4804 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004805
Kate Stoneb9c1b512016-09-06 20:57:50 +00004806 HostThread backup_private_state_thread;
4807 lldb::StateType old_state = eStateInvalid;
4808 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004809
Kate Stoneb9c1b512016-09-06 20:57:50 +00004810 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4811 LIBLLDB_LOG_PROCESS));
4812 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4813 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004814 // public events on this thread, since we are the thread that is generating
4815 // public events. The simplest thing to do is to spin up a temporary thread
4816 // to handle private state thread events while we are fielding public
4817 // events here.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004818 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4819 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004820
Kate Stoneb9c1b512016-09-06 20:57:50 +00004821 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004822
Kate Stoneb9c1b512016-09-06 20:57:50 +00004823 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004824 // anything it pushes, and then stop, returning control here. But in the
4825 // normal course of things, the plan above us on the stack would be given a
4826 // shot at the stop event before deciding to stop, and we don't want that.
4827 // So we insert a "stopper" base plan on the stack before the plan we want
4828 // to run. Since base plans always stop and return control to the user,
4829 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004830 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4831 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4832 // Have to make sure our public state is stopped, since otherwise the
4833 // reporting logic below doesn't work correctly.
4834 old_state = m_public_state.GetValue();
4835 m_public_state.SetValueNoLock(eStateStopped);
4836
4837 // Now spin up the private state thread:
4838 StartPrivateStateThread(true);
4839 }
4840
4841 thread->QueueThreadPlan(
4842 thread_plan_sp, false); // This used to pass "true" does that make sense?
4843
4844 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004845 // In this case, we aren't actually going to run, we just want to stop
4846 // right away. Flush this thread so we will refetch the stacks and show the
4847 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004848 // FIXME: To make this prettier we should invent some stop reason for this,
4849 // but that
4850 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004851 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004852 thread->Flush();
4853 return eExpressionStoppedForDebug;
4854 }
4855
4856 ListenerSP listener_sp(
4857 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4858
4859 lldb::EventSP event_to_broadcast_sp;
4860
4861 {
4862 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004863 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004864 //
4865 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004866 // exits during execution), then the event is put into
4867 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004868
4869 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4870
4871 if (log) {
4872 StreamString s;
4873 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004874 LLDB_LOGF(log,
4875 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4876 " to run thread plan \"%s\".",
4877 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004878 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004879
4880 bool got_event;
4881 lldb::EventSP event_sp;
4882 lldb::StateType stop_state = lldb::eStateInvalid;
4883
4884 bool before_first_timeout = true; // This is set to false the first time
4885 // that we have to halt the target.
4886 bool do_resume = true;
4887 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004888
4889 // This is just for accounting:
4890 uint32_t num_resumes = 0;
4891
Kate Stoneb9c1b512016-09-06 20:57:50 +00004892 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00004893 // going to run one thread, then we don't need the first timeout. So we
4894 // pretend we are after the first timeout already.
4895 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004896 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00004897
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004898 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4899 options.GetStopOthers(), options.GetTryAllThreads(),
4900 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004901
Adrian Prantl05097242018-04-30 16:49:04 +00004902 // This isn't going to work if there are unfetched events on the queue. Are
4903 // there cases where we might want to run the remaining events here, and
4904 // then try to call the function? That's probably being too tricky for our
4905 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004906
4907 Event *other_events = listener_sp->PeekAtNextEvent();
4908 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004909 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004910 eDiagnosticSeverityError,
4911 "RunThreadPlan called with pending events on the queue.");
4912 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00004913 }
4914
Kate Stoneb9c1b512016-09-06 20:57:50 +00004915 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00004916 // calling a function as part of a thread plan, in which case the last
4917 // delivered event could be the running event, and we don't want event
4918 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004919 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00004920
Kate Stoneb9c1b512016-09-06 20:57:50 +00004921// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00004922// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00004923
Kate Stoneb9c1b512016-09-06 20:57:50 +00004924#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00004925 // It's pretty much impossible to write test cases for things like: One
4926 // thread timeout expires, I go to halt, but the process already stopped on
4927 // the function call stop breakpoint. Turning on this define will make us
4928 // not fetch the first event till after the halt. So if you run a quick
4929 // function, it will have completed, and the completion event will be
4930 // waiting, when you interrupt for halt. The expression evaluation should
4931 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004932 bool miss_first_event = true;
4933#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00004934 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00004935 // We usually want to resume the process if we get to the top of the
4936 // loop. The only exception is if we get two running events with no
4937 // intervening stop, which can happen, we will just wait for then next
4938 // stop event.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004939 LLDB_LOGF(log,
4940 "Top of while loop: do_resume: %i handle_running_event: %i "
4941 "before_first_timeout: %i.",
4942 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00004943
Kate Stoneb9c1b512016-09-06 20:57:50 +00004944 if (do_resume || handle_running_event) {
4945 // Do the initial resume and wait for the running event before going
4946 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00004947
Kate Stoneb9c1b512016-09-06 20:57:50 +00004948 if (do_resume) {
4949 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00004950 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004951 if (!resume_error.Success()) {
4952 diagnostic_manager.Printf(
4953 eDiagnosticSeverityError,
4954 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4955 resume_error.AsCString());
4956 return_value = eExpressionSetupError;
4957 break;
4958 }
Jason Molendaef7d6412015-08-06 03:27:10 +00004959 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004960
Pavel Labathd35031e12016-11-30 10:41:42 +00004961 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00004962 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004963 if (!got_event) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004964 LLDB_LOGF(log,
4965 "Process::RunThreadPlan(): didn't get any event after "
4966 "resume %" PRIu32 ", exiting.",
4967 num_resumes);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004968
4969 diagnostic_manager.Printf(eDiagnosticSeverityError,
4970 "didn't get any event after resume %" PRIu32
4971 ", exiting.",
4972 num_resumes);
4973 return_value = eExpressionSetupError;
4974 break;
4975 }
4976
4977 stop_state =
4978 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4979
4980 if (stop_state != eStateRunning) {
4981 bool restarted = false;
4982
4983 if (stop_state == eStateStopped) {
4984 restarted = Process::ProcessEventData::GetRestartedFromEvent(
4985 event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004986 LLDB_LOGF(
4987 log,
4988 "Process::RunThreadPlan(): didn't get running event after "
4989 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4990 "handle_running_event: %i).",
4991 num_resumes, StateAsCString(stop_state), restarted, do_resume,
4992 handle_running_event);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004993 }
4994
4995 if (restarted) {
4996 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00004997 // should ever get a stopped & restarted event here. But if I do,
4998 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004999 const bool clear_thread_plans = false;
5000 const bool use_run_lock = false;
5001 Halt(clear_thread_plans, use_run_lock);
5002 }
5003
5004 diagnostic_manager.Printf(
5005 eDiagnosticSeverityError,
5006 "didn't get running event after initial resume, got %s instead.",
5007 StateAsCString(stop_state));
5008 return_value = eExpressionSetupError;
5009 break;
5010 }
5011
5012 if (log)
5013 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00005014 // We need to call the function synchronously, so spin waiting for it
5015 // to return. If we get interrupted while executing, we're going to
5016 // lose our context, and won't be able to gather the result at this
5017 // point. We set the timeout AFTER the resume, since the resume takes
5018 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005019 } else {
5020 if (log)
5021 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5022 }
5023
Kate Stoneb9c1b512016-09-06 20:57:50 +00005024 do_resume = true;
5025 handle_running_event = true;
5026
5027 // Now wait for the process to stop again:
5028 event_sp.reset();
5029
Pavel Labath2ce22162016-12-01 10:57:30 +00005030 Timeout<std::micro> timeout =
5031 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005032 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005033 if (timeout) {
5034 auto now = system_clock::now();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005035 LLDB_LOGF(log,
5036 "Process::RunThreadPlan(): about to wait - now is %s - "
5037 "endpoint is %s",
5038 llvm::to_string(now).c_str(),
5039 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005040 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005041 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005042 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005043 }
5044
5045#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5046 // See comment above...
5047 if (miss_first_event) {
Pavel Labath3d4f7652019-08-05 08:23:25 +00005048 std::this_thread::sleep_for(std::chrono::milliseconds(1));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005049 miss_first_event = false;
5050 got_event = false;
5051 } else
5052#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005053 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005054
5055 if (got_event) {
5056 if (event_sp) {
5057 bool keep_going = false;
5058 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5059 const bool clear_thread_plans = false;
5060 const bool use_run_lock = false;
5061 Halt(clear_thread_plans, use_run_lock);
5062 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005063 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5064 "execution halted by user interrupt.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005065 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
5066 "eBroadcastBitInterrupted, exiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005067 break;
5068 } else {
5069 stop_state =
5070 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005071 LLDB_LOGF(log,
5072 "Process::RunThreadPlan(): in while loop, got event: %s.",
5073 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005074
5075 switch (stop_state) {
5076 case lldb::eStateStopped: {
5077 // We stopped, figure out what we are going to do now.
5078 ThreadSP thread_sp =
5079 GetThreadList().FindThreadByIndexID(thread_idx_id);
5080 if (!thread_sp) {
5081 // Ooh, our thread has vanished. Unlikely that this was
5082 // successful execution...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005083 LLDB_LOGF(log,
5084 "Process::RunThreadPlan(): execution completed "
5085 "but our thread (index-id=%u) has vanished.",
5086 thread_idx_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005087 return_value = eExpressionInterrupted;
Pavel Labath45dde232017-05-25 10:50:06 +00005088 } else if (Process::ProcessEventData::GetRestartedFromEvent(
5089 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005090 // If we were restarted, we just need to go back up to fetch
5091 // another event.
Pavel Labath45dde232017-05-25 10:50:06 +00005092 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005093 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5094 "restart, so we'll continue waiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005095 }
Pavel Labath45dde232017-05-25 10:50:06 +00005096 keep_going = true;
5097 do_resume = false;
5098 handle_running_event = true;
5099 } else {
5100 const bool handle_interrupts = true;
5101 return_value = *HandleStoppedEvent(
5102 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5103 event_to_broadcast_sp, options, handle_interrupts);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005104 }
5105 } break;
5106
5107 case lldb::eStateRunning:
5108 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005109 // running events without an intervening stop, and in that case
5110 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005111 do_resume = false;
5112 keep_going = true;
5113 handle_running_event = false;
5114 break;
5115
5116 default:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005117 LLDB_LOGF(log,
5118 "Process::RunThreadPlan(): execution stopped with "
5119 "unexpected state: %s.",
5120 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005121
5122 if (stop_state == eStateExited)
5123 event_to_broadcast_sp = event_sp;
5124
Zachary Turnere2411fa2016-11-12 19:12:56 +00005125 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005126 eDiagnosticSeverityError,
5127 "execution stopped with unexpected state.");
5128 return_value = eExpressionInterrupted;
5129 break;
5130 }
5131 }
5132
5133 if (keep_going)
5134 continue;
5135 else
5136 break;
5137 } else {
5138 if (log)
5139 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5140 "the event pointer was null. How odd...");
5141 return_value = eExpressionInterrupted;
5142 break;
5143 }
5144 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005145 // If we didn't get an event that means we've timed out... We will
5146 // interrupt the process here. Depending on what we were asked to do
5147 // we will either exit, or try with all threads running for the same
5148 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005149
5150 if (log) {
5151 if (options.GetTryAllThreads()) {
5152 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005153 LLDB_LOG(log,
5154 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005155 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005156 LLDB_LOG(log, "Restarting function with all threads enabled and "
5157 "timeout: {0} timed out, abandoning execution.",
5158 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005159 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005160 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5161 "abandoning execution.",
5162 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005163 }
5164
5165 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005166 // around to calling Halt the target could have stopped. That's fine,
5167 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005168 // BUT it is also possible that we stopped & restarted (e.g. hit a
5169 // signal with "stop" set to false.) In
5170 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005171 // back to waiting for the Halt's stopped event. That's what this
5172 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005173
5174 bool back_to_top = true;
5175 uint32_t try_halt_again = 0;
5176 bool do_halt = true;
5177 const uint32_t num_retries = 5;
5178 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005179 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005180 if (do_halt) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005181 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005182 const bool clear_thread_plans = false;
5183 const bool use_run_lock = false;
5184 Halt(clear_thread_plans, use_run_lock);
5185 }
5186 if (halt_error.Success()) {
5187 if (log)
5188 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5189
Pavel Labathd35031e12016-11-30 10:41:42 +00005190 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00005191 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005192
5193 if (got_event) {
5194 stop_state =
5195 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5196 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005197 LLDB_LOGF(log,
5198 "Process::RunThreadPlan(): Stopped with event: %s",
5199 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005200 if (stop_state == lldb::eStateStopped &&
5201 Process::ProcessEventData::GetInterruptedFromEvent(
5202 event_sp.get()))
5203 log->PutCString(" Event was the Halt interruption event.");
5204 }
5205
5206 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005207 if (Process::ProcessEventData::GetRestartedFromEvent(
5208 event_sp.get())) {
5209 if (log)
5210 log->PutCString("Process::RunThreadPlan(): Went to halt "
5211 "but got a restarted event, there must be "
5212 "an un-restarted stopped event so try "
5213 "again... "
5214 "Exiting wait loop.");
5215 try_halt_again++;
5216 do_halt = false;
5217 continue;
5218 }
5219
Pavel Labath45dde232017-05-25 10:50:06 +00005220 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005221 // delivered it, the process could have already finished its
5222 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005223 const bool handle_interrupts = false;
5224 if (auto result = HandleStoppedEvent(
5225 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5226 event_to_broadcast_sp, options, handle_interrupts)) {
5227 return_value = *result;
5228 back_to_top = false;
5229 break;
5230 }
5231
Kate Stoneb9c1b512016-09-06 20:57:50 +00005232 if (!options.GetTryAllThreads()) {
5233 if (log)
5234 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5235 "was false, we stopped so now we're "
5236 "quitting.");
5237 return_value = eExpressionInterrupted;
5238 back_to_top = false;
5239 break;
5240 }
5241
5242 if (before_first_timeout) {
5243 // Set all the other threads to run, and return to the top of
5244 // the loop, which will continue;
5245 before_first_timeout = false;
5246 thread_plan_sp->SetStopOthers(false);
5247 if (log)
5248 log->PutCString(
5249 "Process::RunThreadPlan(): about to resume.");
5250
5251 back_to_top = true;
5252 break;
5253 } else {
5254 // Running all threads failed, so return Interrupted.
5255 if (log)
5256 log->PutCString("Process::RunThreadPlan(): running all "
5257 "threads timed out.");
5258 return_value = eExpressionInterrupted;
5259 back_to_top = false;
5260 break;
5261 }
5262 }
5263 } else {
5264 if (log)
5265 log->PutCString("Process::RunThreadPlan(): halt said it "
5266 "succeeded, but I got no event. "
5267 "I'm getting out of here passing Interrupted.");
5268 return_value = eExpressionInterrupted;
5269 back_to_top = false;
5270 break;
5271 }
5272 } else {
5273 try_halt_again++;
5274 continue;
5275 }
5276 }
5277
5278 if (!back_to_top || try_halt_again > num_retries)
5279 break;
5280 else
5281 continue;
5282 }
5283 } // END WAIT LOOP
5284
Adrian Prantl05097242018-04-30 16:49:04 +00005285 // If we had to start up a temporary private state thread to run this
5286 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005287 if (backup_private_state_thread.IsJoinable()) {
5288 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005289 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005290 m_private_state_thread = backup_private_state_thread;
5291 if (stopper_base_plan_sp) {
5292 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5293 }
5294 if (old_state != eStateInvalid)
5295 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005296 }
5297
Kate Stoneb9c1b512016-09-06 20:57:50 +00005298 if (return_value != eExpressionCompleted && log) {
5299 // Print a backtrace into the log so we can figure out where we are:
5300 StreamString s;
5301 s.PutCString("Thread state after unsuccessful completion: \n");
5302 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005303 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005304 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005305 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005306 // There are three cases where this could happen: 1) The execution
5307 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5308 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005309 bool should_unwind = (return_value == eExpressionInterrupted &&
5310 options.DoesUnwindOnError()) ||
5311 (return_value == eExpressionHitBreakpoint &&
5312 options.DoesIgnoreBreakpoints());
5313
5314 if (return_value == eExpressionCompleted || should_unwind) {
5315 thread_plan_sp->RestoreThreadState();
5316 }
5317
5318 // Now do some processing on the results of the run:
5319 if (return_value == eExpressionInterrupted ||
5320 return_value == eExpressionHitBreakpoint) {
5321 if (log) {
5322 StreamString s;
5323 if (event_sp)
5324 event_sp->Dump(&s);
5325 else {
5326 log->PutCString("Process::RunThreadPlan(): Stop event that "
5327 "interrupted us is NULL.");
5328 }
5329
5330 StreamString ts;
5331
5332 const char *event_explanation = nullptr;
5333
5334 do {
5335 if (!event_sp) {
5336 event_explanation = "<no event>";
5337 break;
5338 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5339 event_explanation = "<user interrupt>";
5340 break;
5341 } else {
5342 const Process::ProcessEventData *event_data =
5343 Process::ProcessEventData::GetEventDataFromEvent(
5344 event_sp.get());
5345
5346 if (!event_data) {
5347 event_explanation = "<no event data>";
5348 break;
5349 }
5350
5351 Process *process = event_data->GetProcessSP().get();
5352
5353 if (!process) {
5354 event_explanation = "<no process>";
5355 break;
5356 }
5357
5358 ThreadList &thread_list = process->GetThreadList();
5359
5360 uint32_t num_threads = thread_list.GetSize();
5361 uint32_t thread_index;
5362
5363 ts.Printf("<%u threads> ", num_threads);
5364
5365 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5366 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5367
5368 if (!thread) {
5369 ts.Printf("<?> ");
5370 continue;
5371 }
5372
5373 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5374 RegisterContext *register_context =
5375 thread->GetRegisterContext().get();
5376
5377 if (register_context)
5378 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5379 else
5380 ts.Printf("[ip unknown] ");
5381
5382 // Show the private stop info here, the public stop info will be
5383 // from the last natural stop.
5384 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5385 if (stop_info_sp) {
5386 const char *stop_desc = stop_info_sp->GetDescription();
5387 if (stop_desc)
5388 ts.PutCString(stop_desc);
5389 }
5390 ts.Printf(">");
5391 }
5392
5393 event_explanation = ts.GetData();
5394 }
Jonas Devlieghere09ad8c82019-05-24 00:44:33 +00005395 } while (false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005396
5397 if (event_explanation)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005398 LLDB_LOGF(log,
5399 "Process::RunThreadPlan(): execution interrupted: %s %s",
5400 s.GetData(), event_explanation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005401 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005402 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
5403 s.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005404 }
5405
5406 if (should_unwind) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005407 LLDB_LOGF(log,
5408 "Process::RunThreadPlan: ExecutionInterrupted - "
5409 "discarding thread plans up to %p.",
5410 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005411 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5412 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005413 LLDB_LOGF(log,
5414 "Process::RunThreadPlan: ExecutionInterrupted - for "
5415 "plan: %p not discarding.",
5416 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005417 }
5418 } else if (return_value == eExpressionSetupError) {
5419 if (log)
5420 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5421
5422 if (options.DoesUnwindOnError()) {
5423 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5424 }
5425 } else {
5426 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5427 if (log)
5428 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5429 return_value = eExpressionCompleted;
5430 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5431 if (log)
5432 log->PutCString(
5433 "Process::RunThreadPlan(): thread plan was discarded");
5434 return_value = eExpressionDiscarded;
5435 } else {
5436 if (log)
5437 log->PutCString(
5438 "Process::RunThreadPlan(): thread plan stopped in mid course");
5439 if (options.DoesUnwindOnError() && thread_plan_sp) {
5440 if (log)
5441 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5442 "'cause unwind_on_error is set.");
5443 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5444 }
5445 }
5446 }
5447
5448 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005449 // target Check that it's still there, and if it is put it back in the
5450 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005451 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5452 if (thread) {
5453 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5454 }
5455
5456 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005457 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005458
5459 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5460 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5461 selected_stack_id.IsValid()) {
5462 // We were able to restore the selected thread, now restore the frame:
5463 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5464 StackFrameSP old_frame_sp =
5465 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5466 selected_stack_id);
5467 if (old_frame_sp)
5468 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5469 old_frame_sp.get());
5470 }
5471 }
5472 }
5473
5474 // If the process exited during the run of the thread plan, notify everyone.
5475
5476 if (event_to_broadcast_sp) {
5477 if (log)
5478 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5479 BroadcastEvent(event_to_broadcast_sp);
5480 }
5481
5482 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005483}
5484
Kate Stoneb9c1b512016-09-06 20:57:50 +00005485const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5486 const char *result_name;
5487
5488 switch (result) {
5489 case eExpressionCompleted:
5490 result_name = "eExpressionCompleted";
5491 break;
5492 case eExpressionDiscarded:
5493 result_name = "eExpressionDiscarded";
5494 break;
5495 case eExpressionInterrupted:
5496 result_name = "eExpressionInterrupted";
5497 break;
5498 case eExpressionHitBreakpoint:
5499 result_name = "eExpressionHitBreakpoint";
5500 break;
5501 case eExpressionSetupError:
5502 result_name = "eExpressionSetupError";
5503 break;
5504 case eExpressionParseError:
5505 result_name = "eExpressionParseError";
5506 break;
5507 case eExpressionResultUnavailable:
5508 result_name = "eExpressionResultUnavailable";
5509 break;
5510 case eExpressionTimedOut:
5511 result_name = "eExpressionTimedOut";
5512 break;
5513 case eExpressionStoppedForDebug:
5514 result_name = "eExpressionStoppedForDebug";
5515 break;
5516 }
5517 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005518}
5519
Kate Stoneb9c1b512016-09-06 20:57:50 +00005520void Process::GetStatus(Stream &strm) {
5521 const StateType state = GetState();
5522 if (StateIsStoppedState(state, false)) {
5523 if (state == eStateExited) {
5524 int exit_status = GetExitStatus();
5525 const char *exit_description = GetExitDescription();
5526 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5527 GetID(), exit_status, exit_status,
5528 exit_description ? exit_description : "");
5529 } else {
5530 if (state == eStateConnected)
5531 strm.Printf("Connected to remote target.\n");
5532 else
5533 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5534 }
5535 } else {
5536 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5537 }
Pavel Labatha933d512016-04-05 13:07:16 +00005538}
5539
Kate Stoneb9c1b512016-09-06 20:57:50 +00005540size_t Process::GetThreadStatus(Stream &strm,
5541 bool only_threads_with_stop_reason,
5542 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005543 uint32_t num_frames_with_source,
5544 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005545 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005546
Kate Stoneb9c1b512016-09-06 20:57:50 +00005547 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005548 // very well might run code (e.g. if we need it to get return values or
5549 // arguments.) For that to work the process has to be able to acquire it.
5550 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005551
5552 uint32_t num_threads;
5553 std::vector<lldb::tid_t> thread_id_array;
5554 // Scope for thread list locker;
5555 {
5556 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5557 ThreadList &curr_thread_list = GetThreadList();
5558 num_threads = curr_thread_list.GetSize();
5559 uint32_t idx;
5560 thread_id_array.resize(num_threads);
5561 for (idx = 0; idx < num_threads; ++idx)
5562 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5563 }
5564
5565 for (uint32_t i = 0; i < num_threads; i++) {
5566 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5567 if (thread_sp) {
5568 if (only_threads_with_stop_reason) {
5569 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5570 if (!stop_info_sp || !stop_info_sp->IsValid())
5571 continue;
5572 }
5573 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005574 num_frames_with_source,
5575 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005576 ++num_thread_infos_dumped;
5577 } else {
5578 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005579 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
5580 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005582 }
5583 return num_thread_infos_dumped;
5584}
5585
5586void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5587 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5588}
5589
5590bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5591 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5592 region.GetByteSize());
5593}
5594
5595void Process::AddPreResumeAction(PreResumeActionCallback callback,
5596 void *baton) {
5597 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5598}
5599
5600bool Process::RunPreResumeActions() {
5601 bool result = true;
5602 while (!m_pre_resume_actions.empty()) {
5603 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5604 m_pre_resume_actions.pop_back();
5605 bool this_result = action.callback(action.baton);
5606 if (result)
5607 result = this_result;
5608 }
5609 return result;
5610}
5611
5612void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5613
Jim Inghamffd91752016-10-20 22:50:00 +00005614void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5615{
5616 PreResumeCallbackAndBaton element(callback, baton);
5617 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5618 if (found_iter != m_pre_resume_actions.end())
5619 {
5620 m_pre_resume_actions.erase(found_iter);
5621 }
5622}
5623
Kate Stoneb9c1b512016-09-06 20:57:50 +00005624ProcessRunLock &Process::GetRunLock() {
5625 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5626 return m_private_run_lock;
5627 else
5628 return m_public_run_lock;
5629}
5630
Jim Ingham58c3235e2019-10-01 00:47:25 +00005631bool Process::CurrentThreadIsPrivateStateThread()
5632{
5633 return m_private_state_thread.EqualsThread(Host::GetCurrentThread());
5634}
5635
5636
Kate Stoneb9c1b512016-09-06 20:57:50 +00005637void Process::Flush() {
5638 m_thread_list.Flush();
5639 m_extended_thread_list.Flush();
5640 m_extended_thread_stop_id = 0;
5641 m_queue_list.Clear();
5642 m_queue_list_stop_id = 0;
5643}
5644
5645void Process::DidExec() {
5646 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005647 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005648
5649 Target &target = GetTarget();
5650 target.CleanupProcess();
5651 target.ClearModules(false);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005652 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005653 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005654 m_system_runtime_up.reset();
5655 m_os_up.reset();
5656 m_dyld_up.reset();
5657 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005658 m_image_tokens.clear();
5659 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +00005660 {
5661 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5662 m_language_runtimes.clear();
5663 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005664 m_instrumentation_runtimes.clear();
5665 m_thread_list.DiscardThreadPlans();
5666 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005667 DoDidExec();
5668 CompleteAttach();
5669 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005670 // CompleteAttach() in case the dynamic loader loaded things in new
5671 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005672 Flush();
5673
Adrian Prantl05097242018-04-30 16:49:04 +00005674 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5675 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005676 target.DidExec();
5677}
5678
Zachary Turner97206d52017-05-12 04:51:55 +00005679addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005680 if (address == nullptr) {
5681 error.SetErrorString("Invalid address argument");
5682 return LLDB_INVALID_ADDRESS;
5683 }
5684
5685 addr_t function_addr = LLDB_INVALID_ADDRESS;
5686
5687 addr_t addr = address->GetLoadAddress(&GetTarget());
5688 std::map<addr_t, addr_t>::const_iterator iter =
5689 m_resolved_indirect_addresses.find(addr);
5690 if (iter != m_resolved_indirect_addresses.end()) {
5691 function_addr = (*iter).second;
5692 } else {
Alex Langford5b2b38e2019-09-13 00:02:05 +00005693 if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005694 Symbol *symbol = address->CalculateSymbolContextSymbol();
5695 error.SetErrorStringWithFormat(
5696 "Unable to call resolver for indirect function %s",
5697 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5698 function_addr = LLDB_INVALID_ADDRESS;
5699 } else {
5700 m_resolved_indirect_addresses.insert(
5701 std::pair<addr_t, addr_t>(addr, function_addr));
5702 }
5703 }
5704 return function_addr;
5705}
5706
5707void Process::ModulesDidLoad(ModuleList &module_list) {
5708 SystemRuntime *sys_runtime = GetSystemRuntime();
5709 if (sys_runtime) {
5710 sys_runtime->ModulesDidLoad(module_list);
5711 }
5712
5713 GetJITLoaders().ModulesDidLoad(module_list);
5714
5715 // Give runtimes a chance to be created.
5716 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5717 m_instrumentation_runtimes);
5718
5719 // Tell runtimes about new modules.
5720 for (auto pos = m_instrumentation_runtimes.begin();
5721 pos != m_instrumentation_runtimes.end(); ++pos) {
5722 InstrumentationRuntimeSP runtime = pos->second;
5723 runtime->ModulesDidLoad(module_list);
5724 }
5725
Adrian Prantl05097242018-04-30 16:49:04 +00005726 // Let any language runtimes we have already created know about the modules
5727 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005728
Adrian Prantl05097242018-04-30 16:49:04 +00005729 // Iterate over a copy of this language runtime list in case the language
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005730 // runtime ModulesDidLoad somehow causes the language runtime to be
Adrian Prantl05097242018-04-30 16:49:04 +00005731 // unloaded.
Alex Langford74eb76f2019-05-22 23:01:18 +00005732 {
5733 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5734 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5735 for (const auto &pair : language_runtimes) {
5736 // We must check language_runtime_sp to make sure it is not nullptr as we
5737 // might cache the fact that we didn't have a language runtime for a
5738 // language.
5739 LanguageRuntimeSP language_runtime_sp = pair.second;
5740 if (language_runtime_sp)
5741 language_runtime_sp->ModulesDidLoad(module_list);
5742 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005743 }
5744
5745 // If we don't have an operating system plug-in, try to load one since
5746 // loading shared libraries might cause a new one to try and load
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005747 if (!m_os_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005748 LoadOperatingSystemPlugin(false);
5749
5750 // Give structured-data plugins a chance to see the modified modules.
5751 for (auto pair : m_structured_data_plugin_map) {
5752 if (pair.second)
5753 pair.second->ModulesDidLoad(*this, module_list);
5754 }
5755}
5756
5757void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5758 const char *fmt, ...) {
5759 bool print_warning = true;
5760
5761 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5762 if (!stream_sp)
5763 return;
5764 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5765 return;
5766 }
5767
5768 if (repeat_key != nullptr) {
5769 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5770 if (it == m_warnings_issued.end()) {
5771 m_warnings_issued[warning_type] = WarningsPointerSet();
5772 m_warnings_issued[warning_type].insert(repeat_key);
5773 } else {
5774 if (it->second.find(repeat_key) != it->second.end()) {
5775 print_warning = false;
5776 } else {
5777 it->second.insert(repeat_key);
5778 }
5779 }
5780 }
5781
5782 if (print_warning) {
5783 va_list args;
5784 va_start(args, fmt);
5785 stream_sp->PrintfVarArg(fmt, args);
5786 va_end(args);
5787 }
5788}
5789
5790void Process::PrintWarningOptimization(const SymbolContext &sc) {
5791 if (GetWarningsOptimization() && sc.module_sp &&
5792 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5793 sc.function->GetIsOptimized()) {
5794 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5795 "%s was compiled with optimization - stepping may behave "
5796 "oddly; variables may not be available.\n",
5797 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5798 }
5799}
5800
5801bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5802 info.Clear();
5803
5804 PlatformSP platform_sp = GetTarget().GetPlatform();
5805 if (!platform_sp)
5806 return false;
5807
5808 return platform_sp->GetProcessInfo(GetID(), info);
5809}
5810
5811ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5812 ThreadCollectionSP threads;
5813
5814 const MemoryHistorySP &memory_history =
5815 MemoryHistory::FindPlugin(shared_from_this());
5816
5817 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005818 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005819 }
5820
Jonas Devlieghere796ac802019-02-11 23:13:08 +00005821 threads = std::make_shared<ThreadCollection>(
5822 memory_history->GetHistoryThreads(addr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005823
5824 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005825}
Kuba Brecka63927542014-10-11 01:59:32 +00005826
5827InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005828Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5829 InstrumentationRuntimeCollection::iterator pos;
5830 pos = m_instrumentation_runtimes.find(type);
5831 if (pos == m_instrumentation_runtimes.end()) {
5832 return InstrumentationRuntimeSP();
5833 } else
5834 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005835}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005836
Kate Stoneb9c1b512016-09-06 20:57:50 +00005837bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5838 const ArchSpec &arch, ModuleSpec &module_spec) {
5839 module_spec.Clear();
5840 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005841}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005842
Kate Stoneb9c1b512016-09-06 20:57:50 +00005843size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5844 m_image_tokens.push_back(image_ptr);
5845 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005846}
5847
Kate Stoneb9c1b512016-09-06 20:57:50 +00005848lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5849 if (token < m_image_tokens.size())
5850 return m_image_tokens[token];
Saleem Abdulrasool3775be22020-04-06 17:33:38 -07005851 return LLDB_INVALID_ADDRESS;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005852}
5853
Kate Stoneb9c1b512016-09-06 20:57:50 +00005854void Process::ResetImageToken(size_t token) {
5855 if (token < m_image_tokens.size())
Saleem Abdulrasool3775be22020-04-06 17:33:38 -07005856 m_image_tokens[token] = LLDB_INVALID_ADDRESS;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005857}
Jason Molendafd4cea52016-01-08 21:40:11 +00005858
5859Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005860Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5861 AddressRange range_bounds) {
5862 Target &target = GetTarget();
5863 DisassemblerSP disassembler_sp;
5864 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005865
Kate Stoneb9c1b512016-09-06 20:57:50 +00005866 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005867
Kate Stoneb9c1b512016-09-06 20:57:50 +00005868 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005869 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005870 if (!default_stop_addr.IsValid())
5871 return retval;
5872
Kate Stoneb9c1b512016-09-06 20:57:50 +00005873 const char *plugin_name = nullptr;
5874 const char *flavor = nullptr;
5875 const bool prefer_file_cache = true;
5876 disassembler_sp = Disassembler::DisassembleRange(
Pavel Labath04592d52020-03-05 13:03:26 +01005877 target.GetArchitecture(), plugin_name, flavor, GetTarget(), range_bounds,
Kate Stoneb9c1b512016-09-06 20:57:50 +00005878 prefer_file_cache);
5879 if (disassembler_sp)
5880 insn_list = &disassembler_sp->GetInstructionList();
5881
5882 if (insn_list == nullptr) {
5883 return retval;
5884 }
5885
5886 size_t insn_offset =
5887 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5888 if (insn_offset == UINT32_MAX) {
5889 return retval;
5890 }
5891
5892 uint32_t branch_index =
Greg Claytondf225762019-05-09 20:39:34 +00005893 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target,
Jim Ingham434905b2019-12-16 17:38:13 -08005894 false /* ignore_calls*/,
5895 nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005896 if (branch_index == UINT32_MAX) {
5897 return retval;
5898 }
5899
5900 if (branch_index > insn_offset) {
5901 Address next_branch_insn_address =
5902 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5903 if (next_branch_insn_address.IsValid() &&
5904 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5905 retval = next_branch_insn_address;
5906 }
5907 }
5908
5909 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00005910}
Howard Hellyerad007562016-07-07 08:21:28 +00005911
Zachary Turner97206d52017-05-12 04:51:55 +00005912Status
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005913Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00005914
Zachary Turner97206d52017-05-12 04:51:55 +00005915 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00005916
Kate Stoneb9c1b512016-09-06 20:57:50 +00005917 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00005918
Kate Stoneb9c1b512016-09-06 20:57:50 +00005919 region_list.clear();
5920 do {
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005921 lldb_private::MemoryRegionInfo region_info;
5922 error = GetMemoryRegionInfo(range_end, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005923 // GetMemoryRegionInfo should only return an error if it is unimplemented.
5924 if (error.Fail()) {
5925 region_list.clear();
5926 break;
Todd Fiala75930012016-08-19 04:21:48 +00005927 }
5928
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005929 range_end = region_info.GetRange().GetRangeEnd();
5930 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5931 region_list.push_back(std::move(region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005932 }
5933 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00005934
Kate Stoneb9c1b512016-09-06 20:57:50 +00005935 return error;
5936}
5937
Zachary Turner97206d52017-05-12 04:51:55 +00005938Status
Adrian Prantl0e4c4822019-03-06 21:22:25 +00005939Process::ConfigureStructuredData(ConstString type_name,
Zachary Turner97206d52017-05-12 04:51:55 +00005940 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005941 // If you get this, the Process-derived class needs to implement a method to
5942 // enable an already-reported asynchronous structured data feature. See
5943 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00005944 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005945}
5946
5947void Process::MapSupportedStructuredDataPlugins(
5948 const StructuredData::Array &supported_type_names) {
5949 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5950
5951 // Bail out early if there are no type names to map.
5952 if (supported_type_names.GetSize() == 0) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005953 LLDB_LOGF(log, "Process::%s(): no structured data types supported",
5954 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005955 return;
5956 }
Todd Fiala75930012016-08-19 04:21:48 +00005957
Kate Stoneb9c1b512016-09-06 20:57:50 +00005958 // Convert StructuredData type names to ConstString instances.
5959 std::set<ConstString> const_type_names;
5960
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005961 LLDB_LOGF(log,
5962 "Process::%s(): the process supports the following async "
5963 "structured data types:",
5964 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005965
5966 supported_type_names.ForEach(
5967 [&const_type_names, &log](StructuredData::Object *object) {
5968 if (!object) {
5969 // Invalid - shouldn't be null objects in the array.
5970 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005971 }
5972
5973 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005974 if (!type_name) {
5975 // Invalid format - all type names should be strings.
5976 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005977 }
5978
5979 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00005980 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00005981 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005982 });
Todd Fiala75930012016-08-19 04:21:48 +00005983
Adrian Prantl05097242018-04-30 16:49:04 +00005984 // For each StructuredDataPlugin, if the plugin handles any of the types in
5985 // the supported_type_names, map that type name to that plugin. Stop when
5986 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005987 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00005988 // supports?
5989 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
5990 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00005991 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
5992 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00005993 if (!create_instance)
5994 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005995
Kate Stoneb9c1b512016-09-06 20:57:50 +00005996 // Create the plugin.
5997 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
5998 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005999 // This plugin doesn't think it can work with the process. Move on to the
6000 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006001 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006002 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006003
Adrian Prantl05097242018-04-30 16:49:04 +00006004 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006005 std::vector<ConstString> names_to_remove;
6006 for (auto &type_name : const_type_names) {
6007 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6008 m_structured_data_plugin_map.insert(
6009 std::make_pair(type_name, plugin_sp));
6010 names_to_remove.push_back(type_name);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00006011 LLDB_LOGF(log,
6012 "Process::%s(): using plugin %s for type name "
6013 "%s",
6014 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6015 type_name.GetCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00006016 }
6017 }
6018
6019 // Remove the type names that were consumed by this plugin.
6020 for (auto &type_name : names_to_remove)
6021 const_type_names.erase(type_name);
6022 }
Todd Fiala75930012016-08-19 04:21:48 +00006023}
6024
Kate Stoneb9c1b512016-09-06 20:57:50 +00006025bool Process::RouteAsyncStructuredData(
6026 const StructuredData::ObjectSP object_sp) {
6027 // Nothing to do if there's no data.
6028 if (!object_sp)
6029 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006030
Adrian Prantl05097242018-04-30 16:49:04 +00006031 // The contract is this must be a dictionary, so we can look up the routing
6032 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006033 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6034 if (!dictionary)
6035 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006036
Kate Stoneb9c1b512016-09-06 20:57:50 +00006037 // Grab the async structured type name (i.e. the feature/plugin name).
6038 ConstString type_name;
6039 if (!dictionary->GetValueForKeyAsString("type", type_name))
6040 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006041
Kate Stoneb9c1b512016-09-06 20:57:50 +00006042 // Check if there's a plugin registered for this type name.
6043 auto find_it = m_structured_data_plugin_map.find(type_name);
6044 if (find_it == m_structured_data_plugin_map.end()) {
6045 // We don't have a mapping for this structured data type.
6046 return false;
6047 }
Todd Fiala75930012016-08-19 04:21:48 +00006048
Kate Stoneb9c1b512016-09-06 20:57:50 +00006049 // Route the structured data to the plugin.
6050 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6051 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006052}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006053
Zachary Turner97206d52017-05-12 04:51:55 +00006054Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006055 // Default implementation does nothign.
6056 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00006057 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006058}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006059
Frederic Rissd10d3792018-05-11 18:21:11 +00006060UtilityFunction *Process::GetLoadImageUtilityFunction(
6061 Platform *platform,
6062 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006063 if (platform != GetTarget().GetPlatform().get())
6064 return nullptr;
Michal Gorny3276fff2019-09-03 12:31:24 +00006065 llvm::call_once(m_dlopen_utility_func_flag_once,
6066 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006067 return m_dlopen_utility_func_up.get();
6068}
Alex Langford5b2b38e2019-09-13 00:02:05 +00006069
6070bool Process::CallVoidArgVoidPtrReturn(const Address *address,
6071 addr_t &returned_func,
6072 bool trap_exceptions) {
6073 Thread *thread = GetThreadList().GetExpressionExecutionThread().get();
6074 if (thread == nullptr || address == nullptr)
6075 return false;
6076
6077 EvaluateExpressionOptions options;
6078 options.SetStopOthers(true);
6079 options.SetUnwindOnError(true);
6080 options.SetIgnoreBreakpoints(true);
6081 options.SetTryAllThreads(true);
6082 options.SetDebug(false);
6083 options.SetTimeout(GetUtilityExpressionTimeout());
6084 options.SetTrapExceptions(trap_exceptions);
6085
6086 auto type_system_or_err =
6087 GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC);
6088 if (!type_system_or_err) {
6089 llvm::consumeError(type_system_or_err.takeError());
6090 return false;
6091 }
6092 CompilerType void_ptr_type =
6093 type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
6094 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction(
6095 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
6096 if (call_plan_sp) {
6097 DiagnosticManager diagnostics;
6098
6099 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6100 if (frame) {
6101 ExecutionContext exe_ctx;
6102 frame->CalculateExecutionContext(exe_ctx);
6103 ExpressionResults result =
6104 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
6105 if (result == eExpressionCompleted) {
6106 returned_func =
6107 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6108 LLDB_INVALID_ADDRESS);
6109
6110 if (GetAddressByteSize() == 4) {
6111 if (returned_func == UINT32_MAX)
6112 return false;
6113 } else if (GetAddressByteSize() == 8) {
6114 if (returned_func == UINT64_MAX)
6115 return false;
6116 }
6117 return true;
6118 }
6119 }
6120 }
6121
6122 return false;
6123}