blob: b7694ec43f34177d2e3d884af9cc65a32cb1dd69 [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
Jonas Devlieghere06412da2020-06-24 17:44:33 -0700167 m_experimental_properties_up =
168 std::make_unique<ProcessExperimentalProperties>();
Jonas Devlieghere018e5a92020-05-19 11:16:57 -0700169 m_collection_sp->AppendProperty(
170 ConstString(Properties::GetExperimentalSettingsName()),
171 ConstString("Experimental settings - setting these won't produce "
172 "errors if the setting is not present."),
173 true, m_experimental_properties_up->GetValueProperties());
Greg Clayton67cc0632012-08-22 17:17:09 +0000174}
175
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000176ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000177
Kate Stoneb9c1b512016-09-06 20:57:50 +0000178bool ProcessProperties::GetDisableMemoryCache() const {
179 const uint32_t idx = ePropertyDisableMemCache;
180 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000181 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000182}
183
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
185 const uint32_t idx = ePropertyMemCacheLineSize;
186 return m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000187 nullptr, idx, g_process_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000188}
189
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190Args ProcessProperties::GetExtraStartupCommands() const {
191 Args args;
192 const uint32_t idx = ePropertyExtraStartCommand;
193 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
194 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000195}
196
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197void ProcessProperties::SetExtraStartupCommands(const Args &args) {
198 const uint32_t idx = ePropertyExtraStartCommand;
199 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000200}
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202FileSpec ProcessProperties::GetPythonOSPluginPath() const {
203 const uint32_t idx = ePropertyPythonOSPluginPath;
204 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000205}
206
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
208 const uint32_t idx = ePropertyPythonOSPluginPath;
209 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000210}
211
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
213 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
214 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000215 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000216}
217
Kate Stoneb9c1b512016-09-06 20:57:50 +0000218void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
219 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
220 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000221}
222
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
224 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
225 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000226 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000227}
228
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
230 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
231 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000232}
233
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
235 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
236 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000237 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000238}
239
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
241 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
242 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
243}
244
245bool ProcessProperties::GetDetachKeepsStopped() const {
246 const uint32_t idx = ePropertyDetachKeepsStopped;
247 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000248 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249}
250
251void ProcessProperties::SetDetachKeepsStopped(bool stop) {
252 const uint32_t idx = ePropertyDetachKeepsStopped;
253 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
254}
255
256bool ProcessProperties::GetWarningsOptimization() const {
257 const uint32_t idx = ePropertyWarningOptimization;
258 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000259 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260}
261
Adrian Prantl220c17f2020-05-21 17:42:24 -0700262bool ProcessProperties::GetWarningsUnsupportedLanguage() const {
263 const uint32_t idx = ePropertyWarningUnsupportedLanguage;
264 return m_collection_sp->GetPropertyAtIndexAsBoolean(
265 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
266}
267
Jim Inghamba205c12017-12-05 02:50:45 +0000268bool ProcessProperties::GetStopOnExec() const {
269 const uint32_t idx = ePropertyStopOnExec;
270 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000271 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Inghamba205c12017-12-05 02:50:45 +0000272}
273
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000274std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
275 const uint32_t idx = ePropertyUtilityExpressionTimeout;
276 uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000277 nullptr, idx, g_process_properties[idx].default_uint_value);
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000278 return std::chrono::seconds(value);
279}
280
Jonas Devlieghere018e5a92020-05-19 11:16:57 -0700281bool ProcessProperties::GetOSPluginReportsAllThreads() const {
282 const bool fail_value = true;
283 const Property *exp_property =
284 m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental);
285 OptionValueProperties *exp_values =
286 exp_property->GetValue()->GetAsProperties();
287 if (!exp_values)
288 return fail_value;
289
290 return exp_values->GetPropertyAtIndexAsBoolean(
291 nullptr, ePropertyOSPluginReportsAllThreads, fail_value);
292}
293
294void ProcessProperties::SetOSPluginReportsAllThreads(bool does_report) {
295 const Property *exp_property =
296 m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental);
297 OptionValueProperties *exp_values =
298 exp_property->GetValue()->GetAsProperties();
299 if (exp_values)
300 exp_values->SetPropertyAtIndexAsBoolean(
301 nullptr, ePropertyOSPluginReportsAllThreads, does_report);
302}
303
Zachary Turner97206d52017-05-12 04:51:55 +0000304Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000305 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000307 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308 const int short_option = m_getopt_table[option_idx].val;
309
310 switch (short_option) {
311 case 's': // Stop at program entry point
312 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
313 break;
314
315 case 'i': // STDIN for read only
316 {
317 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000318 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 launch_info.AppendFileAction(action);
320 break;
321 }
322
323 case 'o': // Open STDOUT for write only
324 {
325 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000326 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327 launch_info.AppendFileAction(action);
328 break;
329 }
330
331 case 'e': // STDERR for write only
332 {
333 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000334 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 launch_info.AppendFileAction(action);
336 break;
337 }
338
339 case 'p': // Process plug-in name
340 launch_info.SetProcessPluginName(option_arg);
341 break;
342
343 case 'n': // Disable STDIO
344 {
345 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000346 const FileSpec dev_null(FileSystem::DEV_NULL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 if (action.Open(STDIN_FILENO, dev_null, true, false))
348 launch_info.AppendFileAction(action);
349 if (action.Open(STDOUT_FILENO, dev_null, false, true))
350 launch_info.AppendFileAction(action);
351 if (action.Open(STDERR_FILENO, dev_null, false, true))
352 launch_info.AppendFileAction(action);
353 break;
354 }
355
356 case 'w':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000357 launch_info.SetWorkingDirectory(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 break;
359
360 case 't': // Open process in new terminal window
361 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
362 break;
363
364 case 'a': {
365 TargetSP target_sp =
366 execution_context ? execution_context->GetTargetSP() : TargetSP();
367 PlatformSP platform_sp =
368 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000369 launch_info.GetArchitecture() =
370 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 } break;
372
373 case 'A': // Disable ASLR.
374 {
375 bool success;
376 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000377 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378 if (success)
379 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000380 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 error.SetErrorStringWithFormat(
382 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000383 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 break;
385 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000386
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 case 'X': // shell expand args.
388 {
389 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000390 const bool expand_args =
391 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 if (success)
393 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000394 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 error.SetErrorStringWithFormat(
396 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000397 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 break;
399 }
400
401 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000402 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000403 launch_info.SetShell(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 else
405 launch_info.SetShell(HostInfo::GetDefaultShell());
406 break;
407
408 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000409 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 break;
411
412 default:
413 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
414 short_option);
415 break;
416 }
417 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000418}
419
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000420static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000422 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 "Stop at the entry point of the program when launching a process."},
424 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000425 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426 "Set whether to disable address space layout randomization when launching "
427 "a process."},
428 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000429 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 "Name of the process plugin you want to use."},
431 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000432 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 eArgTypeDirectoryName,
434 "Set the current working directory to <path> when running the inferior."},
435 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000436 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 "Set the architecture for the process to launch when ambiguous."},
438 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000439 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000440 "Specify an environment variable name/value string (--environment "
441 "NAME=VALUE). Can be specified multiple times for subsequent environment "
442 "entries."},
443 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000444 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000446
Kate Stoneb9c1b512016-09-06 20:57:50 +0000447 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000448 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000449 "Redirect stdin for the process to <filename>."},
450 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000451 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 "Redirect stdout for the process to <filename>."},
453 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000454 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000456
Kate Stoneb9c1b512016-09-06 20:57:50 +0000457 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000458 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000460
Kate Stoneb9c1b512016-09-06 20:57:50 +0000461 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000462 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 "Do not set up for terminal I/O to go to running process."},
464 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000465 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000466 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000467};
468
469llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000470 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000471}
Greg Clayton32e0a752011-03-30 18:16:51 +0000472
Zachary Turner31659452016-11-17 21:15:14 +0000473ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
474 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000475 ListenerSP listener_sp,
476 const FileSpec *crash_file_path) {
477 static uint32_t g_process_unique_id = 0;
478
479 ProcessSP process_sp;
480 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000481 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 ConstString const_plugin_name(plugin_name);
483 create_callback =
484 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
485 if (create_callback) {
486 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
487 if (process_sp) {
488 if (process_sp->CanDebug(target_sp, true)) {
489 process_sp->m_process_unique_id = ++g_process_unique_id;
490 } else
491 process_sp.reset();
492 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000493 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 } else {
495 for (uint32_t idx = 0;
496 (create_callback =
497 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
498 ++idx) {
499 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
500 if (process_sp) {
501 if (process_sp->CanDebug(target_sp, false)) {
502 process_sp->m_process_unique_id = ++g_process_unique_id;
503 break;
504 } else
505 process_sp.reset();
506 }
507 }
508 }
509 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000510}
511
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512ConstString &Process::GetStaticBroadcasterClass() {
513 static ConstString class_name("lldb.process");
514 return class_name;
515}
516
517Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
518 : Process(target_sp, listener_sp,
519 UnixSignals::Create(HostInfo::GetArchitecture())) {
520 // This constructor just delegates to the full Process constructor,
521 // defaulting to using the Host's UnixSignals.
522}
523
524Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
525 const UnixSignalsSP &unix_signals_sp)
526 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
527 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
528 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000529 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530 m_private_state(eStateUnloaded),
531 m_private_state_broadcaster(nullptr,
532 "lldb.process.internal_state_broadcaster"),
533 m_private_state_control_broadcaster(
534 nullptr, "lldb.process.internal_state_control_broadcaster"),
535 m_private_state_listener_sp(
536 Listener::MakeListener("lldb.process.internal_state_listener")),
537 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
538 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
539 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
Jim Ingham18930652020-03-18 12:05:08 -0700540 m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
542 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000543 m_breakpoint_site_list(), m_dynamic_checkers_up(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
545 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
546 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
547 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
548 m_memory_cache(*this), m_allocated_memory_cache(*this),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000549 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000550 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
552 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
553 m_can_interpret_function_calls(false), m_warnings_issued(),
554 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
555 CheckInWithManager();
556
557 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000558 LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559
560 if (!m_unix_signals_sp)
561 m_unix_signals_sp = std::make_shared<UnixSignals>();
562
563 SetEventName(eBroadcastBitStateChanged, "state-changed");
564 SetEventName(eBroadcastBitInterrupt, "interrupt");
565 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
566 SetEventName(eBroadcastBitSTDERR, "stderr-available");
567 SetEventName(eBroadcastBitProfileData, "profile-data-available");
568 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
569
570 m_private_state_control_broadcaster.SetEventName(
571 eBroadcastInternalStateControlStop, "control-stop");
572 m_private_state_control_broadcaster.SetEventName(
573 eBroadcastInternalStateControlPause, "control-pause");
574 m_private_state_control_broadcaster.SetEventName(
575 eBroadcastInternalStateControlResume, "control-resume");
576
577 m_listener_sp->StartListeningForEvents(
578 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
579 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
580 eBroadcastBitProfileData | eBroadcastBitStructuredData);
581
582 m_private_state_listener_sp->StartListeningForEvents(
583 &m_private_state_broadcaster,
584 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
585
586 m_private_state_listener_sp->StartListeningForEvents(
587 &m_private_state_control_broadcaster,
588 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
589 eBroadcastInternalStateControlResume);
590 // We need something valid here, even if just the default UnixSignalsSP.
591 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
592
593 // Allow the platform to override the default cache line size
594 OptionValueSP value_sp =
595 m_collection_sp
596 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
597 ->GetValue();
598 uint32_t platform_cache_line_size =
599 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
600 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
601 value_sp->SetUInt64Value(platform_cache_line_size);
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100602
603 RegisterAssertFrameRecognizer(this);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604}
605
606Process::~Process() {
607 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000608 LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 StopPrivateStateThread();
610
611 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000612 // explicitly clear the thread list here to ensure that the mutex is not
613 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 m_thread_list.Clear();
615}
616
617const ProcessPropertiesSP &Process::GetGlobalProperties() {
618 // NOTE: intentional leak so we don't crash if global destructor chain gets
619 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000620 static ProcessPropertiesSP *g_settings_sp_ptr =
621 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622 return *g_settings_sp_ptr;
623}
624
625void Process::Finalize() {
626 m_finalizing = true;
627
628 // Destroy this process if needed
629 switch (GetPrivateState()) {
630 case eStateConnected:
631 case eStateAttaching:
632 case eStateLaunching:
633 case eStateStopped:
634 case eStateRunning:
635 case eStateStepping:
636 case eStateCrashed:
637 case eStateSuspended:
638 Destroy(false);
639 break;
640
641 case eStateInvalid:
642 case eStateUnloaded:
643 case eStateDetached:
644 case eStateExited:
645 break;
646 }
647
648 // Clear our broadcaster before we proceed with destroying
649 Broadcaster::Clear();
650
Adrian Prantl05097242018-04-30 16:49:04 +0000651 // Do any cleanup needed prior to being destructed... Subclasses that
652 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653
654 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000655 // destroyed since it is very likely that undoing the loader will require
656 // access to the real process.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000657 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000659 m_os_up.reset();
660 m_system_runtime_up.reset();
661 m_dyld_up.reset();
662 m_jit_loaders_up.reset();
Jim Ingham61e8e682020-03-10 16:18:11 -0700663 m_thread_plans.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 m_thread_list_real.Destroy();
665 m_thread_list.Destroy();
666 m_extended_thread_list.Destroy();
667 m_queue_list.Clear();
668 m_queue_list_stop_id = 0;
669 std::vector<Notifications> empty_notifications;
670 m_notifications.swap(empty_notifications);
671 m_image_tokens.clear();
672 m_memory_cache.Clear();
673 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +0000674 {
675 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
676 m_language_runtimes.clear();
677 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678 m_instrumentation_runtimes.clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000679 m_next_event_action_up.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000680 // Clear the last natural stop ID since it has a strong reference to this
681 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000682 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
683 //#ifdef LLDB_CONFIGURATION_DEBUG
684 // StreamFile s(stdout, false);
685 // EventSP event_sp;
686 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
687 // {
688 // event_sp->Dump (&s);
689 // s.EOL();
690 // }
691 //#endif
692 // We have to be very careful here as the m_private_state_listener might
693 // contain events that have ProcessSP values in them which can keep this
694 // process around forever. These events need to be cleared out.
695 m_private_state_listener_sp->Clear();
696 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
697 m_public_run_lock.SetStopped();
698 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
699 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000700 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 m_finalize_called = true;
702}
703
704void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
705 m_notifications.push_back(callbacks);
706 if (callbacks.initialize != nullptr)
707 callbacks.initialize(callbacks.baton, this);
708}
709
710bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
711 std::vector<Notifications>::iterator pos, end = m_notifications.end();
712 for (pos = m_notifications.begin(); pos != end; ++pos) {
713 if (pos->baton == callbacks.baton &&
714 pos->initialize == callbacks.initialize &&
715 pos->process_state_changed == callbacks.process_state_changed) {
716 m_notifications.erase(pos);
717 return true;
718 }
719 }
720 return false;
721}
722
723void Process::SynchronouslyNotifyStateChanged(StateType state) {
724 std::vector<Notifications>::iterator notification_pos,
725 notification_end = m_notifications.end();
726 for (notification_pos = m_notifications.begin();
727 notification_pos != notification_end; ++notification_pos) {
728 if (notification_pos->process_state_changed)
729 notification_pos->process_state_changed(notification_pos->baton, this,
730 state);
731 }
732}
733
734// FIXME: We need to do some work on events before the general Listener sees
735// them.
736// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000737// we do the little "insert real insn, step & stop" trick. But we can't do
738// that when the event is delivered by the broadcaster - since that is done on
739// the thread that is waiting for new events, so if we needed more than one
740// event for our handling, we would stall. So instead we do it when we fetch
741// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742//
743
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744StateType Process::GetNextEvent(EventSP &event_sp) {
745 StateType state = eStateInvalid;
746
Pavel Labathd35031e12016-11-30 10:41:42 +0000747 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
748 std::chrono::seconds(0)) &&
749 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
751
752 return state;
753}
754
Pavel Labath3879fe02018-05-09 14:29:30 +0000755void Process::SyncIOHandler(uint32_t iohandler_id,
756 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000757 // don't sync (potentially context switch) in case where there is no process
758 // IO
759 if (!m_process_input_reader)
760 return;
761
Pavel Labath3879fe02018-05-09 14:29:30 +0000762 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763
764 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000765 if (Result) {
766 LLDB_LOG(
767 log,
768 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
769 iohandler_id, *Result);
770 } else {
771 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
772 iohandler_id);
773 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000774}
775
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000776StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
777 EventSP *event_sp_ptr, bool wait_always,
778 ListenerSP hijack_listener_sp,
779 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000781 // have restarted the target. We have to actually check each event, and in
782 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 if (event_sp_ptr)
784 event_sp_ptr->reset();
785 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000786 // If we are exited or detached, we won't ever get back to any other valid
787 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000789 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000790
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000792 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000793
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 if (!wait_always && StateIsStoppedState(state, true) &&
795 StateIsStoppedState(GetPrivateState(), true)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000796 LLDB_LOGF(log,
797 "Process::%s returning without waiting for events; process "
798 "private and public states are already 'stopped'.",
799 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 // We need to toggle the run lock as this won't get done in
801 // SetPublicState() if the process is hijacked.
802 if (hijack_listener_sp && use_run_lock)
803 m_public_run_lock.SetStopped();
804 return state;
805 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000806
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807 while (state != eStateInvalid) {
808 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000809 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 if (event_sp_ptr && event_sp)
811 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +0000812
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
814 Process::HandleProcessStateChangedEvent(event_sp, stream,
815 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +0000816
Kate Stoneb9c1b512016-09-06 20:57:50 +0000817 switch (state) {
818 case eStateCrashed:
819 case eStateDetached:
820 case eStateExited:
821 case eStateUnloaded:
822 // We need to toggle the run lock as this won't get done in
823 // SetPublicState() if the process is hijacked.
824 if (hijack_listener_sp && use_run_lock)
825 m_public_run_lock.SetStopped();
826 return state;
827 case eStateStopped:
828 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
829 continue;
830 else {
Pavel Labath78521ef2015-03-06 10:52:47 +0000831 // We need to toggle the run lock as this won't get done in
832 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +0000833 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 m_public_run_lock.SetStopped();
835 return state;
836 }
837 default:
838 continue;
839 }
840 }
841 return state;
842}
843
844bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
845 Stream *stream,
846 bool &pop_process_io_handler) {
847 const bool handle_pop = pop_process_io_handler;
848
849 pop_process_io_handler = false;
850 ProcessSP process_sp =
851 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
852
853 if (!process_sp)
854 return false;
855
856 StateType event_state =
857 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
858 if (event_state == eStateInvalid)
859 return false;
860
861 switch (event_state) {
862 case eStateInvalid:
863 case eStateUnloaded:
864 case eStateAttaching:
865 case eStateLaunching:
866 case eStateStepping:
867 case eStateDetached:
868 if (stream)
869 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
870 StateAsCString(event_state));
871 if (event_state == eStateDetached)
872 pop_process_io_handler = true;
873 break;
874
875 case eStateConnected:
876 case eStateRunning:
877 // Don't be chatty when we run...
878 break;
879
880 case eStateExited:
881 if (stream)
882 process_sp->GetStatus(*stream);
883 pop_process_io_handler = true;
884 break;
885
886 case eStateStopped:
887 case eStateCrashed:
888 case eStateSuspended:
889 // Make sure the program hasn't been auto-restarted:
890 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
891 if (stream) {
892 size_t num_reasons =
893 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
894 if (num_reasons > 0) {
895 // FIXME: Do we want to report this, or would that just be annoyingly
896 // chatty?
897 if (num_reasons == 1) {
898 const char *reason =
899 Process::ProcessEventData::GetRestartedReasonAtIndex(
900 event_sp.get(), 0);
901 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
902 process_sp->GetID(),
903 reason ? reason : "<UNKNOWN REASON>");
904 } else {
905 stream->Printf("Process %" PRIu64
906 " stopped and restarted, reasons:\n",
907 process_sp->GetID());
908
909 for (size_t i = 0; i < num_reasons; i++) {
910 const char *reason =
911 Process::ProcessEventData::GetRestartedReasonAtIndex(
912 event_sp.get(), i);
913 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
914 }
915 }
916 }
917 }
918 } else {
919 StopInfoSP curr_thread_stop_info_sp;
920 // Lock the thread list so it doesn't change on us, this is the scope for
921 // the locker:
922 {
923 ThreadList &thread_list = process_sp->GetThreadList();
924 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
925
926 ThreadSP curr_thread(thread_list.GetSelectedThread());
927 ThreadSP thread;
928 StopReason curr_thread_stop_reason = eStopReasonInvalid;
929 if (curr_thread) {
930 curr_thread_stop_reason = curr_thread->GetStopReason();
931 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
932 }
933 if (!curr_thread || !curr_thread->IsValid() ||
934 curr_thread_stop_reason == eStopReasonInvalid ||
935 curr_thread_stop_reason == eStopReasonNone) {
936 // Prefer a thread that has just completed its plan over another
937 // thread as current thread.
938 ThreadSP plan_thread;
939 ThreadSP other_thread;
940
941 const size_t num_threads = thread_list.GetSize();
942 size_t i;
943 for (i = 0; i < num_threads; ++i) {
944 thread = thread_list.GetThreadAtIndex(i);
945 StopReason thread_stop_reason = thread->GetStopReason();
946 switch (thread_stop_reason) {
947 case eStopReasonInvalid:
948 case eStopReasonNone:
949 break;
950
951 case eStopReasonSignal: {
952 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +0000953 // that signal. We have to have had another reason for stopping
954 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 uint64_t signo = thread->GetStopInfo()->GetValue();
956 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
957 if (!other_thread)
958 other_thread = thread;
959 }
960 break;
961 }
962 case eStopReasonTrace:
963 case eStopReasonBreakpoint:
964 case eStopReasonWatchpoint:
965 case eStopReasonException:
966 case eStopReasonExec:
967 case eStopReasonThreadExiting:
968 case eStopReasonInstrumentation:
969 if (!other_thread)
970 other_thread = thread;
971 break;
972 case eStopReasonPlanComplete:
973 if (!plan_thread)
974 plan_thread = thread;
975 break;
976 }
977 }
978 if (plan_thread)
979 thread_list.SetSelectedThreadByID(plan_thread->GetID());
980 else if (other_thread)
981 thread_list.SetSelectedThreadByID(other_thread->GetID());
982 else {
983 if (curr_thread && curr_thread->IsValid())
984 thread = curr_thread;
985 else
986 thread = thread_list.GetThreadAtIndex(0);
987
988 if (thread)
989 thread_list.SetSelectedThreadByID(thread->GetID());
990 }
991 }
992 }
993 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +0000994 // have to run code, e.g. for Data formatters, and if we hold the
995 // ThreadList mutex, then the process is going to have a hard time
996 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997 if (stream) {
998 Debugger &debugger = process_sp->GetTarget().GetDebugger();
999 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1000 &process_sp->GetTarget()) {
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +01001001 ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
1002
1003 if (!thread_sp || !thread_sp->IsValid())
1004 return false;
1005
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 const bool only_threads_with_stop_reason = true;
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +01001007 const uint32_t start_frame = thread_sp->GetSelectedFrameIndex();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 const uint32_t num_frames = 1;
1009 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001010 const bool stop_format = true;
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +01001011
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 process_sp->GetStatus(*stream);
1013 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1014 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001015 num_frames_with_source,
1016 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 if (curr_thread_stop_info_sp) {
1018 lldb::addr_t crashing_address;
1019 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1020 curr_thread_stop_info_sp, &crashing_address);
1021 if (valobj_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022 const ValueObject::GetExpressionPathFormat format =
1023 ValueObject::GetExpressionPathFormat::
1024 eGetExpressionPathFormatHonorPointers;
1025 stream->PutCString("Likely cause: ");
Alex Langford3014efe2020-02-02 14:17:02 -08001026 valobj_sp->GetExpressionPath(*stream, format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1028 }
1029 }
1030 } else {
1031 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1032 process_sp->GetTarget().shared_from_this());
1033 if (target_idx != UINT32_MAX)
1034 stream->Printf("Target %d: (", target_idx);
1035 else
1036 stream->Printf("Target <unknown index>: (");
1037 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1038 stream->Printf(") stopped.\n");
1039 }
1040 }
1041
1042 // Pop the process IO handler
1043 pop_process_io_handler = true;
1044 }
1045 break;
1046 }
1047
1048 if (handle_pop && pop_process_io_handler)
1049 process_sp->PopProcessIOHandler();
1050
1051 return true;
1052}
1053
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1055 if (listener_sp) {
1056 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1057 eBroadcastBitInterrupt);
1058 } else
1059 return false;
1060}
Greg Claytondc6224e2014-10-21 01:00:42 +00001061
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001063
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001064StateType Process::GetStateChangedEvents(EventSP &event_sp,
1065 const Timeout<std::micro> &timeout,
1066 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001068 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001069
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070 ListenerSP listener_sp = hijack_listener_sp;
1071 if (!listener_sp)
1072 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001073
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001075 if (listener_sp->GetEventForBroadcasterWithType(
1076 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001077 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1079 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001080 else
1081 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001083
Pavel Labathd02b1c82017-02-10 11:49:33 +00001084 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 return state;
1086}
Greg Claytondc6224e2014-10-21 01:00:42 +00001087
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088Event *Process::PeekAtStateChangedEvents() {
1089 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001090
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001091 LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001092
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 Event *event_ptr;
1094 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1095 this, eBroadcastBitStateChanged);
1096 if (log) {
1097 if (event_ptr) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001098 LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
1099 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001101 LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001102 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103 }
1104 return event_ptr;
1105}
Greg Claytondc6224e2014-10-21 01:00:42 +00001106
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001107StateType
1108Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1109 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001111 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112
1113 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001114 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1115 &m_private_state_broadcaster,
1116 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001117 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1119 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1120
Pavel Labathd02b1c82017-02-10 11:49:33 +00001121 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1122 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 return state;
1124}
1125
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001126bool Process::GetEventsPrivate(EventSP &event_sp,
1127 const Timeout<std::micro> &timeout,
1128 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001130 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001131
1132 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001133 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001134 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001135 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001136 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001137}
1138
1139bool Process::IsRunning() const {
1140 return StateIsRunningState(m_public_state.GetValue());
1141}
1142
1143int Process::GetExitStatus() {
1144 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1145
1146 if (m_public_state.GetValue() == eStateExited)
1147 return m_exit_status;
1148 return -1;
1149}
1150
1151const char *Process::GetExitDescription() {
1152 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1153
1154 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1155 return m_exit_string.c_str();
1156 return nullptr;
1157}
1158
1159bool Process::SetExitStatus(int status, const char *cstr) {
1160 // Use a mutex to protect setting the exit status.
1161 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1162
1163 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1164 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001165 LLDB_LOGF(
1166 log, "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1167 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", cstr ? "\"" : "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168
1169 // We were already in the exited state
1170 if (m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001171 LLDB_LOGF(log, "Process::SetExitStatus () ignoring exit status because "
1172 "state was already set to eStateExited");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 return false;
1174 }
1175
1176 m_exit_status = status;
1177 if (cstr)
1178 m_exit_string = cstr;
1179 else
1180 m_exit_string.clear();
1181
Adrian Prantl05097242018-04-30 16:49:04 +00001182 // Clear the last natural stop ID since it has a strong reference to this
1183 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001184 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1185
1186 SetPrivateState(eStateExited);
1187
1188 // Allow subclasses to do some cleanup
1189 DidExit();
1190
1191 return true;
1192}
1193
1194bool Process::IsAlive() {
1195 switch (m_private_state.GetValue()) {
1196 case eStateConnected:
1197 case eStateAttaching:
1198 case eStateLaunching:
1199 case eStateStopped:
1200 case eStateRunning:
1201 case eStateStepping:
1202 case eStateCrashed:
1203 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001204 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 default:
1206 return false;
1207 }
Jason Molendaa814f702015-11-05 23:03:44 +00001208}
1209
Adrian Prantl05097242018-04-30 16:49:04 +00001210// This static callback can be used to watch for local child processes on the
1211// current host. The child process exits, the process will be found in the
1212// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001213// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214bool Process::SetProcessExitStatus(
1215 lldb::pid_t pid, bool exited,
1216 int signo, // Zero for no signal
1217 int exit_status // Exit value of process if signal is zero
1218 ) {
1219 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001220 LLDB_LOGF(log,
1221 "Process::SetProcessExitStatus (pid=%" PRIu64
1222 ", exited=%i, signal=%i, exit_status=%i)\n",
1223 pid, exited, signo, exit_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001224
1225 if (exited) {
1226 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1227 if (target_sp) {
1228 ProcessSP process_sp(target_sp->GetProcessSP());
1229 if (process_sp) {
1230 const char *signal_cstr = nullptr;
1231 if (signo)
1232 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1233
1234 process_sp->SetExitStatus(exit_status, signal_cstr);
1235 }
1236 }
1237 return true;
1238 }
1239 return false;
1240}
1241
1242void Process::UpdateThreadListIfNeeded() {
1243 const uint32_t stop_id = GetStopID();
1244 if (m_thread_list.GetSize(false) == 0 ||
1245 stop_id != m_thread_list.GetStopID()) {
Jim Ingham18930652020-03-18 12:05:08 -07001246 bool clear_unused_threads = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 const StateType state = GetPrivateState();
1248 if (StateIsStoppedState(state, true)) {
1249 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Jim Ingham18930652020-03-18 12:05:08 -07001250 m_thread_list.SetStopID(stop_id);
1251
Adrian Prantl05097242018-04-30 16:49:04 +00001252 // m_thread_list does have its own mutex, but we need to hold onto the
1253 // mutex between the call to UpdateThreadList(...) and the
1254 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 ThreadList &old_thread_list = m_thread_list;
1256 ThreadList real_thread_list(this);
1257 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001258 // Always update the thread list with the protocol specific thread list,
1259 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001260 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1261 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001262 // are shutting down, since that may call back into the SBAPI's,
1263 // requiring the API lock which is already held by whoever is shutting
1264 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 OperatingSystem *os = GetOperatingSystem();
1266 if (os && !m_destroy_in_process) {
1267 // Clear any old backing threads where memory threads might have been
1268 // backed by actual threads from the lldb_private::Process subclass
1269 size_t num_old_threads = old_thread_list.GetSize(false);
1270 for (size_t i = 0; i < num_old_threads; ++i)
1271 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Jim Ingham18930652020-03-18 12:05:08 -07001272 // See if the OS plugin reports all threads. If it does, then
Jonas Devlieghere32d35fb2020-07-13 13:44:01 -07001273 // it is safe to clear unseen thread's plans here. Otherwise we
Jim Ingham18930652020-03-18 12:05:08 -07001274 // should preserve them in case they show up again:
Jonas Devlieghere018e5a92020-05-19 11:16:57 -07001275 clear_unused_threads = GetOSPluginReportsAllThreads();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276
1277 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001278 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001279 // dynamic type or not and we need to avoid this. OperatingSystem
1280 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001281
1282 Target &target = GetTarget();
1283 const lldb::DynamicValueType saved_prefer_dynamic =
1284 target.GetPreferDynamicValue();
1285 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1286 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1287
1288 // Now let the OperatingSystem plug-in update the thread list
1289
1290 os->UpdateThreadList(
1291 old_thread_list, // Old list full of threads created by OS plug-in
1292 real_thread_list, // The actual thread list full of threads
1293 // created by each lldb_private::Process
1294 // subclass
1295 new_thread_list); // The new thread list that we will show to the
1296 // user that gets filled in
1297
1298 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1299 target.SetPreferDynamicValue(saved_prefer_dynamic);
1300 } else {
1301 // No OS plug-in, the new thread list is the same as the real thread
Jim Ingham18930652020-03-18 12:05:08 -07001302 // list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 new_thread_list = real_thread_list;
1304 }
1305
1306 m_thread_list_real.Update(real_thread_list);
1307 m_thread_list.Update(new_thread_list);
1308 m_thread_list.SetStopID(stop_id);
1309
1310 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1311 // Clear any extended threads that we may have accumulated previously
1312 m_extended_thread_list.Clear();
1313 m_extended_thread_stop_id = GetLastNaturalStopID();
1314
1315 m_queue_list.Clear();
1316 m_queue_list_stop_id = GetLastNaturalStopID();
1317 }
1318 }
Jim Ingham18930652020-03-18 12:05:08 -07001319 // Now update the plan stack map.
1320 // If we do have an OS plugin, any absent real threads in the
1321 // m_thread_list have already been removed from the ThreadPlanStackMap.
1322 // So any remaining threads are OS Plugin threads, and those we want to
1323 // preserve in case they show up again.
1324 m_thread_plans.Update(m_thread_list, clear_unused_threads);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001325 }
1326 }
1327}
1328
Jim Ingham61e8e682020-03-10 16:18:11 -07001329ThreadPlanStack *Process::FindThreadPlans(lldb::tid_t tid) {
1330 return m_thread_plans.Find(tid);
1331}
1332
Jim Ingham18930652020-03-18 12:05:08 -07001333bool Process::PruneThreadPlansForTID(lldb::tid_t tid) {
1334 return m_thread_plans.PrunePlansForTID(tid);
Jim Ingham61e8e682020-03-10 16:18:11 -07001335}
1336
Jim Ingham18930652020-03-18 12:05:08 -07001337void Process::PruneThreadPlans() {
1338 m_thread_plans.Update(GetThreadList(), true, false);
1339}
1340
1341bool Process::DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid,
1342 lldb::DescriptionLevel desc_level,
1343 bool internal, bool condense_trivial,
1344 bool skip_unreported_plans) {
1345 return m_thread_plans.DumpPlansForTID(
1346 strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
1347}
1348void Process::DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,
1349 bool internal, bool condense_trivial,
1350 bool skip_unreported_plans) {
1351 m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
1352 skip_unreported_plans);
Jim Ingham61e8e682020-03-10 16:18:11 -07001353}
1354
Kate Stoneb9c1b512016-09-06 20:57:50 +00001355void Process::UpdateQueueListIfNeeded() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001356 if (m_system_runtime_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001357 if (m_queue_list.GetSize() == 0 ||
1358 m_queue_list_stop_id != GetLastNaturalStopID()) {
1359 const StateType state = GetPrivateState();
1360 if (StateIsStoppedState(state, true)) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001361 m_system_runtime_up->PopulateQueueList(m_queue_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 m_queue_list_stop_id = GetLastNaturalStopID();
1363 }
1364 }
1365 }
1366}
1367
1368ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1369 OperatingSystem *os = GetOperatingSystem();
1370 if (os)
1371 return os->CreateThread(tid, context);
1372 return ThreadSP();
1373}
1374
1375uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1376 return AssignIndexIDToThread(thread_id);
1377}
1378
1379bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1380 return (m_thread_id_to_index_id_map.find(thread_id) !=
1381 m_thread_id_to_index_id_map.end());
1382}
1383
1384uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1385 uint32_t result = 0;
1386 std::map<uint64_t, uint32_t>::iterator iterator =
1387 m_thread_id_to_index_id_map.find(thread_id);
1388 if (iterator == m_thread_id_to_index_id_map.end()) {
1389 result = ++m_thread_index_id;
1390 m_thread_id_to_index_id_map[thread_id] = result;
1391 } else {
1392 result = iterator->second;
1393 }
1394
1395 return result;
1396}
1397
1398StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399 return m_public_state.GetValue();
1400}
1401
Kate Stoneb9c1b512016-09-06 20:57:50 +00001402void Process::SetPublicState(StateType new_state, bool restarted) {
1403 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1404 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001405 LLDB_LOGF(log, "Process::SetPublicState (state = %s, restarted = %i)",
1406 StateAsCString(new_state), restarted);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001407 const StateType old_state = m_public_state.GetValue();
1408 m_public_state.SetValue(new_state);
1409
Adrian Prantl05097242018-04-30 16:49:04 +00001410 // On the transition from Run to Stopped, we unlock the writer end of the run
1411 // lock. The lock gets locked in Resume, which is the public API to tell the
1412 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001413 if (!StateChangedIsExternallyHijacked()) {
1414 if (new_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001415 LLDB_LOGF(log,
1416 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1417 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001418 m_public_run_lock.SetStopped();
1419 } else {
1420 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1421 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1422 if ((old_state_is_stopped != new_state_is_stopped)) {
1423 if (new_state_is_stopped && !restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001424 LLDB_LOGF(log, "Process::SetPublicState (%s) -- unlocking run lock",
1425 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426 m_public_run_lock.SetStopped();
1427 }
1428 }
1429 }
1430 }
1431}
1432
Zachary Turner97206d52017-05-12 04:51:55 +00001433Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1435 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001436 LLDB_LOGF(log, "Process::Resume -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001438 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001439 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001440 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001442 Status error = PrivateResume();
1443 if (!error.Success()) {
1444 // Undo running state change
1445 m_public_run_lock.SetStopped();
1446 }
1447 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001448}
1449
Jim Ingham3139fc92019-03-01 18:13:38 +00001450static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1451
Zachary Turner97206d52017-05-12 04:51:55 +00001452Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1454 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001455 LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001456 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001457 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001458 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001459 return error;
1460 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001461
Kate Stoneb9c1b512016-09-06 20:57:50 +00001462 ListenerSP listener_sp(
Jim Ingham3139fc92019-03-01 18:13:38 +00001463 Listener::MakeListener(g_resume_sync_name));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001465
Zachary Turner97206d52017-05-12 04:51:55 +00001466 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001467 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001468 StateType state =
Konrad Kleine248a1302019-05-23 11:14:47 +00001469 WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001470 const bool must_be_alive =
1471 false; // eStateExited is ok, so this must be false
1472 if (!StateIsStoppedState(state, must_be_alive))
1473 error.SetErrorStringWithFormat(
1474 "process not in stopped state after synchronous resume: %s",
1475 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001476 } else {
1477 // Undo running state change
1478 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001479 }
Ed Mastec29693f2013-07-02 16:35:47 +00001480
Kate Stoneb9c1b512016-09-06 20:57:50 +00001481 // Undo the hijacking of process events...
1482 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001483
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484 return error;
1485}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001486
Jim Ingham3139fc92019-03-01 18:13:38 +00001487bool Process::StateChangedIsExternallyHijacked() {
1488 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1489 const char *hijacking_name = GetHijackingListenerName();
1490 if (hijacking_name &&
1491 strcmp(hijacking_name, g_resume_sync_name))
1492 return true;
1493 }
1494 return false;
1495}
1496
1497bool Process::StateChangedIsHijackedForSynchronousResume() {
1498 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1499 const char *hijacking_name = GetHijackingListenerName();
1500 if (hijacking_name &&
1501 strcmp(hijacking_name, g_resume_sync_name) == 0)
1502 return true;
1503 }
1504 return false;
1505}
1506
Kate Stoneb9c1b512016-09-06 20:57:50 +00001507StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001508
Kate Stoneb9c1b512016-09-06 20:57:50 +00001509void Process::SetPrivateState(StateType new_state) {
1510 if (m_finalize_called)
1511 return;
1512
1513 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1514 LIBLLDB_LOG_PROCESS));
1515 bool state_changed = false;
1516
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001517 LLDB_LOGF(log, "Process::SetPrivateState (%s)", StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001518
1519 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1520 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1521
1522 const StateType old_state = m_private_state.GetValueNoLock();
1523 state_changed = old_state != new_state;
1524
1525 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1526 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1527 if (old_state_is_stopped != new_state_is_stopped) {
1528 if (new_state_is_stopped)
1529 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001530 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001531 m_private_run_lock.SetRunning();
1532 }
1533
1534 if (state_changed) {
1535 m_private_state.SetValueNoLock(new_state);
1536 EventSP event_sp(
1537 new Event(eBroadcastBitStateChanged,
1538 new ProcessEventData(shared_from_this(), new_state)));
1539 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001540 // Note, this currently assumes that all threads in the list stop when
1541 // the process stops. In the future we will want to support a debugging
1542 // model where some threads continue to run while others are stopped.
1543 // When that happens we will either need a way for the thread list to
1544 // identify which threads are stopping or create a special thread list
1545 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546 //
Adrian Prantl05097242018-04-30 16:49:04 +00001547 // The process plugin is responsible for managing the actual behavior of
1548 // the threads and should have stopped any threads that are going to stop
1549 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001550 m_thread_list.DidStop();
1551
1552 m_mod_id.BumpStopID();
1553 if (!m_mod_id.IsLastResumeForUserExpression())
1554 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1555 m_memory_cache.Clear();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001556 LLDB_LOGF(log, "Process::SetPrivateState (%s) stop_id = %u",
1557 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001558 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001559
Kate Stoneb9c1b512016-09-06 20:57:50 +00001560 // Use our target to get a shared pointer to ourselves...
1561 if (m_finalize_called && !PrivateStateThreadIsValid())
1562 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001563 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001564 m_private_state_broadcaster.BroadcastEvent(event_sp);
1565 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001566 LLDB_LOGF(log,
1567 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1568 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001569 }
Jim Ingham22777012010-09-23 02:01:19 +00001570}
1571
Kate Stoneb9c1b512016-09-06 20:57:50 +00001572void Process::SetRunningUserExpression(bool on) {
1573 m_mod_id.SetRunningUserExpression(on);
1574}
1575
Raphael Isemannc01783a2018-08-29 22:50:54 +00001576void Process::SetRunningUtilityFunction(bool on) {
1577 m_mod_id.SetRunningUtilityFunction(on);
1578}
1579
Kate Stoneb9c1b512016-09-06 20:57:50 +00001580addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1581
1582const lldb::ABISP &Process::GetABI() {
1583 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001584 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001585 return m_abi_sp;
1586}
1587
Davide Italianocec82632019-12-03 16:54:04 -08001588std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
Alex Langford03e1a822019-05-29 18:08:22 +00001589 std::vector<LanguageRuntime *> language_runtimes;
1590
1591 if (m_finalizing)
1592 return language_runtimes;
1593
1594 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1595 // Before we pass off a copy of the language runtimes, we must make sure that
1596 // our collection is properly populated. It's possible that some of the
1597 // language runtimes were not loaded yet, either because nobody requested it
1598 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1599 // hadn't been loaded).
1600 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
Davide Italianocec82632019-12-03 16:54:04 -08001601 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
Alex Langford03e1a822019-05-29 18:08:22 +00001602 language_runtimes.emplace_back(runtime);
1603 }
1604
1605 return language_runtimes;
1606}
1607
Davide Italianocec82632019-12-03 16:54:04 -08001608LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001609 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001610 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611
Alex Langford7d3e97f2019-05-29 21:07:53 +00001612 LanguageRuntime *runtime = nullptr;
1613
Alex Langford74eb76f2019-05-22 23:01:18 +00001614 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001615 LanguageRuntimeCollection::iterator pos;
1616 pos = m_language_runtimes.find(language);
Davide Italianocec82632019-12-03 16:54:04 -08001617 if (pos == m_language_runtimes.end() || !pos->second) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001618 lldb::LanguageRuntimeSP runtime_sp(
1619 LanguageRuntime::FindPlugin(this, language));
1620
1621 m_language_runtimes[language] = runtime_sp;
Alex Langford7d3e97f2019-05-29 21:07:53 +00001622 runtime = runtime_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001623 } else
Alex Langford7d3e97f2019-05-29 21:07:53 +00001624 runtime = pos->second.get();
1625
1626 if (runtime)
1627 // It's possible that a language runtime can support multiple LanguageTypes,
1628 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1629 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1630 // primary language type and make sure that our runtime supports it.
1631 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1632
1633 return runtime;
Jim Ingham22777012010-09-23 02:01:19 +00001634}
1635
Kate Stoneb9c1b512016-09-06 20:57:50 +00001636bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1637 if (m_finalizing)
1638 return false;
1639
1640 if (in_value.IsDynamic())
1641 return false;
1642 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1643
1644 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1645 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1646 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1647 }
1648
Alex Langford41dc5522019-05-30 21:03:53 +00001649 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1650 if (runtime->CouldHaveDynamicValue(in_value))
1651 return true;
1652 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001653
Alex Langford41dc5522019-05-30 21:03:53 +00001654 return false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001655}
1656
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001658 m_dynamic_checkers_up.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001659}
1660
Kate Stoneb9c1b512016-09-06 20:57:50 +00001661BreakpointSiteList &Process::GetBreakpointSiteList() {
1662 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001663}
1664
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1666 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001667}
1668
Kate Stoneb9c1b512016-09-06 20:57:50 +00001669void Process::DisableAllBreakpointSites() {
1670 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1671 // bp_site->SetEnabled(true);
1672 DisableBreakpointSite(bp_site);
1673 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001674}
1675
Zachary Turner97206d52017-05-12 04:51:55 +00001676Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1677 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001678
Kate Stoneb9c1b512016-09-06 20:57:50 +00001679 if (error.Success())
1680 m_breakpoint_site_list.Remove(break_id);
1681
1682 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001683}
1684
Zachary Turner97206d52017-05-12 04:51:55 +00001685Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1686 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001687 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1688 if (bp_site_sp) {
1689 if (bp_site_sp->IsEnabled())
1690 error = DisableBreakpointSite(bp_site_sp.get());
1691 } else {
1692 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1693 break_id);
1694 }
1695
1696 return error;
1697}
1698
Zachary Turner97206d52017-05-12 04:51:55 +00001699Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1700 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001701 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1702 if (bp_site_sp) {
1703 if (!bp_site_sp->IsEnabled())
1704 error = EnableBreakpointSite(bp_site_sp.get());
1705 } else {
1706 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1707 break_id);
1708 }
1709 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001710}
1711
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001712lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001713Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1714 bool use_hardware) {
1715 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001716
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717 bool show_error = true;
1718 switch (GetState()) {
1719 case eStateInvalid:
1720 case eStateUnloaded:
1721 case eStateConnected:
1722 case eStateAttaching:
1723 case eStateLaunching:
1724 case eStateDetached:
1725 case eStateExited:
1726 show_error = false;
1727 break;
1728
1729 case eStateStopped:
1730 case eStateRunning:
1731 case eStateStepping:
1732 case eStateCrashed:
1733 case eStateSuspended:
1734 show_error = IsAlive();
1735 break;
1736 }
1737
Adrian Prantl05097242018-04-30 16:49:04 +00001738 // Reset the IsIndirect flag here, in case the location changes from pointing
1739 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001740 owner->SetIsIndirect(false);
1741
1742 if (owner->ShouldResolveIndirectFunctions()) {
1743 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1744 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001745 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001746 Address symbol_address = symbol->GetAddress();
1747 load_addr = ResolveIndirectFunction(&symbol_address, error);
1748 if (!error.Success() && show_error) {
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001749 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001750 "warning: failed to resolve indirect function at 0x%" PRIx64
1751 " for breakpoint %i.%i: %s\n",
1752 symbol->GetLoadAddress(&GetTarget()),
1753 owner->GetBreakpoint().GetID(), owner->GetID(),
1754 error.AsCString() ? error.AsCString() : "unknown error");
1755 return LLDB_INVALID_BREAK_ID;
1756 }
1757 Address resolved_address(load_addr);
1758 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1759 owner->SetIsIndirect(true);
1760 } else
1761 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1762 } else
1763 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1764
1765 if (load_addr != LLDB_INVALID_ADDRESS) {
1766 BreakpointSiteSP bp_site_sp;
1767
1768 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001769 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001770
1771 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1772
1773 if (bp_site_sp) {
1774 bp_site_sp->AddOwner(owner);
1775 owner->SetBreakpointSite(bp_site_sp);
1776 return bp_site_sp->GetID();
1777 } else {
1778 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1779 load_addr, use_hardware));
1780 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001781 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001782 if (error.Success()) {
1783 owner->SetBreakpointSite(bp_site_sp);
1784 return m_breakpoint_site_list.Add(bp_site_sp);
1785 } else {
Jonas Devliegheree103ae92018-11-15 01:18:15 +00001786 if (show_error || use_hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001787 // Report error for setting breakpoint...
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001788 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001789 "warning: failed to set breakpoint site at 0x%" PRIx64
1790 " for breakpoint %i.%i: %s\n",
1791 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1792 error.AsCString() ? error.AsCString() : "unknown error");
1793 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001794 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001796 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001797 }
1798 // We failed to enable the breakpoint
1799 return LLDB_INVALID_BREAK_ID;
1800}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001801
Kate Stoneb9c1b512016-09-06 20:57:50 +00001802void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1803 lldb::user_id_t owner_loc_id,
1804 BreakpointSiteSP &bp_site_sp) {
1805 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1806 if (num_owners == 0) {
1807 // Don't try to disable the site if we don't have a live process anymore.
1808 if (IsAlive())
1809 DisableBreakpointSite(bp_site_sp.get());
1810 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1811 }
1812}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001813
Kate Stoneb9c1b512016-09-06 20:57:50 +00001814size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1815 uint8_t *buf) const {
1816 size_t bytes_removed = 0;
1817 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001818
Kate Stoneb9c1b512016-09-06 20:57:50 +00001819 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1820 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001821 bp_sites_in_range.ForEach([bp_addr, size,
1822 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001823 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1824 addr_t intersect_addr;
1825 size_t intersect_size;
1826 size_t opcode_offset;
1827 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1828 &intersect_size, &opcode_offset)) {
1829 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1830 assert(bp_addr < intersect_addr + intersect_size &&
1831 intersect_addr + intersect_size <= bp_addr + size);
1832 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1833 size_t buf_offset = intersect_addr - bp_addr;
1834 ::memcpy(buf + buf_offset,
1835 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1836 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001838 }
1839 });
1840 }
1841 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001842}
1843
Kate Stoneb9c1b512016-09-06 20:57:50 +00001844size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1845 PlatformSP platform_sp(GetTarget().GetPlatform());
1846 if (platform_sp)
1847 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1848 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001849}
1850
Zachary Turner97206d52017-05-12 04:51:55 +00001851Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1852 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001853 assert(bp_site != nullptr);
1854 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1855 const addr_t bp_addr = bp_site->GetLoadAddress();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001856 LLDB_LOGF(
1857 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1858 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001859 if (bp_site->IsEnabled()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001860 LLDB_LOGF(
1861 log,
1862 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1863 " -- already enabled",
1864 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001865 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001866 }
1867
1868 if (bp_addr == LLDB_INVALID_ADDRESS) {
1869 error.SetErrorString("BreakpointSite contains an invalid load address.");
1870 return error;
1871 }
1872 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1873 // trap for the breakpoint site
1874 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1875
1876 if (bp_opcode_size == 0) {
1877 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1878 "returned zero, unable to get breakpoint "
1879 "trap for address 0x%" PRIx64,
1880 bp_addr);
1881 } else {
1882 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1883
1884 if (bp_opcode_bytes == nullptr) {
1885 error.SetErrorString(
1886 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1887 return error;
1888 }
1889
1890 // Save the original opcode by reading it
1891 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1892 error) == bp_opcode_size) {
1893 // Write a software breakpoint in place of the original opcode
1894 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1895 bp_opcode_size) {
1896 uint8_t verify_bp_opcode_bytes[64];
1897 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1898 error) == bp_opcode_size) {
1899 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1900 bp_opcode_size) == 0) {
1901 bp_site->SetEnabled(true);
1902 bp_site->SetType(BreakpointSite::eSoftware);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001903 LLDB_LOGF(log,
1904 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1905 "addr = 0x%" PRIx64 " -- SUCCESS",
1906 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001907 } else
1908 error.SetErrorString(
1909 "failed to verify the breakpoint trap in memory.");
1910 } else
1911 error.SetErrorString(
1912 "Unable to read memory to verify breakpoint trap.");
1913 } else
1914 error.SetErrorString("Unable to write breakpoint trap to memory.");
1915 } else
1916 error.SetErrorString("Unable to read memory at breakpoint address.");
1917 }
1918 if (log && error.Fail())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001919 LLDB_LOGF(
1920 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001921 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1922 " -- FAILED: %s",
1923 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1924 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001925}
1926
Zachary Turner97206d52017-05-12 04:51:55 +00001927Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1928 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001929 assert(bp_site != nullptr);
1930 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1931 addr_t bp_addr = bp_site->GetLoadAddress();
1932 lldb::user_id_t breakID = bp_site->GetID();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001933 LLDB_LOGF(log,
1934 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1935 ") addr = 0x%" PRIx64,
1936 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001937
Kate Stoneb9c1b512016-09-06 20:57:50 +00001938 if (bp_site->IsHardware()) {
1939 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1940 } else if (bp_site->IsEnabled()) {
1941 const size_t break_op_size = bp_site->GetByteSize();
1942 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1943 if (break_op_size > 0) {
1944 // Clear a software breakpoint instruction
1945 uint8_t curr_break_op[8];
1946 assert(break_op_size <= sizeof(curr_break_op));
1947 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001948
Kate Stoneb9c1b512016-09-06 20:57:50 +00001949 // Read the breakpoint opcode
1950 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1951 break_op_size) {
1952 bool verify = false;
1953 // Make sure the breakpoint opcode exists at this address
1954 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1955 break_op_found = true;
1956 // We found a valid breakpoint opcode at this address, now restore
1957 // the saved opcode.
1958 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1959 break_op_size, error) == break_op_size) {
1960 verify = true;
1961 } else
1962 error.SetErrorString(
1963 "Memory write failed when restoring original opcode.");
1964 } else {
1965 error.SetErrorString(
1966 "Original breakpoint trap is no longer in memory.");
1967 // Set verify to true and so we can check if the original opcode has
1968 // already been restored
1969 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001970 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001971
Kate Stoneb9c1b512016-09-06 20:57:50 +00001972 if (verify) {
1973 uint8_t verify_opcode[8];
1974 assert(break_op_size < sizeof(verify_opcode));
1975 // Verify that our original opcode made it back to the inferior
1976 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1977 break_op_size) {
1978 // compare the memory we just read with the original opcode
1979 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1980 break_op_size) == 0) {
1981 // SUCCESS
1982 bp_site->SetEnabled(false);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001983 LLDB_LOGF(log,
1984 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1985 "addr = 0x%" PRIx64 " -- SUCCESS",
1986 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001987 return error;
1988 } else {
1989 if (break_op_found)
1990 error.SetErrorString("Failed to restore original opcode.");
1991 }
1992 } else
1993 error.SetErrorString("Failed to read memory to verify that "
1994 "breakpoint trap was restored.");
1995 }
1996 } else
1997 error.SetErrorString(
1998 "Unable to read memory that should contain the breakpoint trap.");
1999 }
2000 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002001 LLDB_LOGF(
2002 log,
2003 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2004 " -- already disabled",
2005 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002006 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002007 }
2008
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002009 LLDB_LOGF(
2010 log,
2011 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2012 " -- FAILED: %s",
2013 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002014 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002015}
2016
Adrian Prantl05097242018-04-30 16:49:04 +00002017// Uncomment to verify memory caching works after making changes to caching
2018// code
Greg Clayton58be07b2011-01-07 06:08:19 +00002019//#define VERIFY_MEMORY_READS
2020
Zachary Turner97206d52017-05-12 04:51:55 +00002021size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002022 error.Clear();
2023 if (!GetDisableMemoryCache()) {
2024#if defined(VERIFY_MEMORY_READS)
2025 // Memory caching is enabled, with debug verification
2026
2027 if (buf && size) {
2028 // Uncomment the line below to make sure memory caching is working.
2029 // I ran this through the test suite and got no assertions, so I am
2030 // pretty confident this is working well. If any changes are made to
2031 // memory caching, uncomment the line below and test your changes!
2032
2033 // Verify all memory reads by using the cache first, then redundantly
2034 // reading the same memory from the inferior and comparing to make sure
2035 // everything is exactly the same.
2036 std::string verify_buf(size, '\0');
2037 assert(verify_buf.size() == size);
2038 const size_t cache_bytes_read =
2039 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00002040 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002041 const size_t verify_bytes_read =
2042 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2043 verify_buf.size(), verify_error);
2044 assert(cache_bytes_read == verify_bytes_read);
2045 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2046 assert(verify_error.Success() == error.Success());
2047 return cache_bytes_read;
2048 }
2049 return 0;
2050#else // !defined(VERIFY_MEMORY_READS)
2051 // Memory caching is enabled, without debug verification
2052
2053 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002054#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002055 } else {
2056 // Memory caching is disabled
2057
2058 return ReadMemoryFromInferior(addr, buf, size, error);
2059 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002060}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002061
2062size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00002063 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002064 char buf[256];
2065 out_str.clear();
2066 addr_t curr_addr = addr;
2067 while (true) {
2068 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2069 if (length == 0)
2070 break;
2071 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00002072 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2073 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00002074 if (length == sizeof(buf) - 1)
2075 curr_addr += length;
2076 else
2077 break;
2078 }
2079 return out_str.size();
2080}
2081
2082size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00002083 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002084 size_t total_bytes_read = 0;
2085 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00002086 // Ensure a null terminator independent of the number of bytes that is
2087 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002088 memset(dst, 0, max_bytes);
2089 size_t bytes_left = max_bytes - type_width;
2090
2091 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2092 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2093 "string with more than 4 bytes "
2094 "per character!");
2095
Greg Clayton4c82d422012-05-18 23:20:01 +00002096 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002097 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2098 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002099
Kate Stoneb9c1b512016-09-06 20:57:50 +00002100 error.Clear();
2101 while (bytes_left > 0 && error.Success()) {
2102 addr_t cache_line_bytes_left =
2103 cache_line_size - (curr_addr % cache_line_size);
2104 addr_t bytes_to_read =
2105 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2106 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002107
Kate Stoneb9c1b512016-09-06 20:57:50 +00002108 if (bytes_read == 0)
2109 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002110
Kate Stoneb9c1b512016-09-06 20:57:50 +00002111 // Search for a null terminator of correct size and alignment in
2112 // bytes_read
2113 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2114 for (size_t i = aligned_start;
2115 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2116 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2117 error.Clear();
2118 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002119 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002120
2121 total_bytes_read += bytes_read;
2122 curr_dst += bytes_read;
2123 curr_addr += bytes_read;
2124 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002125 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002126 } else {
2127 if (max_bytes)
2128 error.SetErrorString("invalid arguments");
2129 }
2130 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002131}
2132
Kate Stoneb9c1b512016-09-06 20:57:50 +00002133// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002134// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002135size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002136 size_t dst_max_len,
2137 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002138 size_t total_cstr_len = 0;
2139 if (dst && dst_max_len) {
2140 result_error.Clear();
2141 // NULL out everything just to be safe
2142 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002143 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002144 addr_t curr_addr = addr;
2145 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2146 size_t bytes_left = dst_max_len - 1;
2147 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002148
Kate Stoneb9c1b512016-09-06 20:57:50 +00002149 while (bytes_left > 0) {
2150 addr_t cache_line_bytes_left =
2151 cache_line_size - (curr_addr % cache_line_size);
2152 addr_t bytes_to_read =
2153 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2154 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002155
Kate Stoneb9c1b512016-09-06 20:57:50 +00002156 if (bytes_read == 0) {
2157 result_error = error;
2158 dst[total_cstr_len] = '\0';
2159 break;
2160 }
2161 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002162
Kate Stoneb9c1b512016-09-06 20:57:50 +00002163 total_cstr_len += len;
2164
2165 if (len < bytes_to_read)
2166 break;
2167
2168 curr_dst += bytes_read;
2169 curr_addr += bytes_read;
2170 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002171 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002172 } else {
2173 if (dst == nullptr)
2174 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002175 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002176 result_error.Clear();
2177 }
2178 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002179}
2180
Kate Stoneb9c1b512016-09-06 20:57:50 +00002181size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002182 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183 if (buf == nullptr || size == 0)
2184 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002185
Kate Stoneb9c1b512016-09-06 20:57:50 +00002186 size_t bytes_read = 0;
2187 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002188
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189 while (bytes_read < size) {
2190 const size_t curr_size = size - bytes_read;
2191 const size_t curr_bytes_read =
2192 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2193 bytes_read += curr_bytes_read;
2194 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2195 break;
2196 }
2197
2198 // Replace any software breakpoint opcodes that fall into this range back
2199 // into "buf" before we return
2200 if (bytes_read > 0)
2201 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2202 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002203}
2204
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2206 size_t integer_byte_size,
2207 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002208 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002209 Scalar scalar;
2210 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2211 error))
2212 return scalar.ULongLong(fail_value);
2213 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002214}
2215
Kate Stoneb9c1b512016-09-06 20:57:50 +00002216int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2217 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002218 int64_t fail_value,
2219 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220 Scalar scalar;
2221 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2222 error))
2223 return scalar.SLongLong(fail_value);
2224 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002225}
2226
Zachary Turner97206d52017-05-12 04:51:55 +00002227addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002228 Scalar scalar;
2229 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2230 error))
2231 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2232 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002233}
2234
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002236 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002237 Scalar scalar;
2238 const uint32_t addr_byte_size = GetAddressByteSize();
2239 if (addr_byte_size <= 4)
2240 scalar = (uint32_t)ptr_value;
2241 else
2242 scalar = ptr_value;
2243 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2244 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002245}
2246
Kate Stoneb9c1b512016-09-06 20:57:50 +00002247size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002248 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002249 size_t bytes_written = 0;
2250 const uint8_t *bytes = (const uint8_t *)buf;
2251
2252 while (bytes_written < size) {
2253 const size_t curr_size = size - bytes_written;
2254 const size_t curr_bytes_written = DoWriteMemory(
2255 addr + bytes_written, bytes + bytes_written, curr_size, error);
2256 bytes_written += curr_bytes_written;
2257 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2258 break;
2259 }
2260 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002261}
2262
Kate Stoneb9c1b512016-09-06 20:57:50 +00002263size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002264 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265#if defined(ENABLE_MEMORY_CACHING)
2266 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002267#endif
2268
Kate Stoneb9c1b512016-09-06 20:57:50 +00002269 if (buf == nullptr || size == 0)
2270 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002271
Kate Stoneb9c1b512016-09-06 20:57:50 +00002272 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002273
Kate Stoneb9c1b512016-09-06 20:57:50 +00002274 // We need to write any data that would go where any current software traps
2275 // (enabled software breakpoints) any software traps (breakpoints) that we
2276 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002277
Kate Stoneb9c1b512016-09-06 20:57:50 +00002278 BreakpointSiteList bp_sites_in_range;
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002279 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002280 return WriteMemoryPrivate(addr, buf, size, error);
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002281
2282 // No breakpoint sites overlap
2283 if (bp_sites_in_range.IsEmpty())
2284 return WriteMemoryPrivate(addr, buf, size, error);
2285
2286 const uint8_t *ubuf = (const uint8_t *)buf;
2287 uint64_t bytes_written = 0;
2288
2289 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2290 &error](BreakpointSite *bp) -> void {
2291 if (error.Fail())
2292 return;
2293
2294 addr_t intersect_addr;
2295 size_t intersect_size;
2296 size_t opcode_offset;
2297 const bool intersects = bp->IntersectsRange(
2298 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2299 UNUSED_IF_ASSERT_DISABLED(intersects);
2300 assert(intersects);
2301 assert(addr <= intersect_addr && intersect_addr < addr + size);
2302 assert(addr < intersect_addr + intersect_size &&
2303 intersect_addr + intersect_size <= addr + size);
2304 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2305
2306 // Check for bytes before this breakpoint
2307 const addr_t curr_addr = addr + bytes_written;
2308 if (intersect_addr > curr_addr) {
2309 // There are some bytes before this breakpoint that we need to just
2310 // write to memory
2311 size_t curr_size = intersect_addr - curr_addr;
2312 size_t curr_bytes_written =
2313 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2314 bytes_written += curr_bytes_written;
2315 if (curr_bytes_written != curr_size) {
2316 // We weren't able to write all of the requested bytes, we are
2317 // done looping and will return the number of bytes that we have
2318 // written so far.
2319 if (error.Success())
2320 error.SetErrorToGenericError();
2321 }
2322 }
2323 // Now write any bytes that would cover up any software breakpoints
2324 // directly into the breakpoint opcode buffer
2325 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2326 intersect_size);
2327 bytes_written += intersect_size;
2328 });
Kate Stoneb9c1b512016-09-06 20:57:50 +00002329
2330 // Write any remaining bytes after the last breakpoint if we have any left
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002331 if (bytes_written < size)
2332 bytes_written +=
2333 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2334 size - bytes_written, error);
2335
2336 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002338
Kate Stoneb9c1b512016-09-06 20:57:50 +00002339size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002340 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341 if (byte_size == UINT32_MAX)
2342 byte_size = scalar.GetByteSize();
2343 if (byte_size > 0) {
2344 uint8_t buf[32];
2345 const size_t mem_size =
2346 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2347 if (mem_size > 0)
2348 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002349 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002350 error.SetErrorString("failed to get scalar as memory data");
2351 } else {
2352 error.SetErrorString("invalid scalar value");
2353 }
2354 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002355}
2356
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2358 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002359 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002360 uint64_t uval = 0;
2361 if (byte_size == 0) {
2362 error.SetErrorString("byte size is zero");
2363 } else if (byte_size & (byte_size - 1)) {
2364 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2365 byte_size);
2366 } else if (byte_size <= sizeof(uval)) {
2367 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2368 if (bytes_read == byte_size) {
2369 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2370 GetAddressByteSize());
2371 lldb::offset_t offset = 0;
2372 if (byte_size <= 4)
2373 scalar = data.GetMaxU32(&offset, byte_size);
2374 else
2375 scalar = data.GetMaxU64(&offset, byte_size);
2376 if (is_signed)
2377 scalar.SignExtend(byte_size * 8);
2378 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002379 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002380 } else {
2381 error.SetErrorStringWithFormat(
2382 "byte size of %u is too large for integer scalar type", byte_size);
2383 }
2384 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002385}
2386
Pavel Labath16064d32018-03-20 11:56:24 +00002387Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2388 Status error;
2389 for (const auto &Entry : entries) {
2390 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2391 error);
2392 if (!error.Success())
2393 break;
2394 }
2395 return error;
2396}
2397
Greg Claytond495c532011-05-17 03:37:42 +00002398#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002399addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002400 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002401 if (GetPrivateState() != eStateStopped) {
2402 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002404 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002405
2406#if defined(USE_ALLOCATE_MEMORY_CACHE)
2407 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002408#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002409 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2410 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002411 LLDB_LOGF(log,
2412 "Process::AllocateMemory(size=%" PRIu64
2413 ", permissions=%s) => 0x%16.16" PRIx64
2414 " (m_stop_id = %u m_memory_id = %u)",
2415 (uint64_t)size, GetPermissionsAsCString(permissions),
2416 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2417 m_mod_id.GetMemoryID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002419#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002420}
2421
Kate Stoneb9c1b512016-09-06 20:57:50 +00002422addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002423 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002424 addr_t return_addr = AllocateMemory(size, permissions, error);
2425 if (error.Success()) {
2426 std::string buffer(size, 0);
2427 WriteMemory(return_addr, buffer.c_str(), size, error);
2428 }
2429 return return_addr;
2430}
2431
2432bool Process::CanJIT() {
2433 if (m_can_jit == eCanJITDontKnow) {
2434 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002435 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002436
2437 uint64_t allocated_memory = AllocateMemory(
2438 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2439 err);
2440
2441 if (err.Success()) {
2442 m_can_jit = eCanJITYes;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002443 LLDB_LOGF(log,
2444 "Process::%s pid %" PRIu64
2445 " allocation test passed, CanJIT () is true",
2446 __FUNCTION__, GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447 } else {
2448 m_can_jit = eCanJITNo;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002449 LLDB_LOGF(log,
2450 "Process::%s pid %" PRIu64
2451 " allocation test failed, CanJIT () is false: %s",
2452 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002453 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002454
2455 DeallocateMemory(allocated_memory);
2456 }
2457
2458 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002459}
2460
Kate Stoneb9c1b512016-09-06 20:57:50 +00002461void Process::SetCanJIT(bool can_jit) {
2462 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002463}
2464
Kate Stoneb9c1b512016-09-06 20:57:50 +00002465void Process::SetCanRunCode(bool can_run_code) {
2466 SetCanJIT(can_run_code);
2467 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002468}
2469
Zachary Turner97206d52017-05-12 04:51:55 +00002470Status Process::DeallocateMemory(addr_t ptr) {
2471 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002472#if defined(USE_ALLOCATE_MEMORY_CACHE)
2473 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2474 error.SetErrorStringWithFormat(
2475 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2476 }
Greg Claytond495c532011-05-17 03:37:42 +00002477#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002478 error = DoDeallocateMemory(ptr);
2479
2480 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002481 LLDB_LOGF(log,
2482 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2483 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2484 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2485 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002486#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002487 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002488}
2489
Kate Stoneb9c1b512016-09-06 20:57:50 +00002490ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2491 lldb::addr_t header_addr,
2492 size_t size_to_read) {
2493 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2494 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002495 LLDB_LOGF(log,
2496 "Process::ReadModuleFromMemory reading %s binary from memory",
2497 file_spec.GetPath().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498 }
2499 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2500 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002501 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002502 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2503 shared_from_this(), header_addr, error, size_to_read);
2504 if (objfile)
2505 return module_sp;
2506 }
2507 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002508}
2509
Kate Stoneb9c1b512016-09-06 20:57:50 +00002510bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2511 uint32_t &permissions) {
2512 MemoryRegionInfo range_info;
2513 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002514 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002515 if (!error.Success())
2516 return false;
2517 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2518 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2519 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2520 return false;
2521 }
2522
2523 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2524 permissions |= lldb::ePermissionsReadable;
2525
2526 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2527 permissions |= lldb::ePermissionsWritable;
2528
2529 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2530 permissions |= lldb::ePermissionsExecutable;
2531
2532 return true;
2533}
2534
Zachary Turner97206d52017-05-12 04:51:55 +00002535Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2536 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002537 error.SetErrorString("watchpoints are not supported");
2538 return error;
2539}
2540
Zachary Turner97206d52017-05-12 04:51:55 +00002541Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2542 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002543 error.SetErrorString("watchpoints are not supported");
2544 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002545}
2546
2547StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002548Process::WaitForProcessStopPrivate(EventSP &event_sp,
2549 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002550 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002551
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552 while (true) {
2553 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002554 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002555
Kate Stoneb9c1b512016-09-06 20:57:50 +00002556 if (StateIsStoppedState(state, false))
2557 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002558
Kate Stoneb9c1b512016-09-06 20:57:50 +00002559 // If state is invalid, then we timed out
2560 if (state == eStateInvalid)
2561 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002562
Kate Stoneb9c1b512016-09-06 20:57:50 +00002563 if (event_sp)
2564 HandlePrivateEvent(event_sp);
2565 }
2566 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002567}
2568
Kate Stoneb9c1b512016-09-06 20:57:50 +00002569void Process::LoadOperatingSystemPlugin(bool flush) {
2570 if (flush)
2571 m_thread_list.Clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002572 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002573 if (flush)
2574 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002575}
2576
Zachary Turner97206d52017-05-12 04:51:55 +00002577Status Process::Launch(ProcessLaunchInfo &launch_info) {
2578 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002579 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002580 m_dyld_up.reset();
2581 m_jit_loaders_up.reset();
2582 m_system_runtime_up.reset();
2583 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002584 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002585
Kate Stoneb9c1b512016-09-06 20:57:50 +00002586 Module *exe_module = GetTarget().GetExecutableModulePointer();
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002587 if (!exe_module) {
2588 error.SetErrorString("executable module does not exist");
2589 return error;
2590 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002591
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002592 char local_exec_file_path[PATH_MAX];
2593 char platform_exec_file_path[PATH_MAX];
2594 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2595 sizeof(local_exec_file_path));
2596 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2597 sizeof(platform_exec_file_path));
2598 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2599 // Install anything that might need to be installed prior to launching.
2600 // For host systems, this will do nothing, but if we are connected to a
2601 // remote platform it will install any needed binaries
2602 error = GetTarget().Install(&launch_info);
2603 if (error.Fail())
2604 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002605
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002606 if (PrivateStateThreadIsValid())
2607 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002608
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002609 error = WillLaunch(exe_module);
2610 if (error.Success()) {
2611 const bool restarted = false;
2612 SetPublicState(eStateLaunching, restarted);
2613 m_should_detach = false;
2614
2615 if (m_public_run_lock.TrySetRunning()) {
2616 // Now launch using these arguments.
2617 error = DoLaunch(exe_module, launch_info);
2618 } else {
2619 // This shouldn't happen
2620 error.SetErrorString("failed to acquire process run lock");
2621 }
2622
2623 if (error.Fail()) {
2624 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2625 SetID(LLDB_INVALID_PROCESS_ID);
2626 const char *error_string = error.AsCString();
2627 if (error_string == nullptr)
2628 error_string = "launch failed";
2629 SetExitStatus(-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002630 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002631 } else {
2632 EventSP event_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002633
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002634 // Now wait for the process to launch and return control to us, and then
2635 // call DidLaunch:
2636 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Stella Stamenova36d457c2018-06-01 19:14:53 +00002637
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002638 if (state == eStateInvalid || !event_sp) {
2639 // We were able to launch the process, but we failed to catch the
2640 // initial stop.
2641 error.SetErrorString("failed to catch stop after launch");
2642 SetExitStatus(0, "failed to catch stop after launch");
2643 Destroy(false);
2644 } else if (state == eStateStopped || state == eStateCrashed) {
2645 DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002646
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002647 DynamicLoader *dyld = GetDynamicLoader();
2648 if (dyld)
2649 dyld->DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002650
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002651 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002652
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002653 SystemRuntime *system_runtime = GetSystemRuntime();
2654 if (system_runtime)
2655 system_runtime->DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002656
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002657 if (!m_os_up)
2658 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002659
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002660 // We successfully launched the process and stopped, now it the
2661 // right time to set up signal filters before resuming.
2662 UpdateAutomaticSignalFiltering();
Greg Clayton35824e32015-02-20 20:59:47 +00002663
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002664 // Note, the stop event was consumed above, but not handled. This
2665 // was done to give DidLaunch a chance to run. The target is either
2666 // stopped or crashed. Directly set the state. This is done to
2667 // prevent a stop message with a bunch of spurious output on thread
2668 // status, as well as not pop a ProcessIOHandler.
2669 SetPublicState(state, false);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002670
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002671 if (PrivateStateThreadIsValid())
2672 ResumePrivateStateThread();
2673 else
2674 StartPrivateStateThread();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002675
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002676 // Target was stopped at entry as was intended. Need to notify the
2677 // listeners about it.
2678 if (state == eStateStopped &&
2679 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002680 HandlePrivateEvent(event_sp);
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002681 } else if (state == eStateExited) {
2682 // We exited while trying to launch somehow. Don't call DidLaunch
2683 // as that's not likely to work, and return an invalid pid.
2684 HandlePrivateEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002685 }
2686 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002687 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002688 } else {
2689 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2690 local_exec_file_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002691 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002692
Kate Stoneb9c1b512016-09-06 20:57:50 +00002693 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002694}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002695
Zachary Turner97206d52017-05-12 04:51:55 +00002696Status Process::LoadCore() {
2697 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002698 if (error.Success()) {
2699 ListenerSP listener_sp(
2700 Listener::MakeListener("lldb.process.load_core_listener"));
2701 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002702
Kate Stoneb9c1b512016-09-06 20:57:50 +00002703 if (PrivateStateThreadIsValid())
2704 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002705 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002707
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002709 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002710 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002711
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002712 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002713
Kate Stoneb9c1b512016-09-06 20:57:50 +00002714 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002715 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002716 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002717
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002718 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00002719 LoadOperatingSystemPlugin(false);
2720
Kate Stoneb9c1b512016-09-06 20:57:50 +00002721 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002722 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002724
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002725 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002726 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002727 StateType state =
Pavel Labath7ada1c52019-06-25 07:14:29 +00002728 WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002729
2730 if (!StateIsStoppedState(state, false)) {
2731 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002732 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2733 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 error.SetErrorString(
2735 "Did not get stopped event after loading the core file.");
2736 }
2737 RestoreProcessEvents();
2738 }
2739 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002740}
2741
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742DynamicLoader *Process::GetDynamicLoader() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002743 if (!m_dyld_up)
2744 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2745 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002746}
2747
Antonio Afonso943faef2019-06-11 20:16:13 +00002748DataExtractor Process::GetAuxvData() { return DataExtractor(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749
2750JITLoaderList &Process::GetJITLoaders() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002751 if (!m_jit_loaders_up) {
Jonas Devlieghere06412da2020-06-24 17:44:33 -07002752 m_jit_loaders_up = std::make_unique<JITLoaderList>();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002753 JITLoader::LoadPlugins(this, *m_jit_loaders_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002754 }
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002755 return *m_jit_loaders_up;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002756}
2757
2758SystemRuntime *Process::GetSystemRuntime() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002759 if (!m_system_runtime_up)
2760 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2761 return m_system_runtime_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762}
2763
2764Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2765 uint32_t exec_count)
2766 : NextEventAction(process), m_exec_count(exec_count) {
2767 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002768 LLDB_LOGF(
2769 log,
2770 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2771 __FUNCTION__, static_cast<void *>(process), exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002772}
2773
2774Process::NextEventAction::EventActionResult
2775Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2776 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2777
2778 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002779 LLDB_LOGF(log,
2780 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2781 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782
2783 switch (state) {
2784 case eStateAttaching:
2785 return eEventActionSuccess;
2786
2787 case eStateRunning:
2788 case eStateConnected:
2789 return eEventActionRetry;
2790
2791 case eStateStopped:
2792 case eStateCrashed:
2793 // During attach, prior to sending the eStateStopped event,
2794 // lldb_private::Process subclasses must set the new process ID.
2795 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002796 // We don't want these events to be reported, so go set the
2797 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002798 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2799
2800 if (m_exec_count > 0) {
2801 --m_exec_count;
2802
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002803 LLDB_LOGF(log,
2804 "Process::AttachCompletionHandler::%s state %s: reduced "
2805 "remaining exec count to %" PRIu32 ", requesting resume",
2806 __FUNCTION__, StateAsCString(state), m_exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807
2808 RequestResume();
2809 return eEventActionRetry;
2810 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002811 LLDB_LOGF(log,
2812 "Process::AttachCompletionHandler::%s state %s: no more "
2813 "execs expected to start, continuing with attach",
2814 __FUNCTION__, StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002815
2816 m_process->CompleteAttach();
2817 return eEventActionSuccess;
2818 }
2819 break;
2820
2821 default:
2822 case eStateExited:
2823 case eStateInvalid:
2824 break;
2825 }
2826
2827 m_exit_string.assign("No valid Process");
2828 return eEventActionExit;
2829}
2830
2831Process::NextEventAction::EventActionResult
2832Process::AttachCompletionHandler::HandleBeingInterrupted() {
2833 return eEventActionSuccess;
2834}
2835
2836const char *Process::AttachCompletionHandler::GetExitString() {
2837 return m_exit_string.c_str();
2838}
2839
2840ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2841 if (m_listener_sp)
2842 return m_listener_sp;
2843 else
2844 return debugger.GetListener();
2845}
2846
Zachary Turner97206d52017-05-12 04:51:55 +00002847Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002848 m_abi_sp.reset();
2849 m_process_input_reader.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002850 m_dyld_up.reset();
2851 m_jit_loaders_up.reset();
2852 m_system_runtime_up.reset();
2853 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002854
2855 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002856 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002857 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2858 char process_name[PATH_MAX];
2859
2860 if (attach_info.GetExecutableFile().GetPath(process_name,
2861 sizeof(process_name))) {
2862 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2863
2864 if (wait_for_launch) {
2865 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2866 if (error.Success()) {
2867 if (m_public_run_lock.TrySetRunning()) {
2868 m_should_detach = true;
2869 const bool restarted = false;
2870 SetPublicState(eStateAttaching, restarted);
2871 // Now attach using these arguments.
2872 error = DoAttachToProcessWithName(process_name, attach_info);
2873 } else {
2874 // This shouldn't happen
2875 error.SetErrorString("failed to acquire process run lock");
2876 }
2877
2878 if (error.Fail()) {
2879 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2880 SetID(LLDB_INVALID_PROCESS_ID);
2881 if (error.AsCString() == nullptr)
2882 error.SetErrorString("attach failed");
2883
2884 SetExitStatus(-1, error.AsCString());
2885 }
2886 } else {
2887 SetNextEventAction(new Process::AttachCompletionHandler(
2888 this, attach_info.GetResumeCount()));
2889 StartPrivateStateThread();
2890 }
2891 return error;
2892 }
2893 } else {
2894 ProcessInstanceInfoList process_infos;
2895 PlatformSP platform_sp(GetTarget().GetPlatform());
2896
2897 if (platform_sp) {
2898 ProcessInstanceInfoMatch match_info;
2899 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00002900 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 platform_sp->FindProcesses(match_info, process_infos);
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002902 const uint32_t num_matches = process_infos.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 if (num_matches == 1) {
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002904 attach_pid = process_infos[0].GetProcessID();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002905 // Fall through and attach using the above process ID
2906 } else {
2907 match_info.GetProcessInfo().GetExecutableFile().GetPath(
2908 process_name, sizeof(process_name));
2909 if (num_matches > 1) {
2910 StreamString s;
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002911 ProcessInstanceInfo::DumpTableHeader(s, true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002912 for (size_t i = 0; i < num_matches; i++) {
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002913 process_infos[i].DumpAsTableRow(
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002914 s, platform_sp->GetUserIDResolver(), true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002915 }
2916 error.SetErrorStringWithFormat(
2917 "more than one process named %s:\n%s", process_name,
2918 s.GetData());
2919 } else
2920 error.SetErrorStringWithFormat(
2921 "could not find a process named %s", process_name);
2922 }
2923 } else {
2924 error.SetErrorString(
2925 "invalid platform, can't find processes by name");
2926 return error;
2927 }
2928 }
2929 } else {
2930 error.SetErrorString("invalid process name");
2931 }
2932 }
2933
2934 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2935 error = WillAttachToProcessWithID(attach_pid);
2936 if (error.Success()) {
2937
2938 if (m_public_run_lock.TrySetRunning()) {
2939 // Now attach using these arguments.
2940 m_should_detach = true;
2941 const bool restarted = false;
2942 SetPublicState(eStateAttaching, restarted);
2943 error = DoAttachToProcessWithID(attach_pid, attach_info);
2944 } else {
2945 // This shouldn't happen
2946 error.SetErrorString("failed to acquire process run lock");
2947 }
2948
2949 if (error.Success()) {
2950 SetNextEventAction(new Process::AttachCompletionHandler(
2951 this, attach_info.GetResumeCount()));
2952 StartPrivateStateThread();
2953 } else {
Greg Clayton71337622011-02-24 22:24:29 +00002954 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002955 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002956
Kate Stoneb9c1b512016-09-06 20:57:50 +00002957 const char *error_string = error.AsCString();
2958 if (error_string == nullptr)
2959 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00002960
Kate Stoneb9c1b512016-09-06 20:57:50 +00002961 SetExitStatus(-1, error_string);
2962 }
Greg Claytonb766a732011-02-04 01:58:07 +00002963 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 }
2965 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00002966}
2967
Kate Stoneb9c1b512016-09-06 20:57:50 +00002968void Process::CompleteAttach() {
2969 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2970 LIBLLDB_LOG_TARGET));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002971 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002972
2973 // Let the process subclass figure out at much as it can about the process
2974 // before we go looking for a dynamic loader plug-in.
2975 ArchSpec process_arch;
2976 DidAttach(process_arch);
2977
2978 if (process_arch.IsValid()) {
2979 GetTarget().SetArchitecture(process_arch);
2980 if (log) {
2981 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002982 LLDB_LOGF(log,
2983 "Process::%s replacing process architecture with DidAttach() "
2984 "architecture: %s",
2985 __FUNCTION__, triple_str ? triple_str : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002986 }
2987 }
2988
2989 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00002990 // architecture, and if it isn't the same as the one we've already set,
2991 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 PlatformSP platform_sp(GetTarget().GetPlatform());
2993 assert(platform_sp);
2994 if (platform_sp) {
2995 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2996 if (target_arch.IsValid() &&
2997 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2998 ArchSpec platform_arch;
2999 platform_sp =
3000 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3001 if (platform_sp) {
3002 GetTarget().SetPlatform(platform_sp);
3003 GetTarget().SetArchitecture(platform_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003004 LLDB_LOGF(log,
3005 "Process::%s switching platform to %s and architecture "
3006 "to %s based on info from attach",
3007 __FUNCTION__, platform_sp->GetName().AsCString(""),
3008 platform_arch.GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009 }
3010 } else if (!process_arch.IsValid()) {
3011 ProcessInstanceInfo process_info;
3012 GetProcessInfo(process_info);
3013 const ArchSpec &process_arch = process_info.GetArchitecture();
3014 if (process_arch.IsValid() &&
3015 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3016 GetTarget().SetArchitecture(process_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003017 LLDB_LOGF(log,
3018 "Process::%s switching architecture to %s based on info "
3019 "the platform retrieved for pid %" PRIu64,
3020 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
3021 GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003022 }
3023 }
3024 }
3025
3026 // We have completed the attach, now it is time to find the dynamic loader
3027 // plug-in
3028 DynamicLoader *dyld = GetDynamicLoader();
3029 if (dyld) {
3030 dyld->DidAttach();
3031 if (log) {
3032 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003033 LLDB_LOGF(log,
3034 "Process::%s after DynamicLoader::DidAttach(), target "
3035 "executable is %s (using %s plugin)",
3036 __FUNCTION__,
3037 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3038 : "<none>",
3039 dyld->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003040 }
3041 }
3042
3043 GetJITLoaders().DidAttach();
3044
3045 SystemRuntime *system_runtime = GetSystemRuntime();
3046 if (system_runtime) {
3047 system_runtime->DidAttach();
3048 if (log) {
3049 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003050 LLDB_LOGF(log,
3051 "Process::%s after SystemRuntime::DidAttach(), target "
3052 "executable is %s (using %s plugin)",
3053 __FUNCTION__,
3054 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3055 : "<none>",
3056 system_runtime->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003057 }
3058 }
3059
Jim Ingham8864b432019-06-28 17:57:19 +00003060 if (!m_os_up) {
Greg Clayton29eeea02017-02-09 18:55:41 +00003061 LoadOperatingSystemPlugin(false);
Jim Ingham8864b432019-06-28 17:57:19 +00003062 if (m_os_up) {
3063 // Somebody might have gotten threads before now, but we need to force the
3064 // update after we've loaded the OperatingSystem plugin or it won't get a
3065 // chance to process the threads.
3066 m_thread_list.Clear();
3067 UpdateThreadListIfNeeded();
3068 }
3069 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003070 // Figure out which one is the executable, and set that in our target:
3071 const ModuleList &target_modules = GetTarget().GetImages();
3072 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3073 size_t num_modules = target_modules.GetSize();
3074 ModuleSP new_executable_module_sp;
3075
3076 for (size_t i = 0; i < num_modules; i++) {
3077 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3078 if (module_sp && module_sp->IsExecutable()) {
3079 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3080 new_executable_module_sp = module_sp;
3081 break;
3082 }
3083 }
3084 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00003085 GetTarget().SetExecutableModule(new_executable_module_sp,
3086 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003087 if (log) {
3088 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003089 LLDB_LOGF(
3090 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003091 "Process::%s after looping through modules, target executable is %s",
3092 __FUNCTION__,
3093 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3094 : "<none>");
3095 }
3096 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003097}
3098
Jonas Devlieghere32d35fb2020-07-13 13:44:01 -07003099Status Process::ConnectRemote(llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003100 m_abi_sp.reset();
3101 m_process_input_reader.reset();
3102
3103 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003104 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003105
Jonas Devlieghere32d35fb2020-07-13 13:44:01 -07003106 Status error(DoConnectRemote(remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003107 if (error.Success()) {
3108 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3109 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003110 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003111
3112 if (state == eStateStopped || state == eStateCrashed) {
3113 // If we attached and actually have a process on the other end, then
3114 // this ended up being the equivalent of an attach.
3115 CompleteAttach();
3116
3117 // This delays passing the stopped event to listeners till
3118 // CompleteAttach gets a chance to complete...
3119 HandlePrivateEvent(event_sp);
3120 }
3121 }
3122
3123 if (PrivateStateThreadIsValid())
3124 ResumePrivateStateThread();
3125 else
3126 StartPrivateStateThread();
3127 }
3128 return error;
3129}
3130
Zachary Turner97206d52017-05-12 04:51:55 +00003131Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003132 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3133 LIBLLDB_LOG_STEP));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003134 LLDB_LOGF(log,
3135 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3136 "private state: %s",
3137 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3138 StateAsCString(m_private_state.GetValue()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139
Adrian Prantl05097242018-04-30 16:49:04 +00003140 // If signals handing status changed we might want to update our signal
3141 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003142 UpdateAutomaticSignalFiltering();
3143
Zachary Turner97206d52017-05-12 04:51:55 +00003144 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003145 // Tell the process it is about to resume before the thread list
3146 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003147 // Now let the thread list know we are about to resume so it can let all of
3148 // our threads know that they are about to be resumed. Threads will each be
3149 // called with Thread::WillResume(StateType) where StateType contains the
3150 // state that they are supposed to have when the process is resumed
3151 // (suspended/running/stepping). Threads should also check their resume
3152 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3153 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003154 if (m_thread_list.WillResume()) {
3155 // Last thing, do the PreResumeActions.
3156 if (!RunPreResumeActions()) {
Jonas Devlieghere89533762020-07-20 22:57:06 -07003157 error.SetErrorString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003158 "Process::PrivateResume PreResumeActions failed, not resuming.");
3159 } else {
3160 m_mod_id.BumpResumeID();
3161 error = DoResume();
3162 if (error.Success()) {
3163 DidResume();
3164 m_thread_list.DidResume();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003165 LLDB_LOGF(log, "Process thinks the process has resumed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003166 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003167 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003168 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003169 }
3170 }
3171 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003172 // Somebody wanted to run without running (e.g. we were faking a step
3173 // from one frame of a set of inlined frames that share the same PC to
3174 // another.) So generate a continue & a stopped event, and let the world
3175 // handle them.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003176 LLDB_LOGF(log,
3177 "Process::PrivateResume() asked to simulate a start & stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003178
3179 SetPrivateState(eStateRunning);
3180 SetPrivateState(eStateStopped);
3181 }
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003182 } else
3183 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3184 error.AsCString("<unknown error>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003185 return error;
3186}
3187
Zachary Turner97206d52017-05-12 04:51:55 +00003188Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003189 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003190 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003191
Adrian Prantl05097242018-04-30 16:49:04 +00003192 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3193 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003194 m_clear_thread_plans_on_stop |= clear_thread_plans;
3195
3196 ListenerSP halt_listener_sp(
3197 Listener::MakeListener("lldb.process.halt_listener"));
3198 HijackProcessEvents(halt_listener_sp);
3199
3200 EventSP event_sp;
3201
3202 SendAsyncInterrupt();
3203
3204 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003205 // Don't hijack and eat the eStateExited as the code that was doing the
3206 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003207 RestoreProcessEvents();
3208 SetExitStatus(SIGKILL, "Cancelled async attach.");
3209 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003210 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003211 }
3212
3213 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003214 StateType state = WaitForProcessToStop(
3215 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003216 RestoreProcessEvents();
3217
3218 if (state == eStateInvalid || !event_sp) {
3219 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003220 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003221 }
3222
3223 BroadcastEvent(event_sp);
3224
Zachary Turner97206d52017-05-12 04:51:55 +00003225 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003226}
3227
Zachary Turner97206d52017-05-12 04:51:55 +00003228Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3229 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003230
3231 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003232 // expression, for instance, then the public state will be stopped, but we
3233 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003234 if (m_public_state.GetValue() == eStateRunning ||
3235 m_private_state.GetValue() == eStateRunning) {
3236 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003237 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003238
Kate Stoneb9c1b512016-09-06 20:57:50 +00003239 ListenerSP listener_sp(
3240 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3241 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003242
Pavel Labath19da1f12015-12-07 12:36:52 +00003243 SendAsyncInterrupt();
3244
Kate Stoneb9c1b512016-09-06 20:57:50 +00003245 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003246 StateType state =
3247 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003248
Pavel Labath19da1f12015-12-07 12:36:52 +00003249 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003250
Kate Stoneb9c1b512016-09-06 20:57:50 +00003251 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003252 // exited event into the shared pointer passed in and return. Our caller
3253 // doesn't need to do anything else, since they don't have a process
3254 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003255
3256 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003257 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3258 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003259 return error;
3260 } else
3261 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3262
3263 if (state != eStateStopped) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003264 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3265 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003266 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003267 // here, but if the lower levels just bobbled sending the event and we
3268 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003269 StateType private_state = m_private_state.GetValue();
3270 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003271 return Status(
3272 "Attempt to stop the target in order to detach timed out. "
3273 "State = %s",
3274 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003275 }
3276 }
3277 }
3278 return error;
3279}
3280
Zachary Turner97206d52017-05-12 04:51:55 +00003281Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003282 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003283 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003284 m_destroy_in_process = true;
3285
3286 error = WillDetach();
3287
3288 if (error.Success()) {
3289 if (DetachRequiresHalt()) {
3290 error = StopForDestroyOrDetach(exit_event_sp);
3291 if (!error.Success()) {
3292 m_destroy_in_process = false;
3293 return error;
3294 } else if (exit_event_sp) {
3295 // We shouldn't need to do anything else here. There's no process left
3296 // to detach from...
3297 StopPrivateStateThread();
3298 m_destroy_in_process = false;
3299 return error;
3300 }
3301 }
3302
3303 m_thread_list.DiscardThreadPlans();
3304 DisableAllBreakpointSites();
3305
3306 error = DoDetach(keep_stopped);
3307 if (error.Success()) {
3308 DidDetach();
3309 StopPrivateStateThread();
3310 } else {
3311 return error;
3312 }
3313 }
3314 m_destroy_in_process = false;
3315
Adrian Prantl05097242018-04-30 16:49:04 +00003316 // If we exited when we were waiting for a process to stop, then forward the
3317 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003318 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003319 // Directly broadcast our exited event because we shut down our private
3320 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003321 BroadcastEvent(exit_event_sp);
3322 }
3323
3324 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003325 // not end up propagating the last events through the event system, in which
3326 // case we might strand the write lock. Unlock it here so when we do to tear
3327 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003328
3329 m_public_run_lock.SetStopped();
3330 return error;
3331}
3332
Zachary Turner97206d52017-05-12 04:51:55 +00003333Status Process::Destroy(bool force_kill) {
Jim Ingham61e8e682020-03-10 16:18:11 -07003334 // If we've already called Process::Finalize then there's nothing useful to
3335 // be done here. Finalize has actually called Destroy already.
3336 if (m_finalize_called)
3337 return {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003338
3339 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003340 // don't do any unnecessary work that might hinder the destruction. Remember
3341 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003342 // failed and the process stays around for some reason it won't be in a
3343 // confused state.
3344
3345 if (force_kill)
3346 m_should_detach = false;
3347
3348 if (GetShouldDetach()) {
3349 // FIXME: This will have to be a process setting:
3350 bool keep_stopped = false;
3351 Detach(keep_stopped);
3352 }
3353
3354 m_destroy_in_process = true;
3355
Zachary Turner97206d52017-05-12 04:51:55 +00003356 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003357 if (error.Success()) {
3358 EventSP exit_event_sp;
3359 if (DestroyRequiresHalt()) {
3360 error = StopForDestroyOrDetach(exit_event_sp);
3361 }
3362
3363 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003364 // Ditch all thread plans, and remove all our breakpoints: in case we
3365 // have to restart the target to kill it, we don't want it hitting a
3366 // breakpoint... Only do this if we've stopped, however, since if we
3367 // didn't manage to halt it above, then we're not going to have much luck
3368 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003369 m_thread_list.DiscardThreadPlans();
3370 DisableAllBreakpointSites();
3371 }
3372
3373 error = DoDestroy();
3374 if (error.Success()) {
3375 DidDestroy();
3376 StopPrivateStateThread();
3377 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003378 m_stdio_communication.StopReadThread();
Pavel Labath93212552020-04-23 16:27:01 +02003379 m_stdio_communication.Disconnect();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003380 m_stdin_forward = false;
3381
3382 if (m_process_input_reader) {
3383 m_process_input_reader->SetIsDone(true);
3384 m_process_input_reader->Cancel();
3385 m_process_input_reader.reset();
3386 }
3387
Adrian Prantl05097242018-04-30 16:49:04 +00003388 // If we exited when we were waiting for a process to stop, then forward
3389 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003390 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003391 // Directly broadcast our exited event because we shut down our private
3392 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003393 BroadcastEvent(exit_event_sp);
3394 }
3395
Adrian Prantl05097242018-04-30 16:49:04 +00003396 // If we have been interrupted (to kill us) in the middle of running, we
3397 // may not end up propagating the last events through the event system, in
3398 // which case we might strand the write lock. Unlock it here so when we do
3399 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003400 m_public_run_lock.SetStopped();
3401 }
3402
3403 m_destroy_in_process = false;
3404
3405 return error;
3406}
3407
Zachary Turner97206d52017-05-12 04:51:55 +00003408Status Process::Signal(int signal) {
3409 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003410 if (error.Success()) {
3411 error = DoSignal(signal);
3412 if (error.Success())
3413 DidSignal();
3414 }
3415 return error;
3416}
3417
3418void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3419 assert(signals_sp && "null signals_sp");
3420 m_unix_signals_sp = signals_sp;
3421}
3422
3423const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3424 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3425 return m_unix_signals_sp;
3426}
3427
3428lldb::ByteOrder Process::GetByteOrder() const {
3429 return GetTarget().GetArchitecture().GetByteOrder();
3430}
3431
3432uint32_t Process::GetAddressByteSize() const {
3433 return GetTarget().GetArchitecture().GetAddressByteSize();
3434}
3435
3436bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3437 const StateType state =
3438 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3439 bool return_value = true;
3440 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3441 LIBLLDB_LOG_PROCESS));
3442
3443 switch (state) {
3444 case eStateDetached:
3445 case eStateExited:
3446 case eStateUnloaded:
3447 m_stdio_communication.SynchronizeWithReadThread();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003448 m_stdio_communication.StopReadThread();
Jonas Devlieghereb424b0b2020-04-22 16:51:56 -07003449 m_stdio_communication.Disconnect();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003450 m_stdin_forward = false;
3451
3452 LLVM_FALLTHROUGH;
3453 case eStateConnected:
3454 case eStateAttaching:
3455 case eStateLaunching:
3456 // These events indicate changes in the state of the debugging session,
3457 // always report them.
3458 return_value = true;
3459 break;
3460 case eStateInvalid:
3461 // We stopped for no apparent reason, don't report it.
3462 return_value = false;
3463 break;
3464 case eStateRunning:
3465 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003466 // If we've started the target running, we handle the cases where we are
3467 // already running and where there is a transition from stopped to running
3468 // differently. running -> running: Automatically suppress extra running
3469 // events stopped -> running: Report except when there is one or more no
3470 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003471 // and no yes votes.
3472 SynchronouslyNotifyStateChanged(state);
3473 if (m_force_next_event_delivery)
3474 return_value = true;
3475 else {
3476 switch (m_last_broadcast_state) {
3477 case eStateRunning:
3478 case eStateStepping:
3479 // We always suppress multiple runnings with no PUBLIC stop in between.
3480 return_value = false;
3481 break;
3482 default:
3483 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003484 // run if we aren't running so we don't miss any running events. If I
3485 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3486 // and hit the breakpoints on multiple threads, then somehow during the
3487 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003488
3489 // This is a transition from stop to run.
3490 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3491 case eVoteYes:
3492 case eVoteNoOpinion:
3493 return_value = true;
3494 break;
3495 case eVoteNo:
3496 return_value = false;
3497 break;
3498 }
3499 break;
3500 }
3501 }
3502 break;
3503 case eStateStopped:
3504 case eStateCrashed:
3505 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003506 // We've stopped. First see if we're going to restart the target. If we
3507 // are going to stop, then we always broadcast the event. If we aren't
3508 // going to stop, let the thread plans decide if we're going to report this
3509 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003510
3511 m_stdio_communication.SynchronizeWithReadThread();
3512 RefreshStateAfterStop();
3513 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003514 LLDB_LOGF(log,
3515 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3516 "interrupt, state: %s",
3517 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003518 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003519 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003520 m_thread_list.ShouldStop(event_ptr);
3521 return_value = true;
3522 } else {
3523 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3524 bool should_resume = false;
3525
3526 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003527 // restarted... Asking the thread list is also not likely to go well,
3528 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003529
3530 if (!was_restarted)
3531 should_resume = !m_thread_list.ShouldStop(event_ptr);
3532
3533 if (was_restarted || should_resume || m_resume_requested) {
3534 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003535 LLDB_LOGF(log,
3536 "Process::ShouldBroadcastEvent: should_resume: %i state: "
3537 "%s was_restarted: %i stop_vote: %d.",
3538 should_resume, StateAsCString(state), was_restarted,
3539 stop_vote);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003540
3541 switch (stop_vote) {
3542 case eVoteYes:
3543 return_value = true;
3544 break;
3545 case eVoteNoOpinion:
3546 case eVoteNo:
3547 return_value = false;
3548 break;
3549 }
3550
3551 if (!was_restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003552 LLDB_LOGF(log,
3553 "Process::ShouldBroadcastEvent (%p) Restarting process "
3554 "from state: %s",
3555 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003556 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3557 PrivateResume();
3558 }
3559 } else {
3560 return_value = true;
3561 SynchronouslyNotifyStateChanged(state);
3562 }
3563 }
3564 break;
3565 }
3566
3567 // Forcing the next event delivery is a one shot deal. So reset it here.
3568 m_force_next_event_delivery = false;
3569
3570 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003571 // events get coalesced.) But we only coalesce against events we actually
3572 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3573 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3574 // done, because the PublicState reflects the last event pulled off the
3575 // queue, and there may be several events stacked up on the queue unserviced.
3576 // So the PublicState may not reflect the last broadcasted event yet.
3577 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003578
3579 if (return_value)
3580 m_last_broadcast_state = state;
3581
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003582 LLDB_LOGF(log,
3583 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3584 "broadcast state: %s - %s",
3585 static_cast<void *>(event_ptr), StateAsCString(state),
3586 StateAsCString(m_last_broadcast_state),
3587 return_value ? "YES" : "NO");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003588 return return_value;
3589}
3590
3591bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3592 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3593
3594 bool already_running = PrivateStateThreadIsValid();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003595 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
3596 already_running ? " already running"
3597 : " starting private state thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003598
3599 if (!is_secondary_thread && already_running)
3600 return true;
3601
Adrian Prantl05097242018-04-30 16:49:04 +00003602 // Create a thread that watches our internal state and controls which events
3603 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003604 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003605 uint32_t max_len = llvm::get_max_thread_name_length();
3606 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003607 // On platforms with abbreviated thread name lengths, choose thread names
3608 // that fit within the limit.
3609 if (already_running)
3610 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3611 else
3612 snprintf(thread_name, sizeof(thread_name), "intern-state");
3613 } else {
3614 if (already_running)
3615 snprintf(thread_name, sizeof(thread_name),
3616 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3617 GetID());
3618 else
3619 snprintf(thread_name, sizeof(thread_name),
3620 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3621 }
3622
3623 // Create the private state thread, and start it running.
3624 PrivateStateThreadArgs *args_ptr =
3625 new PrivateStateThreadArgs(this, is_secondary_thread);
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003626 llvm::Expected<HostThread> private_state_thread =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003627 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003628 (void *)args_ptr, 8 * 1024 * 1024);
3629 if (!private_state_thread) {
3630 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3631 "failed to launch host thread: {}",
3632 llvm::toString(private_state_thread.takeError()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003633 return false;
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003634 }
3635
3636 assert(private_state_thread->IsJoinable());
3637 m_private_state_thread = *private_state_thread;
3638 ResumePrivateStateThread();
3639 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003640}
3641
3642void Process::PausePrivateStateThread() {
3643 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3644}
3645
3646void Process::ResumePrivateStateThread() {
3647 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3648}
3649
3650void Process::StopPrivateStateThread() {
3651 if (m_private_state_thread.IsJoinable())
3652 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3653 else {
3654 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003655 LLDB_LOGF(
3656 log,
3657 "Went to stop the private state thread, but it was already invalid.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003658 }
3659}
3660
3661void Process::ControlPrivateStateThread(uint32_t signal) {
3662 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3663
3664 assert(signal == eBroadcastInternalStateControlStop ||
3665 signal == eBroadcastInternalStateControlPause ||
3666 signal == eBroadcastInternalStateControlResume);
3667
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003668 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003669
3670 // Signal the private state thread
3671 if (m_private_state_thread.IsJoinable()) {
3672 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003673 // It is important to do this outside of the if below, because it's
3674 // possible that the thread state is invalid but that the thread is waiting
3675 // on a control event instead of simply being on its way out (this should
3676 // not happen, but it apparently can).
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003677 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003678 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3679 m_private_state_control_broadcaster.BroadcastEvent(signal,
3680 event_receipt_sp);
3681
3682 // Wait for the event receipt or for the private state thread to exit
3683 bool receipt_received = false;
3684 if (PrivateStateThreadIsValid()) {
3685 while (!receipt_received) {
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003686 // Check for a receipt for n seconds and then check if the private
Adrian Prantl05097242018-04-30 16:49:04 +00003687 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003688 receipt_received =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003689 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003690 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003691 // Check if the private state thread is still around. If it isn't
3692 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003693 if (!PrivateStateThreadIsValid())
3694 break; // Private state thread exited or is exiting, we are done
3695 }
3696 }
3697 }
3698
3699 if (signal == eBroadcastInternalStateControlStop) {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003700 thread_result_t result = {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003701 m_private_state_thread.Join(&result);
3702 m_private_state_thread.Reset();
3703 }
3704 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003705 LLDB_LOGF(
3706 log,
3707 "Private state thread already dead, no need to signal it to stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003708 }
3709}
3710
3711void Process::SendAsyncInterrupt() {
3712 if (PrivateStateThreadIsValid())
3713 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3714 nullptr);
3715 else
3716 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3717}
3718
3719void Process::HandlePrivateEvent(EventSP &event_sp) {
3720 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3721 m_resume_requested = false;
3722
3723 const StateType new_state =
3724 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3725
3726 // First check to see if anybody wants a shot at this event:
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003727 if (m_next_event_action_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003728 NextEventAction::EventActionResult action_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003729 m_next_event_action_up->PerformAction(event_sp);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003730 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003731
3732 switch (action_result) {
3733 case NextEventAction::eEventActionSuccess:
3734 SetNextEventAction(nullptr);
3735 break;
3736
3737 case NextEventAction::eEventActionRetry:
3738 break;
3739
3740 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003741 // Handle Exiting Here. If we already got an exited event, we should
3742 // just propagate it. Otherwise, swallow this event, and set our state
3743 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003744 if (new_state != eStateExited) {
3745 // FIXME: should cons up an exited event, and discard this one.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003746 SetExitStatus(0, m_next_event_action_up->GetExitString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003747 SetNextEventAction(nullptr);
3748 return;
3749 }
3750 SetNextEventAction(nullptr);
3751 break;
3752 }
3753 }
3754
3755 // See if we should broadcast this state to external clients?
3756 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3757
3758 if (should_broadcast) {
3759 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3760 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003761 LLDB_LOGF(log,
3762 "Process::%s (pid = %" PRIu64
3763 ") broadcasting new state %s (old state %s) to %s",
3764 __FUNCTION__, GetID(), StateAsCString(new_state),
3765 StateAsCString(GetState()),
3766 is_hijacked ? "hijacked" : "public");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003767 }
3768 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3769 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003770 // Only push the input handler if we aren't fowarding events, as this
3771 // means the curses GUI is in use... Or don't push it if we are launching
3772 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003773 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3774 new_state != eStateLaunching && new_state != eStateAttaching) {
3775 PushProcessIOHandler();
3776 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3777 eBroadcastAlways);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003778 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
3779 __FUNCTION__, m_iohandler_sync.GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003780 }
3781 } else if (StateIsStoppedState(new_state, false)) {
3782 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003783 // If the lldb_private::Debugger is handling the events, we don't want
3784 // to pop the process IOHandler here, we want to do it when we receive
3785 // the stopped event so we can carefully control when the process
3786 // IOHandler is popped because when we stop we want to display some
3787 // text stating how and why we stopped, then maybe some
3788 // process/thread/frame info, and then we want the "(lldb) " prompt to
3789 // show up. If we pop the process IOHandler here, then we will cause
3790 // the command interpreter to become the top IOHandler after the
3791 // process pops off and it will update its prompt right away... See the
3792 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003793 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3794 // Otherwise we end up getting overlapping "(lldb) " prompts and
3795 // garbled output.
3796 //
3797 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003798 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3799 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003800 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003801 // thread plans, or when commands want to run in synchronous mode and
3802 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003803 // that will hijack the events is a simple expression:
3804 //
3805 // (lldb) expr (int)puts("hello")
3806 //
3807 // This will cause the internal process state thread to resume and halt
3808 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3809 // events) and we do need the IO handler to be pushed and popped
3810 // correctly.
3811
3812 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3813 PopProcessIOHandler();
3814 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003815 }
3816
3817 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003818 } else {
3819 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003820 LLDB_LOGF(
3821 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003822 "Process::%s (pid = %" PRIu64
3823 ") suppressing state %s (old state %s): should_broadcast == false",
3824 __FUNCTION__, GetID(), StateAsCString(new_state),
3825 StateAsCString(GetState()));
3826 }
3827 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003828}
3829
Zachary Turner97206d52017-05-12 04:51:55 +00003830Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003831 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003832 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003833 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003834 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003835
3836 // Ask the process subclass to actually halt our process
3837 bool caused_stop;
3838 error = DoHalt(caused_stop);
3839
3840 DidHalt();
3841 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003842}
3843
Kate Stoneb9c1b512016-09-06 20:57:50 +00003844thread_result_t Process::PrivateStateThread(void *arg) {
3845 std::unique_ptr<PrivateStateThreadArgs> args_up(
3846 static_cast<PrivateStateThreadArgs *>(arg));
3847 thread_result_t result =
3848 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3849 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003850}
3851
Kate Stoneb9c1b512016-09-06 20:57:50 +00003852thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3853 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003854
Kate Stoneb9c1b512016-09-06 20:57:50 +00003855 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003856 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3857 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003858
Kate Stoneb9c1b512016-09-06 20:57:50 +00003859 bool exit_now = false;
3860 bool interrupt_requested = false;
3861 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003862 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003863 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003864 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003865 LLDB_LOGF(log,
3866 "Process::%s (arg = %p, pid = %" PRIu64
3867 ") got a control event: %d",
3868 __FUNCTION__, static_cast<void *>(this), GetID(),
3869 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003870
Kate Stoneb9c1b512016-09-06 20:57:50 +00003871 switch (event_sp->GetType()) {
3872 case eBroadcastInternalStateControlStop:
3873 exit_now = true;
3874 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003875
Kate Stoneb9c1b512016-09-06 20:57:50 +00003876 case eBroadcastInternalStateControlPause:
3877 control_only = true;
3878 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003879
Kate Stoneb9c1b512016-09-06 20:57:50 +00003880 case eBroadcastInternalStateControlResume:
3881 control_only = false;
3882 break;
3883 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003884
Kate Stoneb9c1b512016-09-06 20:57:50 +00003885 continue;
3886 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3887 if (m_public_state.GetValue() == eStateAttaching) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003888 LLDB_LOGF(log,
3889 "Process::%s (arg = %p, pid = %" PRIu64
3890 ") woke up with an interrupt while attaching - "
3891 "forwarding interrupt.",
3892 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003893 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3894 } else if (StateIsRunningState(m_last_broadcast_state)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003895 LLDB_LOGF(log,
3896 "Process::%s (arg = %p, pid = %" PRIu64
3897 ") woke up with an interrupt - Halting.",
3898 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00003899 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003900 if (error.Fail() && log)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003901 LLDB_LOGF(log,
3902 "Process::%s (arg = %p, pid = %" PRIu64
3903 ") failed to halt the process: %s",
3904 __FUNCTION__, static_cast<void *>(this), GetID(),
3905 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00003906 // Halt should generate a stopped event. Make a note of the fact that
3907 // we were doing the interrupt, so we can set the interrupted flag
3908 // after we receive the event. We deliberately set this to true even if
3909 // HaltPrivate failed, so that we can interrupt on the next natural
3910 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003911 interrupt_requested = true;
3912 } else {
3913 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00003914 // running and sends an interrupt request, but the process actually
3915 // stops before we receive it. In that case, we can just ignore the
3916 // request. We use m_last_broadcast_state, because the Stopped event
3917 // may not have been popped of the event queue yet, which is when the
3918 // public state gets updated.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003919 LLDB_LOGF(log,
3920 "Process::%s ignoring interrupt as we have already stopped.",
3921 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003922 }
3923 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003924 }
3925
Kate Stoneb9c1b512016-09-06 20:57:50 +00003926 const StateType internal_state =
3927 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003928
Kate Stoneb9c1b512016-09-06 20:57:50 +00003929 if (internal_state != eStateInvalid) {
3930 if (m_clear_thread_plans_on_stop &&
3931 StateIsStoppedState(internal_state, true)) {
3932 m_clear_thread_plans_on_stop = false;
3933 m_thread_list.DiscardThreadPlans();
3934 }
3935
3936 if (interrupt_requested) {
3937 if (StateIsStoppedState(internal_state, true)) {
3938 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00003939 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00003940 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3941 interrupt_requested = false;
3942 } else if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003943 LLDB_LOGF(log,
3944 "Process::%s interrupt_requested, but a non-stopped "
3945 "state '%s' received.",
3946 __FUNCTION__, StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003947 }
3948 }
3949
3950 HandlePrivateEvent(event_sp);
3951 }
3952
3953 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3954 internal_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003955 LLDB_LOGF(log,
3956 "Process::%s (arg = %p, pid = %" PRIu64
3957 ") about to exit with internal state %s...",
3958 __FUNCTION__, static_cast<void *>(this), GetID(),
3959 StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003960
3961 break;
3962 }
3963 }
3964
3965 // Verify log is still enabled before attempting to write to it...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003966 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3967 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003968
3969 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00003970 // will have already acquired the public_run_lock, and isn't done with what
3971 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003972 if (!is_secondary_thread)
3973 m_public_run_lock.SetStopped();
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003974 return {};
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003975}
3976
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003977// Process Event Data
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003978
Kate Stoneb9c1b512016-09-06 20:57:50 +00003979Process::ProcessEventData::ProcessEventData()
3980 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3981 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003982
Kate Stoneb9c1b512016-09-06 20:57:50 +00003983Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3984 StateType state)
3985 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3986 m_update_state(0), m_interrupted(false) {
3987 if (process_sp)
3988 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003989}
3990
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003991Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003992
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003993ConstString Process::ProcessEventData::GetFlavorString() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003994 static ConstString g_flavor("Process::ProcessEventData");
3995 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003996}
3997
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003998ConstString Process::ProcessEventData::GetFlavor() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003999 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004000}
4001
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004002bool Process::ProcessEventData::ShouldStop(Event *event_ptr,
4003 bool &found_valid_stopinfo) {
4004 found_valid_stopinfo = false;
4005
4006 ProcessSP process_sp(m_process_wp.lock());
4007 if (!process_sp)
4008 return false;
4009
4010 ThreadList &curr_thread_list = process_sp->GetThreadList();
4011 uint32_t num_threads = curr_thread_list.GetSize();
4012 uint32_t idx;
4013
4014 // The actions might change one of the thread's stop_info's opinions about
4015 // whether we should stop the process, so we need to query that as we go.
4016
4017 // One other complication here, is that we try to catch any case where the
4018 // target has run (except for expressions) and immediately exit, but if we
4019 // get that wrong (which is possible) then the thread list might have
4020 // changed, and that would cause our iteration here to crash. We could
4021 // make a copy of the thread list, but we'd really like to also know if it
4022 // has changed at all, so we make up a vector of the thread ID's and check
4023 // what we get back against this list & bag out if anything differs.
4024 ThreadList not_suspended_thread_list(process_sp.get());
4025 std::vector<uint32_t> thread_index_array(num_threads);
4026 uint32_t not_suspended_idx = 0;
4027 for (idx = 0; idx < num_threads; ++idx) {
4028 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4029
4030 /*
4031 Filter out all suspended threads, they could not be the reason
4032 of stop and no need to perform any actions on them.
4033 */
4034 if (thread_sp->GetResumeState() != eStateSuspended) {
4035 not_suspended_thread_list.AddThread(thread_sp);
4036 thread_index_array[not_suspended_idx] = thread_sp->GetIndexID();
4037 not_suspended_idx++;
4038 }
4039 }
4040
4041 // Use this to track whether we should continue from here. We will only
4042 // continue the target running if no thread says we should stop. Of course
4043 // if some thread's PerformAction actually sets the target running, then it
4044 // doesn't matter what the other threads say...
4045
4046 bool still_should_stop = false;
4047
4048 // Sometimes - for instance if we have a bug in the stub we are talking to,
4049 // we stop but no thread has a valid stop reason. In that case we should
4050 // just stop, because we have no way of telling what the right thing to do
4051 // is, and it's better to let the user decide than continue behind their
4052 // backs.
4053
4054 for (idx = 0; idx < not_suspended_thread_list.GetSize(); ++idx) {
4055 curr_thread_list = process_sp->GetThreadList();
4056 if (curr_thread_list.GetSize() != num_threads) {
4057 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4058 LIBLLDB_LOG_PROCESS));
4059 LLDB_LOGF(
4060 log,
4061 "Number of threads changed from %u to %u while processing event.",
4062 num_threads, curr_thread_list.GetSize());
4063 break;
4064 }
4065
4066 lldb::ThreadSP thread_sp = not_suspended_thread_list.GetThreadAtIndex(idx);
4067
4068 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4069 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4070 LIBLLDB_LOG_PROCESS));
4071 LLDB_LOGF(log,
4072 "The thread at position %u changed from %u to %u while "
4073 "processing event.",
4074 idx, thread_index_array[idx], thread_sp->GetIndexID());
4075 break;
4076 }
4077
4078 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4079 if (stop_info_sp && stop_info_sp->IsValid()) {
4080 found_valid_stopinfo = true;
4081 bool this_thread_wants_to_stop;
4082 if (stop_info_sp->GetOverrideShouldStop()) {
4083 this_thread_wants_to_stop =
4084 stop_info_sp->GetOverriddenShouldStopValue();
4085 } else {
4086 stop_info_sp->PerformAction(event_ptr);
4087 // The stop action might restart the target. If it does, then we
4088 // want to mark that in the event so that whoever is receiving it
4089 // will know to wait for the running event and reflect that state
4090 // appropriately. We also need to stop processing actions, since they
4091 // aren't expecting the target to be running.
4092
4093 // FIXME: we might have run.
4094 if (stop_info_sp->HasTargetRunSinceMe()) {
4095 SetRestarted(true);
4096 break;
4097 }
4098
4099 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4100 }
4101
4102 if (!still_should_stop)
4103 still_should_stop = this_thread_wants_to_stop;
4104 }
4105 }
4106
4107 return still_should_stop;
4108}
4109
Kate Stoneb9c1b512016-09-06 20:57:50 +00004110void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4111 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004112
Kate Stoneb9c1b512016-09-06 20:57:50 +00004113 if (!process_sp)
4114 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004115
Kate Stoneb9c1b512016-09-06 20:57:50 +00004116 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00004117 // pulled off of the private process event queue, and then any number of
4118 // times, first when it gets pulled off of the public event queue, then other
4119 // times when we're pretending that this is where we stopped at the end of
4120 // expression evaluation. m_update_state is used to distinguish these three
4121 // cases; it is 0 when we're just pulling it off for private handling, and >
4122 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00004123 // command handling then.
4124 if (m_update_state != 1)
4125 return;
4126
4127 process_sp->SetPublicState(
4128 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4129
Jason Molendab3a3cd12016-12-08 06:27:29 +00004130 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00004131 // Let process subclasses know we are about to do a public stop and do
4132 // anything they might need to in order to speed up register and memory
4133 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00004134 process_sp->WillPublicStop();
4135 }
4136
Kate Stoneb9c1b512016-09-06 20:57:50 +00004137 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00004138 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4139 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00004140 // end up restarting the process.
4141 if (m_interrupted)
4142 return;
4143
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004144 // If we're not stopped or have restarted, then skip the StopInfo actions:
4145 if (m_state != eStateStopped || m_restarted) {
4146 return;
4147 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004148
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004149 bool does_anybody_have_an_opinion = false;
4150 bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004151
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004152 if (GetRestarted()) {
4153 return;
4154 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004155
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004156 if (!still_should_stop && does_anybody_have_an_opinion) {
4157 // We've been asked to continue, so do that here.
4158 SetRestarted(true);
4159 // Use the public resume method here, since this is just extending a
4160 // public resume.
4161 process_sp->PrivateResume();
4162 } else {
4163 bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4164 !process_sp->StateChangedIsHijackedForSynchronousResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004165
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004166 if (!hijacked) {
4167 // If we didn't restart, run the Stop Hooks here.
4168 // Don't do that if state changed events aren't hooked up to the
4169 // public (or SyncResume) broadcasters. StopHooks are just for
4170 // real public stops. They might also restart the target,
4171 // so watch for that.
4172 process_sp->GetTarget().RunStopHooks();
4173 if (process_sp->GetPrivateState() == eStateRunning)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004174 SetRestarted(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004175 }
4176 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004177}
4178
Kate Stoneb9c1b512016-09-06 20:57:50 +00004179void Process::ProcessEventData::Dump(Stream *s) const {
4180 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004181
Kate Stoneb9c1b512016-09-06 20:57:50 +00004182 if (process_sp)
4183 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4184 static_cast<void *>(process_sp.get()), process_sp->GetID());
4185 else
4186 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004187
Kate Stoneb9c1b512016-09-06 20:57:50 +00004188 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004189}
4190
4191const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004192Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4193 if (event_ptr) {
4194 const EventData *event_data = event_ptr->GetData();
4195 if (event_data &&
4196 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4197 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4198 }
4199 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004200}
4201
4202ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004203Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4204 ProcessSP process_sp;
4205 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4206 if (data)
4207 process_sp = data->GetProcessSP();
4208 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004209}
4210
Kate Stoneb9c1b512016-09-06 20:57:50 +00004211StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4212 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4213 if (data == nullptr)
4214 return eStateInvalid;
4215 else
4216 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004217}
4218
Kate Stoneb9c1b512016-09-06 20:57:50 +00004219bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4220 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4221 if (data == nullptr)
4222 return false;
4223 else
4224 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004225}
4226
Kate Stoneb9c1b512016-09-06 20:57:50 +00004227void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4228 bool new_value) {
4229 ProcessEventData *data =
4230 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4231 if (data != nullptr)
4232 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004233}
4234
Jim Ingham0161b492013-02-09 01:29:05 +00004235size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004236Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4237 ProcessEventData *data =
4238 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4239 if (data != nullptr)
4240 return data->GetNumRestartedReasons();
4241 else
4242 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004243}
4244
4245const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004246Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4247 size_t idx) {
4248 ProcessEventData *data =
4249 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4250 if (data != nullptr)
4251 return data->GetRestartedReasonAtIndex(idx);
4252 else
4253 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004254}
4255
Kate Stoneb9c1b512016-09-06 20:57:50 +00004256void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4257 const char *reason) {
4258 ProcessEventData *data =
4259 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4260 if (data != nullptr)
4261 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004262}
4263
Kate Stoneb9c1b512016-09-06 20:57:50 +00004264bool Process::ProcessEventData::GetInterruptedFromEvent(
4265 const Event *event_ptr) {
4266 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4267 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004268 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004269 else
4270 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004271}
4272
Kate Stoneb9c1b512016-09-06 20:57:50 +00004273void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4274 bool new_value) {
4275 ProcessEventData *data =
4276 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4277 if (data != nullptr)
4278 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004279}
4280
Kate Stoneb9c1b512016-09-06 20:57:50 +00004281bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4282 ProcessEventData *data =
4283 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4284 if (data) {
4285 data->SetUpdateStateOnRemoval();
4286 return true;
4287 }
4288 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004289}
4290
Jim Inghamb87b9e62018-06-26 23:38:58 +00004291lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004292
4293void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4294 exe_ctx.SetTargetPtr(&GetTarget());
4295 exe_ctx.SetProcessPtr(this);
4296 exe_ctx.SetThreadPtr(nullptr);
4297 exe_ctx.SetFramePtr(nullptr);
4298}
4299
4300// uint32_t
4301// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4302// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004303//{
4304// return 0;
4305//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004306//
4307// ArchSpec
4308// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004309//{
4310// return Host::GetArchSpecForExistingProcess (pid);
4311//}
4312//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004313// ArchSpec
4314// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004315//{
4316// return Host::GetArchSpecForExistingProcess (process_name);
4317//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004318
Kate Stoneb9c1b512016-09-06 20:57:50 +00004319void Process::AppendSTDOUT(const char *s, size_t len) {
4320 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4321 m_stdout_data.append(s, len);
4322 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4323 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004324}
4325
Kate Stoneb9c1b512016-09-06 20:57:50 +00004326void Process::AppendSTDERR(const char *s, size_t len) {
4327 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4328 m_stderr_data.append(s, len);
4329 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4330 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004331}
4332
Kate Stoneb9c1b512016-09-06 20:57:50 +00004333void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4334 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4335 m_profile_data.push_back(one_profile_data);
4336 BroadcastEventIfUnique(eBroadcastBitProfileData,
4337 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004338}
4339
Kate Stoneb9c1b512016-09-06 20:57:50 +00004340void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4341 const StructuredDataPluginSP &plugin_sp) {
4342 BroadcastEvent(
4343 eBroadcastBitStructuredData,
4344 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004345}
4346
4347StructuredDataPluginSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004348Process::GetStructuredDataPlugin(ConstString type_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004349 auto find_it = m_structured_data_plugin_map.find(type_name);
4350 if (find_it != m_structured_data_plugin_map.end())
4351 return find_it->second;
4352 else
4353 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004354}
4355
Zachary Turner97206d52017-05-12 04:51:55 +00004356size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004357 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4358 if (m_profile_data.empty())
4359 return 0;
4360
4361 std::string &one_profile_data = m_profile_data.front();
4362 size_t bytes_available = one_profile_data.size();
4363 if (bytes_available > 0) {
4364 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004365 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4366 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004367 if (bytes_available > buf_size) {
4368 memcpy(buf, one_profile_data.c_str(), buf_size);
4369 one_profile_data.erase(0, buf_size);
4370 bytes_available = buf_size;
4371 } else {
4372 memcpy(buf, one_profile_data.c_str(), bytes_available);
4373 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004374 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004375 }
4376 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004377}
4378
Greg Clayton93e86192011-11-13 04:45:22 +00004379// Process STDIO
Greg Clayton93e86192011-11-13 04:45:22 +00004380
Zachary Turner97206d52017-05-12 04:51:55 +00004381size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004382 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4383 size_t bytes_available = m_stdout_data.size();
4384 if (bytes_available > 0) {
4385 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004386 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4387 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004388 if (bytes_available > buf_size) {
4389 memcpy(buf, m_stdout_data.c_str(), buf_size);
4390 m_stdout_data.erase(0, buf_size);
4391 bytes_available = buf_size;
4392 } else {
4393 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4394 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004395 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004396 }
4397 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004398}
4399
Zachary Turner97206d52017-05-12 04:51:55 +00004400size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004401 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4402 size_t bytes_available = m_stderr_data.size();
4403 if (bytes_available > 0) {
4404 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004405 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4406 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004407 if (bytes_available > buf_size) {
4408 memcpy(buf, m_stderr_data.c_str(), buf_size);
4409 m_stderr_data.erase(0, buf_size);
4410 bytes_available = buf_size;
4411 } else {
4412 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4413 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004414 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004415 }
4416 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004417}
4418
Kate Stoneb9c1b512016-09-06 20:57:50 +00004419void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4420 size_t src_len) {
4421 Process *process = (Process *)baton;
4422 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004423}
4424
Kate Stoneb9c1b512016-09-06 20:57:50 +00004425class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004426public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004427 IOHandlerProcessSTDIO(Process *process, int write_fd)
4428 : IOHandler(process->GetTarget().GetDebugger(),
4429 IOHandler::Type::ProcessIO),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004430 m_process(process),
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00004431 m_read_file(GetInputFD(), File::eOpenOptionRead, false),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004432 m_write_file(write_fd, File::eOpenOptionWrite, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004433 m_pipe.CreateNew(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004434 }
4435
4436 ~IOHandlerProcessSTDIO() override = default;
4437
Adrian Prantl05097242018-04-30 16:49:04 +00004438 // Each IOHandler gets to run until it is done. It should read data from the
4439 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004440 void Run() override {
4441 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4442 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4443 SetIsDone(true);
4444 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004445 }
4446
Kate Stoneb9c1b512016-09-06 20:57:50 +00004447 SetIsDone(false);
4448 const int read_fd = m_read_file.GetDescriptor();
4449 TerminalState terminal_state;
4450 terminal_state.Save(read_fd, false);
4451 Terminal terminal(read_fd);
4452 terminal.SetCanonical(false);
4453 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004454// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004455#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004456 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4457 m_is_running = true;
4458 while (!GetIsDone()) {
4459 SelectHelper select_helper;
4460 select_helper.FDSetRead(read_fd);
4461 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004462 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004463
Kate Stoneb9c1b512016-09-06 20:57:50 +00004464 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004465 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004466 } else {
4467 char ch = 0;
4468 size_t n;
4469 if (select_helper.FDIsSetRead(read_fd)) {
4470 n = 1;
4471 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4472 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4473 SetIsDone(true);
4474 } else
4475 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004476 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004477 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4478 size_t bytes_read;
4479 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004480 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004481 if (error.Success()) {
4482 switch (ch) {
4483 case 'q':
4484 SetIsDone(true);
4485 break;
4486 case 'i':
4487 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004488 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004489 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004490 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004491 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004492 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004493 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004494 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004495 m_is_running = false;
4496#endif
4497 terminal_state.Restore();
4498 }
4499
4500 void Cancel() override {
4501 SetIsDone(true);
4502 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004503 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4504 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004505 //
4506 // (lldb) step_process_thousands_of_times
4507 //
4508 // In this case the command interpreter will be in the middle of handling
4509 // the command and if the process pushes and pops the IOHandler thousands
4510 // of times, we can end up writing to m_pipe without ever consuming the
4511 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4512 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4513 if (m_is_running) {
4514 char ch = 'q'; // Send 'q' for quit
4515 size_t bytes_written = 0;
4516 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004517 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004518 }
4519
4520 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004521 // Do only things that are safe to do in an interrupt context (like in a
4522 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004523 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4524 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004525 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004526 if (m_active) {
4527 char ch = 'i'; // Send 'i' for interrupt
4528 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004529 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004530 return result.Success();
4531 } else {
4532 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004533 // currently so do the right thing if we aren't actively watching for
4534 // STDIN by sending the interrupt to the process. Otherwise the write to
4535 // the pipe above would do nothing. This can happen when the command
4536 // interpreter is running and gets a "expression ...". It will be on the
4537 // IOHandler thread and sending the input is complete to the delegate
4538 // which will cause the expression to run, which will push the process IO
4539 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004540
4541 if (StateIsRunningState(m_process->GetState())) {
4542 m_process->SendAsyncInterrupt();
4543 return true;
4544 }
4545 }
4546 return false;
4547 }
4548
4549 void GotEOF() override {}
4550
Greg Clayton44d93782014-01-27 23:43:24 +00004551protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004552 Process *m_process;
Lawrence D'Annaf913fd62019-10-03 04:31:46 +00004553 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
4554 NativeFile m_write_file; // Write to this file (usually the master pty for
4555 // getting io to debuggee)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004556 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004557 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004558};
4559
Kate Stoneb9c1b512016-09-06 20:57:50 +00004560void Process::SetSTDIOFileDescriptor(int fd) {
4561 // First set up the Read Thread for reading/handling process I/O
Pavel Labath451741a2020-04-02 14:40:59 +02004562 m_stdio_communication.SetConnection(
4563 std::make_unique<ConnectionFileDescriptor>(fd, true));
4564 if (m_stdio_communication.IsConnected()) {
4565 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4566 STDIOReadThreadBytesReceived, this);
4567 m_stdio_communication.StartReadThread();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004568
Pavel Labath451741a2020-04-02 14:40:59 +02004569 // Now read thread is set up, set up input reader.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004570
Pavel Labath451741a2020-04-02 14:40:59 +02004571 if (!m_process_input_reader)
4572 m_process_input_reader =
4573 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004574 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004575}
4576
Kate Stoneb9c1b512016-09-06 20:57:50 +00004577bool Process::ProcessIOHandlerIsActive() {
4578 IOHandlerSP io_handler_sp(m_process_input_reader);
4579 if (io_handler_sp)
4580 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4581 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004582}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004583bool Process::PushProcessIOHandler() {
4584 IOHandlerSP io_handler_sp(m_process_input_reader);
4585 if (io_handler_sp) {
4586 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004587 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004588
Kate Stoneb9c1b512016-09-06 20:57:50 +00004589 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004590 // If we evaluate an utility function, then we don't cancel the current
4591 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4592 // existing IOHandler that potentially provides the user interface (e.g.
4593 // the IOHandler for Editline).
4594 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004595 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
4596 cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004597 return true;
4598 }
4599 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004600}
4601
Kate Stoneb9c1b512016-09-06 20:57:50 +00004602bool Process::PopProcessIOHandler() {
4603 IOHandlerSP io_handler_sp(m_process_input_reader);
4604 if (io_handler_sp)
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004605 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004606 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004607}
4608
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004609// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004610void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004611
Kate Stoneb9c1b512016-09-06 20:57:50 +00004612void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004613
Kate Stoneb9c1b512016-09-06 20:57:50 +00004614namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004615// RestorePlanState is used to record the "is private", "is master" and "okay
4616// to discard" fields of the plan we are running, and reset it on Clean or on
4617// destruction. It will only reset the state once, so you can call Clean and
4618// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004619
Kate Stoneb9c1b512016-09-06 20:57:50 +00004620class RestorePlanState {
4621public:
4622 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4623 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4624 if (m_thread_plan_sp) {
4625 m_private = m_thread_plan_sp->GetPrivate();
4626 m_is_master = m_thread_plan_sp->IsMasterPlan();
4627 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4628 }
4629 }
4630
4631 ~RestorePlanState() { Clean(); }
4632
4633 void Clean() {
4634 if (!m_already_reset && m_thread_plan_sp) {
4635 m_already_reset = true;
4636 m_thread_plan_sp->SetPrivate(m_private);
4637 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4638 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4639 }
4640 }
4641
4642private:
4643 lldb::ThreadPlanSP m_thread_plan_sp;
4644 bool m_already_reset;
4645 bool m_private;
4646 bool m_is_master;
4647 bool m_okay_to_discard;
4648};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004649} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004650
Pavel Labath2ce22162016-12-01 10:57:30 +00004651static microseconds
4652GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4653 const milliseconds default_one_thread_timeout(250);
4654
4655 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004656 if (!options.GetTimeout()) {
4657 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4658 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004659 }
4660
4661 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004662 if (options.GetOneThreadTimeout())
4663 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004664
4665 // Otherwise use half the total timeout, bounded by the
4666 // default_one_thread_timeout.
4667 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004668 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004669}
4670
4671static Timeout<std::micro>
4672GetExpressionTimeout(const EvaluateExpressionOptions &options,
4673 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004674 // If we are going to run all threads the whole time, or if we are only going
4675 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004676 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004677 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004678
4679 if (before_first_timeout)
4680 return GetOneThreadExpressionTimeout(options);
4681
Pavel Labath43d35412016-12-06 11:24:51 +00004682 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004683 return llvm::None;
4684 else
Pavel Labath43d35412016-12-06 11:24:51 +00004685 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004686}
4687
Pavel Labath45dde232017-05-25 10:50:06 +00004688static llvm::Optional<ExpressionResults>
Jim Inghamdbbed972020-05-20 18:00:56 -07004689HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
Pavel Labath45dde232017-05-25 10:50:06 +00004690 RestorePlanState &restorer, const EventSP &event_sp,
4691 EventSP &event_to_broadcast_sp,
Jim Inghamdbbed972020-05-20 18:00:56 -07004692 const EvaluateExpressionOptions &options,
4693 bool handle_interrupts) {
Pavel Labath45dde232017-05-25 10:50:06 +00004694 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4695
Jim Inghamdbbed972020-05-20 18:00:56 -07004696 ThreadSP thread_sp = thread_plan_sp->GetTarget()
4697 .GetProcessSP()
4698 ->GetThreadList()
4699 .FindThreadByID(thread_id);
4700 if (!thread_sp) {
4701 LLDB_LOG(log,
4702 "The thread on which we were running the "
4703 "expression: tid = {0}, exited while "
4704 "the expression was running.",
4705 thread_id);
4706 return eExpressionThreadVanished;
4707 }
4708
4709 ThreadPlanSP plan = thread_sp->GetCompletedPlan();
Pavel Labath45dde232017-05-25 10:50:06 +00004710 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4711 LLDB_LOG(log, "execution completed successfully");
4712
4713 // Restore the plan state so it will get reported as intended when we are
4714 // done.
4715 restorer.Clean();
4716 return eExpressionCompleted;
4717 }
4718
Jim Inghamdbbed972020-05-20 18:00:56 -07004719 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Pavel Labath45dde232017-05-25 10:50:06 +00004720 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4721 stop_info_sp->ShouldNotify(event_sp.get())) {
4722 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4723 if (!options.DoesIgnoreBreakpoints()) {
4724 // Restore the plan state and then force Private to false. We are going
4725 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004726 // it won't report correctly when we continue to its termination later
4727 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004728 restorer.Clean();
4729 thread_plan_sp->SetPrivate(false);
4730 event_to_broadcast_sp = event_sp;
4731 }
4732 return eExpressionHitBreakpoint;
4733 }
4734
4735 if (!handle_interrupts &&
4736 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4737 return llvm::None;
4738
4739 LLDB_LOG(log, "thread plan did not successfully complete");
4740 if (!options.DoesUnwindOnError())
4741 event_to_broadcast_sp = event_sp;
4742 return eExpressionInterrupted;
4743}
4744
Jim Ingham1624a2d2014-05-05 02:26:40 +00004745ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004746Process::RunThreadPlan(ExecutionContext &exe_ctx,
4747 lldb::ThreadPlanSP &thread_plan_sp,
4748 const EvaluateExpressionOptions &options,
4749 DiagnosticManager &diagnostic_manager) {
4750 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004751
Kate Stoneb9c1b512016-09-06 20:57:50 +00004752 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4753
4754 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004755 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004756 eDiagnosticSeverityError,
4757 "RunThreadPlan called with empty thread plan.");
4758 return eExpressionSetupError;
4759 }
4760
4761 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004762 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004763 eDiagnosticSeverityError,
4764 "RunThreadPlan called with an invalid thread plan.");
4765 return eExpressionSetupError;
4766 }
4767
4768 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004769 diagnostic_manager.PutString(eDiagnosticSeverityError,
4770 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004771 return eExpressionSetupError;
4772 }
4773
4774 Thread *thread = exe_ctx.GetThreadPtr();
4775 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004776 diagnostic_manager.PutString(eDiagnosticSeverityError,
4777 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004778 return eExpressionSetupError;
4779 }
4780
Jim Inghamdbbed972020-05-20 18:00:56 -07004781 // Record the thread's id so we can tell when a thread we were using
4782 // to run the expression exits during the expression evaluation.
4783 lldb::tid_t expr_thread_id = thread->GetID();
4784
Kate Stoneb9c1b512016-09-06 20:57:50 +00004785 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004786 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004787
4788 RestorePlanState thread_plan_restorer(thread_plan_sp);
4789
Adrian Prantl05097242018-04-30 16:49:04 +00004790 // We rely on the thread plan we are running returning "PlanCompleted" if
4791 // when it successfully completes. For that to be true the plan can't be
4792 // private - since private plans suppress themselves in the GetCompletedPlan
4793 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004794
4795 thread_plan_sp->SetPrivate(false);
4796
4797 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004798 // when they are done we will end up asking the plan above us whether we
4799 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004800
4801 thread_plan_sp->SetIsMasterPlan(true);
4802 thread_plan_sp->SetOkayToDiscard(false);
4803
Raphael Isemannc01783a2018-08-29 22:50:54 +00004804 // If we are running some utility expression for LLDB, we now have to mark
4805 // this in the ProcesModID of this process. This RAII takes care of marking
4806 // and reverting the mark it once we are done running the expression.
4807 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4808
Kate Stoneb9c1b512016-09-06 20:57:50 +00004809 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004810 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004811 eDiagnosticSeverityError,
4812 "RunThreadPlan called while the private state was not stopped.");
4813 return eExpressionSetupError;
4814 }
4815
4816 // Save the thread & frame from the exe_ctx for restoration after we run
4817 const uint32_t thread_idx_id = thread->GetIndexID();
4818 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4819 if (!selected_frame_sp) {
4820 thread->SetSelectedFrame(nullptr);
4821 selected_frame_sp = thread->GetSelectedFrame();
4822 if (!selected_frame_sp) {
4823 diagnostic_manager.Printf(
4824 eDiagnosticSeverityError,
4825 "RunThreadPlan called without a selected frame on thread %d",
4826 thread_idx_id);
4827 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004828 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004829 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004830
Adrian Prantl05097242018-04-30 16:49:04 +00004831 // Make sure the timeout values make sense. The one thread timeout needs to
4832 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004833 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4834 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004835 diagnostic_manager.PutString(eDiagnosticSeverityError,
4836 "RunThreadPlan called with one thread "
4837 "timeout greater than total timeout");
4838 return eExpressionSetupError;
4839 }
4840
Kate Stoneb9c1b512016-09-06 20:57:50 +00004841 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004842
Kate Stoneb9c1b512016-09-06 20:57:50 +00004843 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004844 // We don't want to do that either, so we should arrange to reset them as
4845 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004846
Kate Stoneb9c1b512016-09-06 20:57:50 +00004847 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004848
Kate Stoneb9c1b512016-09-06 20:57:50 +00004849 uint32_t selected_tid;
4850 StackID selected_stack_id;
4851 if (selected_thread_sp) {
4852 selected_tid = selected_thread_sp->GetIndexID();
4853 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4854 } else {
4855 selected_tid = LLDB_INVALID_THREAD_ID;
4856 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004857
Kate Stoneb9c1b512016-09-06 20:57:50 +00004858 HostThread backup_private_state_thread;
4859 lldb::StateType old_state = eStateInvalid;
4860 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004861
Kate Stoneb9c1b512016-09-06 20:57:50 +00004862 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4863 LIBLLDB_LOG_PROCESS));
4864 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4865 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004866 // public events on this thread, since we are the thread that is generating
4867 // public events. The simplest thing to do is to spin up a temporary thread
4868 // to handle private state thread events while we are fielding public
4869 // events here.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004870 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4871 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004872
Kate Stoneb9c1b512016-09-06 20:57:50 +00004873 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004874
Kate Stoneb9c1b512016-09-06 20:57:50 +00004875 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004876 // anything it pushes, and then stop, returning control here. But in the
4877 // normal course of things, the plan above us on the stack would be given a
4878 // shot at the stop event before deciding to stop, and we don't want that.
4879 // So we insert a "stopper" base plan on the stack before the plan we want
4880 // to run. Since base plans always stop and return control to the user,
4881 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004882 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4883 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4884 // Have to make sure our public state is stopped, since otherwise the
4885 // reporting logic below doesn't work correctly.
4886 old_state = m_public_state.GetValue();
4887 m_public_state.SetValueNoLock(eStateStopped);
4888
4889 // Now spin up the private state thread:
4890 StartPrivateStateThread(true);
4891 }
4892
4893 thread->QueueThreadPlan(
4894 thread_plan_sp, false); // This used to pass "true" does that make sense?
4895
4896 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004897 // In this case, we aren't actually going to run, we just want to stop
4898 // right away. Flush this thread so we will refetch the stacks and show the
4899 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004900 // FIXME: To make this prettier we should invent some stop reason for this,
4901 // but that
4902 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004903 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004904 thread->Flush();
4905 return eExpressionStoppedForDebug;
4906 }
4907
4908 ListenerSP listener_sp(
4909 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4910
4911 lldb::EventSP event_to_broadcast_sp;
4912
4913 {
4914 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004915 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004916 //
4917 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004918 // exits during execution), then the event is put into
4919 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004920
4921 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4922
4923 if (log) {
4924 StreamString s;
4925 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004926 LLDB_LOGF(log,
4927 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4928 " to run thread plan \"%s\".",
Jim Inghamdbbed972020-05-20 18:00:56 -07004929 thread_idx_id, expr_thread_id, s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004930 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004931
4932 bool got_event;
4933 lldb::EventSP event_sp;
4934 lldb::StateType stop_state = lldb::eStateInvalid;
4935
4936 bool before_first_timeout = true; // This is set to false the first time
4937 // that we have to halt the target.
4938 bool do_resume = true;
4939 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004940
4941 // This is just for accounting:
4942 uint32_t num_resumes = 0;
4943
Kate Stoneb9c1b512016-09-06 20:57:50 +00004944 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00004945 // going to run one thread, then we don't need the first timeout. So we
4946 // pretend we are after the first timeout already.
4947 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004948 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00004949
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004950 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4951 options.GetStopOthers(), options.GetTryAllThreads(),
4952 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004953
Adrian Prantl05097242018-04-30 16:49:04 +00004954 // This isn't going to work if there are unfetched events on the queue. Are
4955 // there cases where we might want to run the remaining events here, and
4956 // then try to call the function? That's probably being too tricky for our
4957 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004958
4959 Event *other_events = listener_sp->PeekAtNextEvent();
4960 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004961 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004962 eDiagnosticSeverityError,
4963 "RunThreadPlan called with pending events on the queue.");
4964 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00004965 }
4966
Kate Stoneb9c1b512016-09-06 20:57:50 +00004967 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00004968 // calling a function as part of a thread plan, in which case the last
4969 // delivered event could be the running event, and we don't want event
4970 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004971 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00004972
Kate Stoneb9c1b512016-09-06 20:57:50 +00004973// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00004974// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00004975
Kate Stoneb9c1b512016-09-06 20:57:50 +00004976#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00004977 // It's pretty much impossible to write test cases for things like: One
4978 // thread timeout expires, I go to halt, but the process already stopped on
4979 // the function call stop breakpoint. Turning on this define will make us
4980 // not fetch the first event till after the halt. So if you run a quick
4981 // function, it will have completed, and the completion event will be
4982 // waiting, when you interrupt for halt. The expression evaluation should
4983 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004984 bool miss_first_event = true;
4985#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00004986 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00004987 // We usually want to resume the process if we get to the top of the
4988 // loop. The only exception is if we get two running events with no
4989 // intervening stop, which can happen, we will just wait for then next
4990 // stop event.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004991 LLDB_LOGF(log,
4992 "Top of while loop: do_resume: %i handle_running_event: %i "
4993 "before_first_timeout: %i.",
4994 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00004995
Kate Stoneb9c1b512016-09-06 20:57:50 +00004996 if (do_resume || handle_running_event) {
4997 // Do the initial resume and wait for the running event before going
4998 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00004999
Kate Stoneb9c1b512016-09-06 20:57:50 +00005000 if (do_resume) {
5001 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00005002 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005003 if (!resume_error.Success()) {
5004 diagnostic_manager.Printf(
5005 eDiagnosticSeverityError,
5006 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5007 resume_error.AsCString());
5008 return_value = eExpressionSetupError;
5009 break;
5010 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005011 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005012
Pavel Labathd35031e12016-11-30 10:41:42 +00005013 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00005014 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005015 if (!got_event) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005016 LLDB_LOGF(log,
5017 "Process::RunThreadPlan(): didn't get any event after "
5018 "resume %" PRIu32 ", exiting.",
5019 num_resumes);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005020
5021 diagnostic_manager.Printf(eDiagnosticSeverityError,
5022 "didn't get any event after resume %" PRIu32
5023 ", exiting.",
5024 num_resumes);
5025 return_value = eExpressionSetupError;
5026 break;
5027 }
5028
5029 stop_state =
5030 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5031
5032 if (stop_state != eStateRunning) {
5033 bool restarted = false;
5034
5035 if (stop_state == eStateStopped) {
5036 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5037 event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005038 LLDB_LOGF(
5039 log,
5040 "Process::RunThreadPlan(): didn't get running event after "
5041 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5042 "handle_running_event: %i).",
5043 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5044 handle_running_event);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005045 }
5046
5047 if (restarted) {
5048 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00005049 // should ever get a stopped & restarted event here. But if I do,
5050 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005051 const bool clear_thread_plans = false;
5052 const bool use_run_lock = false;
5053 Halt(clear_thread_plans, use_run_lock);
5054 }
5055
5056 diagnostic_manager.Printf(
5057 eDiagnosticSeverityError,
5058 "didn't get running event after initial resume, got %s instead.",
5059 StateAsCString(stop_state));
5060 return_value = eExpressionSetupError;
5061 break;
5062 }
5063
5064 if (log)
5065 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00005066 // We need to call the function synchronously, so spin waiting for it
5067 // to return. If we get interrupted while executing, we're going to
5068 // lose our context, and won't be able to gather the result at this
5069 // point. We set the timeout AFTER the resume, since the resume takes
5070 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005071 } else {
5072 if (log)
5073 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5074 }
5075
Kate Stoneb9c1b512016-09-06 20:57:50 +00005076 do_resume = true;
5077 handle_running_event = true;
5078
5079 // Now wait for the process to stop again:
5080 event_sp.reset();
5081
Pavel Labath2ce22162016-12-01 10:57:30 +00005082 Timeout<std::micro> timeout =
5083 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005084 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005085 if (timeout) {
5086 auto now = system_clock::now();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005087 LLDB_LOGF(log,
5088 "Process::RunThreadPlan(): about to wait - now is %s - "
5089 "endpoint is %s",
5090 llvm::to_string(now).c_str(),
5091 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005092 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005093 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005094 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005095 }
5096
5097#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5098 // See comment above...
5099 if (miss_first_event) {
Pavel Labath3d4f7652019-08-05 08:23:25 +00005100 std::this_thread::sleep_for(std::chrono::milliseconds(1));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005101 miss_first_event = false;
5102 got_event = false;
5103 } else
5104#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005105 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005106
5107 if (got_event) {
5108 if (event_sp) {
5109 bool keep_going = false;
5110 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5111 const bool clear_thread_plans = false;
5112 const bool use_run_lock = false;
5113 Halt(clear_thread_plans, use_run_lock);
5114 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005115 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5116 "execution halted by user interrupt.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005117 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
5118 "eBroadcastBitInterrupted, exiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005119 break;
5120 } else {
5121 stop_state =
5122 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005123 LLDB_LOGF(log,
5124 "Process::RunThreadPlan(): in while loop, got event: %s.",
5125 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005126
5127 switch (stop_state) {
5128 case lldb::eStateStopped: {
Jim Inghamdbbed972020-05-20 18:00:56 -07005129 if (Process::ProcessEventData::GetRestartedFromEvent(
5130 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005131 // If we were restarted, we just need to go back up to fetch
5132 // another event.
Jim Inghamdbbed972020-05-20 18:00:56 -07005133 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5134 "restart, so we'll continue waiting.");
Pavel Labath45dde232017-05-25 10:50:06 +00005135 keep_going = true;
5136 do_resume = false;
5137 handle_running_event = true;
5138 } else {
5139 const bool handle_interrupts = true;
5140 return_value = *HandleStoppedEvent(
Jim Inghamdbbed972020-05-20 18:00:56 -07005141 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5142 event_sp, event_to_broadcast_sp, options,
5143 handle_interrupts);
5144 if (return_value == eExpressionThreadVanished)
5145 keep_going = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005146 }
5147 } break;
5148
5149 case lldb::eStateRunning:
5150 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005151 // running events without an intervening stop, and in that case
5152 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005153 do_resume = false;
5154 keep_going = true;
5155 handle_running_event = false;
5156 break;
5157
5158 default:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005159 LLDB_LOGF(log,
5160 "Process::RunThreadPlan(): execution stopped with "
5161 "unexpected state: %s.",
5162 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005163
5164 if (stop_state == eStateExited)
5165 event_to_broadcast_sp = event_sp;
5166
Zachary Turnere2411fa2016-11-12 19:12:56 +00005167 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005168 eDiagnosticSeverityError,
5169 "execution stopped with unexpected state.");
5170 return_value = eExpressionInterrupted;
5171 break;
5172 }
5173 }
5174
5175 if (keep_going)
5176 continue;
5177 else
5178 break;
5179 } else {
5180 if (log)
5181 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5182 "the event pointer was null. How odd...");
5183 return_value = eExpressionInterrupted;
5184 break;
5185 }
5186 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005187 // If we didn't get an event that means we've timed out... We will
5188 // interrupt the process here. Depending on what we were asked to do
5189 // we will either exit, or try with all threads running for the same
5190 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005191
5192 if (log) {
5193 if (options.GetTryAllThreads()) {
5194 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005195 LLDB_LOG(log,
5196 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005197 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005198 LLDB_LOG(log, "Restarting function with all threads enabled and "
5199 "timeout: {0} timed out, abandoning execution.",
5200 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005201 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005202 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5203 "abandoning execution.",
5204 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005205 }
5206
5207 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005208 // around to calling Halt the target could have stopped. That's fine,
5209 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005210 // BUT it is also possible that we stopped & restarted (e.g. hit a
5211 // signal with "stop" set to false.) In
5212 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005213 // back to waiting for the Halt's stopped event. That's what this
5214 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005215
5216 bool back_to_top = true;
5217 uint32_t try_halt_again = 0;
5218 bool do_halt = true;
5219 const uint32_t num_retries = 5;
5220 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005221 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005222 if (do_halt) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005223 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005224 const bool clear_thread_plans = false;
5225 const bool use_run_lock = false;
5226 Halt(clear_thread_plans, use_run_lock);
5227 }
5228 if (halt_error.Success()) {
5229 if (log)
5230 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5231
Pavel Labathd35031e12016-11-30 10:41:42 +00005232 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00005233 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005234
5235 if (got_event) {
5236 stop_state =
5237 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5238 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005239 LLDB_LOGF(log,
5240 "Process::RunThreadPlan(): Stopped with event: %s",
5241 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005242 if (stop_state == lldb::eStateStopped &&
5243 Process::ProcessEventData::GetInterruptedFromEvent(
5244 event_sp.get()))
5245 log->PutCString(" Event was the Halt interruption event.");
5246 }
5247
5248 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005249 if (Process::ProcessEventData::GetRestartedFromEvent(
5250 event_sp.get())) {
5251 if (log)
5252 log->PutCString("Process::RunThreadPlan(): Went to halt "
5253 "but got a restarted event, there must be "
5254 "an un-restarted stopped event so try "
5255 "again... "
5256 "Exiting wait loop.");
5257 try_halt_again++;
5258 do_halt = false;
5259 continue;
5260 }
5261
Pavel Labath45dde232017-05-25 10:50:06 +00005262 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005263 // delivered it, the process could have already finished its
5264 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005265 const bool handle_interrupts = false;
5266 if (auto result = HandleStoppedEvent(
Jim Inghamdbbed972020-05-20 18:00:56 -07005267 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5268 event_sp, event_to_broadcast_sp, options,
5269 handle_interrupts)) {
Pavel Labath45dde232017-05-25 10:50:06 +00005270 return_value = *result;
5271 back_to_top = false;
5272 break;
5273 }
5274
Kate Stoneb9c1b512016-09-06 20:57:50 +00005275 if (!options.GetTryAllThreads()) {
5276 if (log)
5277 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5278 "was false, we stopped so now we're "
5279 "quitting.");
5280 return_value = eExpressionInterrupted;
5281 back_to_top = false;
5282 break;
5283 }
5284
5285 if (before_first_timeout) {
5286 // Set all the other threads to run, and return to the top of
5287 // the loop, which will continue;
5288 before_first_timeout = false;
5289 thread_plan_sp->SetStopOthers(false);
5290 if (log)
5291 log->PutCString(
5292 "Process::RunThreadPlan(): about to resume.");
5293
5294 back_to_top = true;
5295 break;
5296 } else {
5297 // Running all threads failed, so return Interrupted.
5298 if (log)
5299 log->PutCString("Process::RunThreadPlan(): running all "
5300 "threads timed out.");
5301 return_value = eExpressionInterrupted;
5302 back_to_top = false;
5303 break;
5304 }
5305 }
5306 } else {
5307 if (log)
5308 log->PutCString("Process::RunThreadPlan(): halt said it "
5309 "succeeded, but I got no event. "
5310 "I'm getting out of here passing Interrupted.");
5311 return_value = eExpressionInterrupted;
5312 back_to_top = false;
5313 break;
5314 }
5315 } else {
5316 try_halt_again++;
5317 continue;
5318 }
5319 }
5320
5321 if (!back_to_top || try_halt_again > num_retries)
5322 break;
5323 else
5324 continue;
5325 }
5326 } // END WAIT LOOP
5327
Adrian Prantl05097242018-04-30 16:49:04 +00005328 // If we had to start up a temporary private state thread to run this
5329 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005330 if (backup_private_state_thread.IsJoinable()) {
5331 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005332 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005333 m_private_state_thread = backup_private_state_thread;
5334 if (stopper_base_plan_sp) {
5335 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5336 }
5337 if (old_state != eStateInvalid)
5338 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005339 }
5340
Jim Inghamdbbed972020-05-20 18:00:56 -07005341 // If our thread went away on us, we need to get out of here without
5342 // doing any more work. We don't have to clean up the thread plan, that
5343 // will have happened when the Thread was destroyed.
5344 if (return_value == eExpressionThreadVanished) {
5345 return return_value;
5346 }
5347
Kate Stoneb9c1b512016-09-06 20:57:50 +00005348 if (return_value != eExpressionCompleted && log) {
5349 // Print a backtrace into the log so we can figure out where we are:
5350 StreamString s;
5351 s.PutCString("Thread state after unsuccessful completion: \n");
5352 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005353 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005354 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005355 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005356 // There are three cases where this could happen: 1) The execution
5357 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5358 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005359 bool should_unwind = (return_value == eExpressionInterrupted &&
5360 options.DoesUnwindOnError()) ||
5361 (return_value == eExpressionHitBreakpoint &&
5362 options.DoesIgnoreBreakpoints());
5363
5364 if (return_value == eExpressionCompleted || should_unwind) {
5365 thread_plan_sp->RestoreThreadState();
5366 }
5367
5368 // Now do some processing on the results of the run:
5369 if (return_value == eExpressionInterrupted ||
5370 return_value == eExpressionHitBreakpoint) {
5371 if (log) {
5372 StreamString s;
5373 if (event_sp)
5374 event_sp->Dump(&s);
5375 else {
5376 log->PutCString("Process::RunThreadPlan(): Stop event that "
5377 "interrupted us is NULL.");
5378 }
5379
5380 StreamString ts;
5381
5382 const char *event_explanation = nullptr;
5383
5384 do {
5385 if (!event_sp) {
5386 event_explanation = "<no event>";
5387 break;
5388 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5389 event_explanation = "<user interrupt>";
5390 break;
5391 } else {
5392 const Process::ProcessEventData *event_data =
5393 Process::ProcessEventData::GetEventDataFromEvent(
5394 event_sp.get());
5395
5396 if (!event_data) {
5397 event_explanation = "<no event data>";
5398 break;
5399 }
5400
5401 Process *process = event_data->GetProcessSP().get();
5402
5403 if (!process) {
5404 event_explanation = "<no process>";
5405 break;
5406 }
5407
5408 ThreadList &thread_list = process->GetThreadList();
5409
5410 uint32_t num_threads = thread_list.GetSize();
5411 uint32_t thread_index;
5412
5413 ts.Printf("<%u threads> ", num_threads);
5414
5415 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5416 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5417
5418 if (!thread) {
5419 ts.Printf("<?> ");
5420 continue;
5421 }
5422
5423 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5424 RegisterContext *register_context =
5425 thread->GetRegisterContext().get();
5426
5427 if (register_context)
5428 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5429 else
5430 ts.Printf("[ip unknown] ");
5431
5432 // Show the private stop info here, the public stop info will be
5433 // from the last natural stop.
5434 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5435 if (stop_info_sp) {
5436 const char *stop_desc = stop_info_sp->GetDescription();
5437 if (stop_desc)
5438 ts.PutCString(stop_desc);
5439 }
5440 ts.Printf(">");
5441 }
5442
5443 event_explanation = ts.GetData();
5444 }
Jonas Devlieghere09ad8c82019-05-24 00:44:33 +00005445 } while (false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005446
5447 if (event_explanation)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005448 LLDB_LOGF(log,
5449 "Process::RunThreadPlan(): execution interrupted: %s %s",
5450 s.GetData(), event_explanation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005451 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005452 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
5453 s.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005454 }
5455
5456 if (should_unwind) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005457 LLDB_LOGF(log,
5458 "Process::RunThreadPlan: ExecutionInterrupted - "
5459 "discarding thread plans up to %p.",
5460 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005461 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5462 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005463 LLDB_LOGF(log,
5464 "Process::RunThreadPlan: ExecutionInterrupted - for "
5465 "plan: %p not discarding.",
5466 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005467 }
5468 } else if (return_value == eExpressionSetupError) {
5469 if (log)
5470 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5471
5472 if (options.DoesUnwindOnError()) {
5473 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5474 }
5475 } else {
5476 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5477 if (log)
5478 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5479 return_value = eExpressionCompleted;
5480 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5481 if (log)
5482 log->PutCString(
5483 "Process::RunThreadPlan(): thread plan was discarded");
5484 return_value = eExpressionDiscarded;
5485 } else {
5486 if (log)
5487 log->PutCString(
5488 "Process::RunThreadPlan(): thread plan stopped in mid course");
5489 if (options.DoesUnwindOnError() && thread_plan_sp) {
5490 if (log)
5491 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5492 "'cause unwind_on_error is set.");
5493 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5494 }
5495 }
5496 }
5497
5498 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005499 // target Check that it's still there, and if it is put it back in the
5500 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005501 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5502 if (thread) {
5503 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5504 }
5505
5506 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005507 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005508
5509 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5510 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5511 selected_stack_id.IsValid()) {
5512 // We were able to restore the selected thread, now restore the frame:
5513 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5514 StackFrameSP old_frame_sp =
5515 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5516 selected_stack_id);
5517 if (old_frame_sp)
5518 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5519 old_frame_sp.get());
5520 }
5521 }
5522 }
5523
5524 // If the process exited during the run of the thread plan, notify everyone.
5525
5526 if (event_to_broadcast_sp) {
5527 if (log)
5528 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5529 BroadcastEvent(event_to_broadcast_sp);
5530 }
5531
5532 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005533}
5534
Kate Stoneb9c1b512016-09-06 20:57:50 +00005535const char *Process::ExecutionResultAsCString(ExpressionResults result) {
Jim Inghamdbbed972020-05-20 18:00:56 -07005536 const char *result_name = "<unknown>";
Kate Stoneb9c1b512016-09-06 20:57:50 +00005537
5538 switch (result) {
5539 case eExpressionCompleted:
5540 result_name = "eExpressionCompleted";
5541 break;
5542 case eExpressionDiscarded:
5543 result_name = "eExpressionDiscarded";
5544 break;
5545 case eExpressionInterrupted:
5546 result_name = "eExpressionInterrupted";
5547 break;
5548 case eExpressionHitBreakpoint:
5549 result_name = "eExpressionHitBreakpoint";
5550 break;
5551 case eExpressionSetupError:
5552 result_name = "eExpressionSetupError";
5553 break;
5554 case eExpressionParseError:
5555 result_name = "eExpressionParseError";
5556 break;
5557 case eExpressionResultUnavailable:
5558 result_name = "eExpressionResultUnavailable";
5559 break;
5560 case eExpressionTimedOut:
5561 result_name = "eExpressionTimedOut";
5562 break;
5563 case eExpressionStoppedForDebug:
5564 result_name = "eExpressionStoppedForDebug";
5565 break;
Jim Inghamdbbed972020-05-20 18:00:56 -07005566 case eExpressionThreadVanished:
5567 result_name = "eExpressionThreadVanished";
Kate Stoneb9c1b512016-09-06 20:57:50 +00005568 }
5569 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005570}
5571
Kate Stoneb9c1b512016-09-06 20:57:50 +00005572void Process::GetStatus(Stream &strm) {
5573 const StateType state = GetState();
5574 if (StateIsStoppedState(state, false)) {
5575 if (state == eStateExited) {
5576 int exit_status = GetExitStatus();
5577 const char *exit_description = GetExitDescription();
5578 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5579 GetID(), exit_status, exit_status,
5580 exit_description ? exit_description : "");
5581 } else {
5582 if (state == eStateConnected)
5583 strm.Printf("Connected to remote target.\n");
5584 else
5585 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5586 }
5587 } else {
5588 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5589 }
Pavel Labatha933d512016-04-05 13:07:16 +00005590}
5591
Kate Stoneb9c1b512016-09-06 20:57:50 +00005592size_t Process::GetThreadStatus(Stream &strm,
5593 bool only_threads_with_stop_reason,
5594 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005595 uint32_t num_frames_with_source,
5596 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005597 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005598
Kate Stoneb9c1b512016-09-06 20:57:50 +00005599 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005600 // very well might run code (e.g. if we need it to get return values or
5601 // arguments.) For that to work the process has to be able to acquire it.
5602 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005603
5604 uint32_t num_threads;
5605 std::vector<lldb::tid_t> thread_id_array;
5606 // Scope for thread list locker;
5607 {
5608 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5609 ThreadList &curr_thread_list = GetThreadList();
5610 num_threads = curr_thread_list.GetSize();
5611 uint32_t idx;
5612 thread_id_array.resize(num_threads);
5613 for (idx = 0; idx < num_threads; ++idx)
5614 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5615 }
5616
5617 for (uint32_t i = 0; i < num_threads; i++) {
5618 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5619 if (thread_sp) {
5620 if (only_threads_with_stop_reason) {
5621 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5622 if (!stop_info_sp || !stop_info_sp->IsValid())
5623 continue;
5624 }
5625 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005626 num_frames_with_source,
5627 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005628 ++num_thread_infos_dumped;
5629 } else {
5630 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005631 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
5632 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005633 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005634 }
5635 return num_thread_infos_dumped;
5636}
5637
5638void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5639 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5640}
5641
5642bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5643 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5644 region.GetByteSize());
5645}
5646
5647void Process::AddPreResumeAction(PreResumeActionCallback callback,
5648 void *baton) {
5649 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5650}
5651
5652bool Process::RunPreResumeActions() {
5653 bool result = true;
5654 while (!m_pre_resume_actions.empty()) {
5655 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5656 m_pre_resume_actions.pop_back();
5657 bool this_result = action.callback(action.baton);
5658 if (result)
5659 result = this_result;
5660 }
5661 return result;
5662}
5663
5664void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5665
Jim Inghamffd91752016-10-20 22:50:00 +00005666void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5667{
5668 PreResumeCallbackAndBaton element(callback, baton);
5669 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5670 if (found_iter != m_pre_resume_actions.end())
5671 {
5672 m_pre_resume_actions.erase(found_iter);
5673 }
5674}
5675
Kate Stoneb9c1b512016-09-06 20:57:50 +00005676ProcessRunLock &Process::GetRunLock() {
5677 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5678 return m_private_run_lock;
5679 else
5680 return m_public_run_lock;
5681}
5682
Jim Ingham58c3235e2019-10-01 00:47:25 +00005683bool Process::CurrentThreadIsPrivateStateThread()
5684{
5685 return m_private_state_thread.EqualsThread(Host::GetCurrentThread());
5686}
5687
5688
Kate Stoneb9c1b512016-09-06 20:57:50 +00005689void Process::Flush() {
5690 m_thread_list.Flush();
5691 m_extended_thread_list.Flush();
5692 m_extended_thread_stop_id = 0;
5693 m_queue_list.Clear();
5694 m_queue_list_stop_id = 0;
5695}
5696
5697void Process::DidExec() {
5698 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005699 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005700
5701 Target &target = GetTarget();
5702 target.CleanupProcess();
5703 target.ClearModules(false);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005704 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005705 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005706 m_system_runtime_up.reset();
5707 m_os_up.reset();
5708 m_dyld_up.reset();
5709 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005710 m_image_tokens.clear();
5711 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +00005712 {
5713 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5714 m_language_runtimes.clear();
5715 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005716 m_instrumentation_runtimes.clear();
5717 m_thread_list.DiscardThreadPlans();
5718 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005719 DoDidExec();
5720 CompleteAttach();
5721 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005722 // CompleteAttach() in case the dynamic loader loaded things in new
5723 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005724 Flush();
5725
Adrian Prantl05097242018-04-30 16:49:04 +00005726 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5727 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005728 target.DidExec();
5729}
5730
Zachary Turner97206d52017-05-12 04:51:55 +00005731addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005732 if (address == nullptr) {
5733 error.SetErrorString("Invalid address argument");
5734 return LLDB_INVALID_ADDRESS;
5735 }
5736
5737 addr_t function_addr = LLDB_INVALID_ADDRESS;
5738
5739 addr_t addr = address->GetLoadAddress(&GetTarget());
5740 std::map<addr_t, addr_t>::const_iterator iter =
5741 m_resolved_indirect_addresses.find(addr);
5742 if (iter != m_resolved_indirect_addresses.end()) {
5743 function_addr = (*iter).second;
5744 } else {
Alex Langford5b2b38e2019-09-13 00:02:05 +00005745 if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005746 Symbol *symbol = address->CalculateSymbolContextSymbol();
5747 error.SetErrorStringWithFormat(
5748 "Unable to call resolver for indirect function %s",
5749 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5750 function_addr = LLDB_INVALID_ADDRESS;
5751 } else {
5752 m_resolved_indirect_addresses.insert(
5753 std::pair<addr_t, addr_t>(addr, function_addr));
5754 }
5755 }
5756 return function_addr;
5757}
5758
5759void Process::ModulesDidLoad(ModuleList &module_list) {
5760 SystemRuntime *sys_runtime = GetSystemRuntime();
5761 if (sys_runtime) {
5762 sys_runtime->ModulesDidLoad(module_list);
5763 }
5764
5765 GetJITLoaders().ModulesDidLoad(module_list);
5766
5767 // Give runtimes a chance to be created.
5768 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5769 m_instrumentation_runtimes);
5770
5771 // Tell runtimes about new modules.
5772 for (auto pos = m_instrumentation_runtimes.begin();
5773 pos != m_instrumentation_runtimes.end(); ++pos) {
5774 InstrumentationRuntimeSP runtime = pos->second;
5775 runtime->ModulesDidLoad(module_list);
5776 }
5777
Adrian Prantl05097242018-04-30 16:49:04 +00005778 // Let any language runtimes we have already created know about the modules
5779 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005780
Adrian Prantl05097242018-04-30 16:49:04 +00005781 // Iterate over a copy of this language runtime list in case the language
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005782 // runtime ModulesDidLoad somehow causes the language runtime to be
Adrian Prantl05097242018-04-30 16:49:04 +00005783 // unloaded.
Alex Langford74eb76f2019-05-22 23:01:18 +00005784 {
5785 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5786 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5787 for (const auto &pair : language_runtimes) {
5788 // We must check language_runtime_sp to make sure it is not nullptr as we
5789 // might cache the fact that we didn't have a language runtime for a
5790 // language.
5791 LanguageRuntimeSP language_runtime_sp = pair.second;
5792 if (language_runtime_sp)
5793 language_runtime_sp->ModulesDidLoad(module_list);
5794 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005795 }
5796
5797 // If we don't have an operating system plug-in, try to load one since
5798 // loading shared libraries might cause a new one to try and load
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005799 if (!m_os_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005800 LoadOperatingSystemPlugin(false);
5801
5802 // Give structured-data plugins a chance to see the modified modules.
5803 for (auto pair : m_structured_data_plugin_map) {
5804 if (pair.second)
5805 pair.second->ModulesDidLoad(*this, module_list);
5806 }
5807}
5808
5809void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5810 const char *fmt, ...) {
5811 bool print_warning = true;
5812
5813 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5814 if (!stream_sp)
5815 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005816
5817 if (repeat_key != nullptr) {
5818 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5819 if (it == m_warnings_issued.end()) {
5820 m_warnings_issued[warning_type] = WarningsPointerSet();
5821 m_warnings_issued[warning_type].insert(repeat_key);
5822 } else {
5823 if (it->second.find(repeat_key) != it->second.end()) {
5824 print_warning = false;
5825 } else {
5826 it->second.insert(repeat_key);
5827 }
5828 }
5829 }
5830
5831 if (print_warning) {
5832 va_list args;
5833 va_start(args, fmt);
5834 stream_sp->PrintfVarArg(fmt, args);
5835 va_end(args);
5836 }
5837}
5838
5839void Process::PrintWarningOptimization(const SymbolContext &sc) {
Adrian Prantl220c17f2020-05-21 17:42:24 -07005840 if (!GetWarningsOptimization())
5841 return;
5842 if (!sc.module_sp)
5843 return;
5844 if (!sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
Kate Stoneb9c1b512016-09-06 20:57:50 +00005845 sc.function->GetIsOptimized()) {
5846 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5847 "%s was compiled with optimization - stepping may behave "
5848 "oddly; variables may not be available.\n",
5849 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5850 }
5851}
5852
Adrian Prantl220c17f2020-05-21 17:42:24 -07005853void Process::PrintWarningUnsupportedLanguage(const SymbolContext &sc) {
5854 if (!GetWarningsUnsupportedLanguage())
5855 return;
5856 if (!sc.module_sp)
5857 return;
5858 LanguageType language = sc.GetLanguage();
5859 if (language == eLanguageTypeUnknown)
5860 return;
5861 auto type_system_or_err = sc.module_sp->GetTypeSystemForLanguage(language);
5862 if (auto err = type_system_or_err.takeError()) {
5863 llvm::consumeError(std::move(err));
5864 PrintWarning(Process::Warnings::eWarningsUnsupportedLanguage,
5865 sc.module_sp.get(),
5866 "This version of LLDB has no plugin for the %s language. "
5867 "Inspection of frame variables will be limited.\n",
5868 Language::GetNameForLanguageType(language));
5869 }
5870}
5871
Kate Stoneb9c1b512016-09-06 20:57:50 +00005872bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5873 info.Clear();
5874
5875 PlatformSP platform_sp = GetTarget().GetPlatform();
5876 if (!platform_sp)
5877 return false;
5878
5879 return platform_sp->GetProcessInfo(GetID(), info);
5880}
5881
5882ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5883 ThreadCollectionSP threads;
5884
5885 const MemoryHistorySP &memory_history =
5886 MemoryHistory::FindPlugin(shared_from_this());
5887
5888 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005889 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005890 }
5891
Jonas Devlieghere796ac802019-02-11 23:13:08 +00005892 threads = std::make_shared<ThreadCollection>(
5893 memory_history->GetHistoryThreads(addr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005894
5895 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005896}
Kuba Brecka63927542014-10-11 01:59:32 +00005897
5898InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005899Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5900 InstrumentationRuntimeCollection::iterator pos;
5901 pos = m_instrumentation_runtimes.find(type);
5902 if (pos == m_instrumentation_runtimes.end()) {
5903 return InstrumentationRuntimeSP();
5904 } else
5905 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005906}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005907
Kate Stoneb9c1b512016-09-06 20:57:50 +00005908bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5909 const ArchSpec &arch, ModuleSpec &module_spec) {
5910 module_spec.Clear();
5911 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005912}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005913
Kate Stoneb9c1b512016-09-06 20:57:50 +00005914size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5915 m_image_tokens.push_back(image_ptr);
5916 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005917}
5918
Kate Stoneb9c1b512016-09-06 20:57:50 +00005919lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5920 if (token < m_image_tokens.size())
5921 return m_image_tokens[token];
Saleem Abdulrasool3775be22020-04-06 17:33:38 -07005922 return LLDB_INVALID_ADDRESS;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005923}
5924
Kate Stoneb9c1b512016-09-06 20:57:50 +00005925void Process::ResetImageToken(size_t token) {
5926 if (token < m_image_tokens.size())
Saleem Abdulrasool3775be22020-04-06 17:33:38 -07005927 m_image_tokens[token] = LLDB_INVALID_ADDRESS;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005928}
Jason Molendafd4cea52016-01-08 21:40:11 +00005929
5930Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005931Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5932 AddressRange range_bounds) {
5933 Target &target = GetTarget();
5934 DisassemblerSP disassembler_sp;
5935 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005936
Kate Stoneb9c1b512016-09-06 20:57:50 +00005937 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005938
Kate Stoneb9c1b512016-09-06 20:57:50 +00005939 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005940 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005941 if (!default_stop_addr.IsValid())
5942 return retval;
5943
Kate Stoneb9c1b512016-09-06 20:57:50 +00005944 const char *plugin_name = nullptr;
5945 const char *flavor = nullptr;
5946 const bool prefer_file_cache = true;
5947 disassembler_sp = Disassembler::DisassembleRange(
Pavel Labath04592d52020-03-05 13:03:26 +01005948 target.GetArchitecture(), plugin_name, flavor, GetTarget(), range_bounds,
Kate Stoneb9c1b512016-09-06 20:57:50 +00005949 prefer_file_cache);
5950 if (disassembler_sp)
5951 insn_list = &disassembler_sp->GetInstructionList();
5952
5953 if (insn_list == nullptr) {
5954 return retval;
5955 }
5956
5957 size_t insn_offset =
5958 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5959 if (insn_offset == UINT32_MAX) {
5960 return retval;
5961 }
5962
5963 uint32_t branch_index =
Greg Claytondf225762019-05-09 20:39:34 +00005964 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target,
Jim Ingham434905b2019-12-16 17:38:13 -08005965 false /* ignore_calls*/,
5966 nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005967 if (branch_index == UINT32_MAX) {
5968 return retval;
5969 }
5970
5971 if (branch_index > insn_offset) {
5972 Address next_branch_insn_address =
5973 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5974 if (next_branch_insn_address.IsValid() &&
5975 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5976 retval = next_branch_insn_address;
5977 }
5978 }
5979
5980 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00005981}
Howard Hellyerad007562016-07-07 08:21:28 +00005982
Zachary Turner97206d52017-05-12 04:51:55 +00005983Status
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005984Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00005985
Zachary Turner97206d52017-05-12 04:51:55 +00005986 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00005987
Kate Stoneb9c1b512016-09-06 20:57:50 +00005988 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00005989
Kate Stoneb9c1b512016-09-06 20:57:50 +00005990 region_list.clear();
5991 do {
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005992 lldb_private::MemoryRegionInfo region_info;
5993 error = GetMemoryRegionInfo(range_end, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005994 // GetMemoryRegionInfo should only return an error if it is unimplemented.
5995 if (error.Fail()) {
5996 region_list.clear();
5997 break;
Todd Fiala75930012016-08-19 04:21:48 +00005998 }
5999
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00006000 range_end = region_info.GetRange().GetRangeEnd();
6001 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
6002 region_list.push_back(std::move(region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00006003 }
6004 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00006005
Kate Stoneb9c1b512016-09-06 20:57:50 +00006006 return error;
6007}
6008
Zachary Turner97206d52017-05-12 04:51:55 +00006009Status
Adrian Prantl0e4c4822019-03-06 21:22:25 +00006010Process::ConfigureStructuredData(ConstString type_name,
Zachary Turner97206d52017-05-12 04:51:55 +00006011 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00006012 // If you get this, the Process-derived class needs to implement a method to
6013 // enable an already-reported asynchronous structured data feature. See
6014 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00006015 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00006016}
6017
6018void Process::MapSupportedStructuredDataPlugins(
6019 const StructuredData::Array &supported_type_names) {
6020 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6021
6022 // Bail out early if there are no type names to map.
6023 if (supported_type_names.GetSize() == 0) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00006024 LLDB_LOGF(log, "Process::%s(): no structured data types supported",
6025 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006026 return;
6027 }
Todd Fiala75930012016-08-19 04:21:48 +00006028
Kate Stoneb9c1b512016-09-06 20:57:50 +00006029 // Convert StructuredData type names to ConstString instances.
6030 std::set<ConstString> const_type_names;
6031
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00006032 LLDB_LOGF(log,
6033 "Process::%s(): the process supports the following async "
6034 "structured data types:",
6035 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006036
6037 supported_type_names.ForEach(
6038 [&const_type_names, &log](StructuredData::Object *object) {
6039 if (!object) {
6040 // Invalid - shouldn't be null objects in the array.
6041 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006042 }
6043
6044 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006045 if (!type_name) {
6046 // Invalid format - all type names should be strings.
6047 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006048 }
6049
6050 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00006051 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00006052 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006053 });
Todd Fiala75930012016-08-19 04:21:48 +00006054
Adrian Prantl05097242018-04-30 16:49:04 +00006055 // For each StructuredDataPlugin, if the plugin handles any of the types in
6056 // the supported_type_names, map that type name to that plugin. Stop when
6057 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00006058 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00006059 // supports?
6060 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
6061 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00006062 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6063 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00006064 if (!create_instance)
6065 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00006066
Kate Stoneb9c1b512016-09-06 20:57:50 +00006067 // Create the plugin.
6068 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6069 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00006070 // This plugin doesn't think it can work with the process. Move on to the
6071 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006072 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006073 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006074
Adrian Prantl05097242018-04-30 16:49:04 +00006075 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006076 std::vector<ConstString> names_to_remove;
6077 for (auto &type_name : const_type_names) {
6078 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6079 m_structured_data_plugin_map.insert(
6080 std::make_pair(type_name, plugin_sp));
6081 names_to_remove.push_back(type_name);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00006082 LLDB_LOGF(log,
6083 "Process::%s(): using plugin %s for type name "
6084 "%s",
6085 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6086 type_name.GetCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00006087 }
6088 }
6089
6090 // Remove the type names that were consumed by this plugin.
6091 for (auto &type_name : names_to_remove)
6092 const_type_names.erase(type_name);
6093 }
Todd Fiala75930012016-08-19 04:21:48 +00006094}
6095
Kate Stoneb9c1b512016-09-06 20:57:50 +00006096bool Process::RouteAsyncStructuredData(
6097 const StructuredData::ObjectSP object_sp) {
6098 // Nothing to do if there's no data.
6099 if (!object_sp)
6100 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006101
Adrian Prantl05097242018-04-30 16:49:04 +00006102 // The contract is this must be a dictionary, so we can look up the routing
6103 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006104 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6105 if (!dictionary)
6106 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006107
Kate Stoneb9c1b512016-09-06 20:57:50 +00006108 // Grab the async structured type name (i.e. the feature/plugin name).
6109 ConstString type_name;
6110 if (!dictionary->GetValueForKeyAsString("type", type_name))
6111 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006112
Kate Stoneb9c1b512016-09-06 20:57:50 +00006113 // Check if there's a plugin registered for this type name.
6114 auto find_it = m_structured_data_plugin_map.find(type_name);
6115 if (find_it == m_structured_data_plugin_map.end()) {
6116 // We don't have a mapping for this structured data type.
6117 return false;
6118 }
Todd Fiala75930012016-08-19 04:21:48 +00006119
Kate Stoneb9c1b512016-09-06 20:57:50 +00006120 // Route the structured data to the plugin.
6121 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6122 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006123}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006124
Zachary Turner97206d52017-05-12 04:51:55 +00006125Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006126 // Default implementation does nothign.
6127 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00006128 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006129}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006130
Frederic Rissd10d3792018-05-11 18:21:11 +00006131UtilityFunction *Process::GetLoadImageUtilityFunction(
6132 Platform *platform,
6133 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006134 if (platform != GetTarget().GetPlatform().get())
6135 return nullptr;
Michal Gorny3276fff2019-09-03 12:31:24 +00006136 llvm::call_once(m_dlopen_utility_func_flag_once,
6137 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006138 return m_dlopen_utility_func_up.get();
6139}
Alex Langford5b2b38e2019-09-13 00:02:05 +00006140
6141bool Process::CallVoidArgVoidPtrReturn(const Address *address,
6142 addr_t &returned_func,
6143 bool trap_exceptions) {
6144 Thread *thread = GetThreadList().GetExpressionExecutionThread().get();
6145 if (thread == nullptr || address == nullptr)
6146 return false;
6147
6148 EvaluateExpressionOptions options;
6149 options.SetStopOthers(true);
6150 options.SetUnwindOnError(true);
6151 options.SetIgnoreBreakpoints(true);
6152 options.SetTryAllThreads(true);
6153 options.SetDebug(false);
6154 options.SetTimeout(GetUtilityExpressionTimeout());
6155 options.SetTrapExceptions(trap_exceptions);
6156
6157 auto type_system_or_err =
6158 GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC);
6159 if (!type_system_or_err) {
6160 llvm::consumeError(type_system_or_err.takeError());
6161 return false;
6162 }
6163 CompilerType void_ptr_type =
6164 type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
6165 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction(
6166 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
6167 if (call_plan_sp) {
6168 DiagnosticManager diagnostics;
6169
6170 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6171 if (frame) {
6172 ExecutionContext exe_ctx;
6173 frame->CalculateExecutionContext(exe_ctx);
6174 ExpressionResults result =
6175 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
6176 if (result == eExpressionCompleted) {
6177 returned_func =
6178 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6179 LLDB_INVALID_ADDRESS);
6180
6181 if (GetAddressByteSize() == 4) {
6182 if (returned_func == UINT32_MAX)
6183 return false;
6184 } else if (GetAddressByteSize() == 8) {
6185 if (returned_func == UINT64_MAX)
6186 return false;
6187 }
6188 return true;
6189 }
6190 }
6191 }
6192
6193 return false;
6194}