blob: d32d3df5c8e616fd9b0c7e0ed1359d5d2d50fd09 [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
Jim Inghamd3dfd8c2020-08-07 14:44:01 -0700281bool ProcessProperties::GetSteppingRunsAllThreads() const {
282 const uint32_t idx = ePropertySteppingRunsAllThreads;
283 return m_collection_sp->GetPropertyAtIndexAsBoolean(
284 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
285}
286
Jonas Devlieghere018e5a92020-05-19 11:16:57 -0700287bool ProcessProperties::GetOSPluginReportsAllThreads() const {
288 const bool fail_value = true;
289 const Property *exp_property =
290 m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental);
291 OptionValueProperties *exp_values =
292 exp_property->GetValue()->GetAsProperties();
293 if (!exp_values)
294 return fail_value;
295
296 return exp_values->GetPropertyAtIndexAsBoolean(
297 nullptr, ePropertyOSPluginReportsAllThreads, fail_value);
298}
299
300void ProcessProperties::SetOSPluginReportsAllThreads(bool does_report) {
301 const Property *exp_property =
302 m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental);
303 OptionValueProperties *exp_values =
304 exp_property->GetValue()->GetAsProperties();
305 if (exp_values)
306 exp_values->SetPropertyAtIndexAsBoolean(
307 nullptr, ePropertyOSPluginReportsAllThreads, does_report);
308}
309
Zachary Turner97206d52017-05-12 04:51:55 +0000310Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000311 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000313 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314 const int short_option = m_getopt_table[option_idx].val;
315
316 switch (short_option) {
317 case 's': // Stop at program entry point
318 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
319 break;
320
321 case 'i': // STDIN for read only
322 {
323 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000324 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 launch_info.AppendFileAction(action);
326 break;
327 }
328
329 case 'o': // Open STDOUT for write only
330 {
331 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000332 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 launch_info.AppendFileAction(action);
334 break;
335 }
336
337 case 'e': // STDERR for write only
338 {
339 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000340 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 launch_info.AppendFileAction(action);
342 break;
343 }
344
345 case 'p': // Process plug-in name
346 launch_info.SetProcessPluginName(option_arg);
347 break;
348
349 case 'n': // Disable STDIO
350 {
351 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000352 const FileSpec dev_null(FileSystem::DEV_NULL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 if (action.Open(STDIN_FILENO, dev_null, true, false))
354 launch_info.AppendFileAction(action);
355 if (action.Open(STDOUT_FILENO, dev_null, false, true))
356 launch_info.AppendFileAction(action);
357 if (action.Open(STDERR_FILENO, dev_null, false, true))
358 launch_info.AppendFileAction(action);
359 break;
360 }
361
362 case 'w':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000363 launch_info.SetWorkingDirectory(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 break;
365
366 case 't': // Open process in new terminal window
367 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
368 break;
369
370 case 'a': {
371 TargetSP target_sp =
372 execution_context ? execution_context->GetTargetSP() : TargetSP();
373 PlatformSP platform_sp =
374 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000375 launch_info.GetArchitecture() =
376 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 } break;
378
379 case 'A': // Disable ASLR.
380 {
381 bool success;
382 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000383 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 if (success)
385 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000386 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 error.SetErrorStringWithFormat(
388 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000389 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000390 break;
391 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 case 'X': // shell expand args.
394 {
395 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000396 const bool expand_args =
397 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 if (success)
399 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000400 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 error.SetErrorStringWithFormat(
402 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000403 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 break;
405 }
406
407 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000408 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000409 launch_info.SetShell(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 else
411 launch_info.SetShell(HostInfo::GetDefaultShell());
412 break;
413
414 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000415 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416 break;
417
418 default:
419 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
420 short_option);
421 break;
422 }
423 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000424}
425
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000426static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000428 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429 "Stop at the entry point of the program when launching a process."},
430 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000431 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 "Set whether to disable address space layout randomization when launching "
433 "a process."},
434 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000435 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 "Name of the process plugin you want to use."},
437 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000438 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 eArgTypeDirectoryName,
440 "Set the current working directory to <path> when running the inferior."},
441 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000442 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 "Set the architecture for the process to launch when ambiguous."},
444 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000445 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 "Specify an environment variable name/value string (--environment "
447 "NAME=VALUE). Can be specified multiple times for subsequent environment "
448 "entries."},
449 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000450 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000452
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000454 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455 "Redirect stdin for the process to <filename>."},
456 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000457 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458 "Redirect stdout for the process to <filename>."},
459 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000460 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000461 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000462
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000464 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000465 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000466
Kate Stoneb9c1b512016-09-06 20:57:50 +0000467 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000468 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 "Do not set up for terminal I/O to go to running process."},
470 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000471 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000472 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000473};
474
475llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000476 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000477}
Greg Clayton32e0a752011-03-30 18:16:51 +0000478
Zachary Turner31659452016-11-17 21:15:14 +0000479ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
480 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481 ListenerSP listener_sp,
482 const FileSpec *crash_file_path) {
483 static uint32_t g_process_unique_id = 0;
484
485 ProcessSP process_sp;
486 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000487 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 ConstString const_plugin_name(plugin_name);
489 create_callback =
490 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
491 if (create_callback) {
492 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
493 if (process_sp) {
494 if (process_sp->CanDebug(target_sp, true)) {
495 process_sp->m_process_unique_id = ++g_process_unique_id;
496 } else
497 process_sp.reset();
498 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000499 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500 } else {
501 for (uint32_t idx = 0;
502 (create_callback =
503 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
504 ++idx) {
505 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
506 if (process_sp) {
507 if (process_sp->CanDebug(target_sp, false)) {
508 process_sp->m_process_unique_id = ++g_process_unique_id;
509 break;
510 } else
511 process_sp.reset();
512 }
513 }
514 }
515 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000516}
517
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518ConstString &Process::GetStaticBroadcasterClass() {
519 static ConstString class_name("lldb.process");
520 return class_name;
521}
522
523Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
524 : Process(target_sp, listener_sp,
525 UnixSignals::Create(HostInfo::GetArchitecture())) {
526 // This constructor just delegates to the full Process constructor,
527 // defaulting to using the Host's UnixSignals.
528}
529
530Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
531 const UnixSignalsSP &unix_signals_sp)
Raphael Isemannccd90912020-11-18 14:30:06 +0100532 : ProcessProperties(this),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
534 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000535 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536 m_private_state(eStateUnloaded),
537 m_private_state_broadcaster(nullptr,
538 "lldb.process.internal_state_broadcaster"),
539 m_private_state_control_broadcaster(
540 nullptr, "lldb.process.internal_state_control_broadcaster"),
541 m_private_state_listener_sp(
542 Listener::MakeListener("lldb.process.internal_state_listener")),
543 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
544 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
545 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
Jim Ingham18930652020-03-18 12:05:08 -0700546 m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
548 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000549 m_breakpoint_site_list(), m_dynamic_checkers_up(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
551 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
552 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
553 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
554 m_memory_cache(*this), m_allocated_memory_cache(*this),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000555 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000556 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
558 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
559 m_can_interpret_function_calls(false), m_warnings_issued(),
560 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
561 CheckInWithManager();
562
563 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000564 LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565
566 if (!m_unix_signals_sp)
567 m_unix_signals_sp = std::make_shared<UnixSignals>();
568
569 SetEventName(eBroadcastBitStateChanged, "state-changed");
570 SetEventName(eBroadcastBitInterrupt, "interrupt");
571 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
572 SetEventName(eBroadcastBitSTDERR, "stderr-available");
573 SetEventName(eBroadcastBitProfileData, "profile-data-available");
574 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
575
576 m_private_state_control_broadcaster.SetEventName(
577 eBroadcastInternalStateControlStop, "control-stop");
578 m_private_state_control_broadcaster.SetEventName(
579 eBroadcastInternalStateControlPause, "control-pause");
580 m_private_state_control_broadcaster.SetEventName(
581 eBroadcastInternalStateControlResume, "control-resume");
582
583 m_listener_sp->StartListeningForEvents(
584 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
585 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
586 eBroadcastBitProfileData | eBroadcastBitStructuredData);
587
588 m_private_state_listener_sp->StartListeningForEvents(
589 &m_private_state_broadcaster,
590 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
591
592 m_private_state_listener_sp->StartListeningForEvents(
593 &m_private_state_control_broadcaster,
594 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
595 eBroadcastInternalStateControlResume);
596 // We need something valid here, even if just the default UnixSignalsSP.
597 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
598
599 // Allow the platform to override the default cache line size
600 OptionValueSP value_sp =
601 m_collection_sp
602 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
603 ->GetValue();
604 uint32_t platform_cache_line_size =
605 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
606 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
607 value_sp->SetUInt64Value(platform_cache_line_size);
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100608
609 RegisterAssertFrameRecognizer(this);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000610}
611
612Process::~Process() {
613 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000614 LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 StopPrivateStateThread();
616
617 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000618 // explicitly clear the thread list here to ensure that the mutex is not
619 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000620 m_thread_list.Clear();
621}
622
623const ProcessPropertiesSP &Process::GetGlobalProperties() {
624 // NOTE: intentional leak so we don't crash if global destructor chain gets
625 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000626 static ProcessPropertiesSP *g_settings_sp_ptr =
627 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 return *g_settings_sp_ptr;
629}
630
631void Process::Finalize() {
632 m_finalizing = true;
633
634 // Destroy this process if needed
635 switch (GetPrivateState()) {
636 case eStateConnected:
637 case eStateAttaching:
638 case eStateLaunching:
639 case eStateStopped:
640 case eStateRunning:
641 case eStateStepping:
642 case eStateCrashed:
643 case eStateSuspended:
644 Destroy(false);
645 break;
646
647 case eStateInvalid:
648 case eStateUnloaded:
649 case eStateDetached:
650 case eStateExited:
651 break;
652 }
653
654 // Clear our broadcaster before we proceed with destroying
655 Broadcaster::Clear();
656
Adrian Prantl05097242018-04-30 16:49:04 +0000657 // Do any cleanup needed prior to being destructed... Subclasses that
658 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659
660 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000661 // destroyed since it is very likely that undoing the loader will require
662 // access to the real process.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000663 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000665 m_os_up.reset();
666 m_system_runtime_up.reset();
667 m_dyld_up.reset();
668 m_jit_loaders_up.reset();
Jim Ingham61e8e682020-03-10 16:18:11 -0700669 m_thread_plans.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 m_thread_list_real.Destroy();
671 m_thread_list.Destroy();
672 m_extended_thread_list.Destroy();
673 m_queue_list.Clear();
674 m_queue_list_stop_id = 0;
675 std::vector<Notifications> empty_notifications;
676 m_notifications.swap(empty_notifications);
677 m_image_tokens.clear();
678 m_memory_cache.Clear();
679 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +0000680 {
681 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
682 m_language_runtimes.clear();
683 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000684 m_instrumentation_runtimes.clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000685 m_next_event_action_up.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000686 // Clear the last natural stop ID since it has a strong reference to this
687 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
689 //#ifdef LLDB_CONFIGURATION_DEBUG
690 // StreamFile s(stdout, false);
691 // EventSP event_sp;
692 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
693 // {
694 // event_sp->Dump (&s);
695 // s.EOL();
696 // }
697 //#endif
698 // We have to be very careful here as the m_private_state_listener might
699 // contain events that have ProcessSP values in them which can keep this
700 // process around forever. These events need to be cleared out.
701 m_private_state_listener_sp->Clear();
702 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
703 m_public_run_lock.SetStopped();
704 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
705 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000706 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 m_finalize_called = true;
708}
709
710void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
711 m_notifications.push_back(callbacks);
712 if (callbacks.initialize != nullptr)
713 callbacks.initialize(callbacks.baton, this);
714}
715
716bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
717 std::vector<Notifications>::iterator pos, end = m_notifications.end();
718 for (pos = m_notifications.begin(); pos != end; ++pos) {
719 if (pos->baton == callbacks.baton &&
720 pos->initialize == callbacks.initialize &&
721 pos->process_state_changed == callbacks.process_state_changed) {
722 m_notifications.erase(pos);
723 return true;
724 }
725 }
726 return false;
727}
728
729void Process::SynchronouslyNotifyStateChanged(StateType state) {
730 std::vector<Notifications>::iterator notification_pos,
731 notification_end = m_notifications.end();
732 for (notification_pos = m_notifications.begin();
733 notification_pos != notification_end; ++notification_pos) {
734 if (notification_pos->process_state_changed)
735 notification_pos->process_state_changed(notification_pos->baton, this,
736 state);
737 }
738}
739
740// FIXME: We need to do some work on events before the general Listener sees
741// them.
742// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000743// we do the little "insert real insn, step & stop" trick. But we can't do
744// that when the event is delivered by the broadcaster - since that is done on
745// the thread that is waiting for new events, so if we needed more than one
746// event for our handling, we would stall. So instead we do it when we fetch
747// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000748//
749
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750StateType Process::GetNextEvent(EventSP &event_sp) {
751 StateType state = eStateInvalid;
752
Pavel Labathd35031e12016-11-30 10:41:42 +0000753 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
754 std::chrono::seconds(0)) &&
755 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
757
758 return state;
759}
760
Pavel Labath3879fe02018-05-09 14:29:30 +0000761void Process::SyncIOHandler(uint32_t iohandler_id,
762 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763 // don't sync (potentially context switch) in case where there is no process
764 // IO
765 if (!m_process_input_reader)
766 return;
767
Pavel Labath3879fe02018-05-09 14:29:30 +0000768 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769
770 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000771 if (Result) {
772 LLDB_LOG(
773 log,
774 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
775 iohandler_id, *Result);
776 } else {
777 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
778 iohandler_id);
779 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780}
781
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000782StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
783 EventSP *event_sp_ptr, bool wait_always,
784 ListenerSP hijack_listener_sp,
785 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000787 // have restarted the target. We have to actually check each event, and in
788 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000789 if (event_sp_ptr)
790 event_sp_ptr->reset();
791 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000792 // If we are exited or detached, we won't ever get back to any other valid
793 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000796
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000798 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000799
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 if (!wait_always && StateIsStoppedState(state, true) &&
801 StateIsStoppedState(GetPrivateState(), true)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000802 LLDB_LOGF(log,
803 "Process::%s returning without waiting for events; process "
804 "private and public states are already 'stopped'.",
805 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 // We need to toggle the run lock as this won't get done in
807 // SetPublicState() if the process is hijacked.
808 if (hijack_listener_sp && use_run_lock)
809 m_public_run_lock.SetStopped();
810 return state;
811 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000812
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 while (state != eStateInvalid) {
814 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000815 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 if (event_sp_ptr && event_sp)
817 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +0000818
Kate Stoneb9c1b512016-09-06 20:57:50 +0000819 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
820 Process::HandleProcessStateChangedEvent(event_sp, stream,
821 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +0000822
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 switch (state) {
824 case eStateCrashed:
825 case eStateDetached:
826 case eStateExited:
827 case eStateUnloaded:
828 // We need to toggle the run lock as this won't get done in
829 // SetPublicState() if the process is hijacked.
830 if (hijack_listener_sp && use_run_lock)
831 m_public_run_lock.SetStopped();
832 return state;
833 case eStateStopped:
834 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
835 continue;
836 else {
Pavel Labath78521ef2015-03-06 10:52:47 +0000837 // We need to toggle the run lock as this won't get done in
838 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +0000839 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000840 m_public_run_lock.SetStopped();
841 return state;
842 }
843 default:
844 continue;
845 }
846 }
847 return state;
848}
849
850bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
851 Stream *stream,
852 bool &pop_process_io_handler) {
853 const bool handle_pop = pop_process_io_handler;
854
855 pop_process_io_handler = false;
856 ProcessSP process_sp =
857 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
858
859 if (!process_sp)
860 return false;
861
862 StateType event_state =
863 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
864 if (event_state == eStateInvalid)
865 return false;
866
867 switch (event_state) {
868 case eStateInvalid:
869 case eStateUnloaded:
870 case eStateAttaching:
871 case eStateLaunching:
872 case eStateStepping:
873 case eStateDetached:
874 if (stream)
875 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
876 StateAsCString(event_state));
877 if (event_state == eStateDetached)
878 pop_process_io_handler = true;
879 break;
880
881 case eStateConnected:
882 case eStateRunning:
883 // Don't be chatty when we run...
884 break;
885
886 case eStateExited:
887 if (stream)
888 process_sp->GetStatus(*stream);
889 pop_process_io_handler = true;
890 break;
891
892 case eStateStopped:
893 case eStateCrashed:
894 case eStateSuspended:
895 // Make sure the program hasn't been auto-restarted:
896 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
897 if (stream) {
898 size_t num_reasons =
899 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
900 if (num_reasons > 0) {
901 // FIXME: Do we want to report this, or would that just be annoyingly
902 // chatty?
903 if (num_reasons == 1) {
904 const char *reason =
905 Process::ProcessEventData::GetRestartedReasonAtIndex(
906 event_sp.get(), 0);
907 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
908 process_sp->GetID(),
909 reason ? reason : "<UNKNOWN REASON>");
910 } else {
911 stream->Printf("Process %" PRIu64
912 " stopped and restarted, reasons:\n",
913 process_sp->GetID());
914
915 for (size_t i = 0; i < num_reasons; i++) {
916 const char *reason =
917 Process::ProcessEventData::GetRestartedReasonAtIndex(
918 event_sp.get(), i);
919 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
920 }
921 }
922 }
923 }
924 } else {
925 StopInfoSP curr_thread_stop_info_sp;
926 // Lock the thread list so it doesn't change on us, this is the scope for
927 // the locker:
928 {
929 ThreadList &thread_list = process_sp->GetThreadList();
930 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
931
932 ThreadSP curr_thread(thread_list.GetSelectedThread());
933 ThreadSP thread;
934 StopReason curr_thread_stop_reason = eStopReasonInvalid;
935 if (curr_thread) {
936 curr_thread_stop_reason = curr_thread->GetStopReason();
937 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
938 }
939 if (!curr_thread || !curr_thread->IsValid() ||
940 curr_thread_stop_reason == eStopReasonInvalid ||
941 curr_thread_stop_reason == eStopReasonNone) {
942 // Prefer a thread that has just completed its plan over another
943 // thread as current thread.
944 ThreadSP plan_thread;
945 ThreadSP other_thread;
946
947 const size_t num_threads = thread_list.GetSize();
948 size_t i;
949 for (i = 0; i < num_threads; ++i) {
950 thread = thread_list.GetThreadAtIndex(i);
951 StopReason thread_stop_reason = thread->GetStopReason();
952 switch (thread_stop_reason) {
953 case eStopReasonInvalid:
954 case eStopReasonNone:
955 break;
956
957 case eStopReasonSignal: {
958 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +0000959 // that signal. We have to have had another reason for stopping
960 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 uint64_t signo = thread->GetStopInfo()->GetValue();
962 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
963 if (!other_thread)
964 other_thread = thread;
965 }
966 break;
967 }
968 case eStopReasonTrace:
969 case eStopReasonBreakpoint:
970 case eStopReasonWatchpoint:
971 case eStopReasonException:
972 case eStopReasonExec:
973 case eStopReasonThreadExiting:
974 case eStopReasonInstrumentation:
975 if (!other_thread)
976 other_thread = thread;
977 break;
978 case eStopReasonPlanComplete:
979 if (!plan_thread)
980 plan_thread = thread;
981 break;
982 }
983 }
984 if (plan_thread)
985 thread_list.SetSelectedThreadByID(plan_thread->GetID());
986 else if (other_thread)
987 thread_list.SetSelectedThreadByID(other_thread->GetID());
988 else {
989 if (curr_thread && curr_thread->IsValid())
990 thread = curr_thread;
991 else
992 thread = thread_list.GetThreadAtIndex(0);
993
994 if (thread)
995 thread_list.SetSelectedThreadByID(thread->GetID());
996 }
997 }
998 }
999 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +00001000 // have to run code, e.g. for Data formatters, and if we hold the
1001 // ThreadList mutex, then the process is going to have a hard time
1002 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 if (stream) {
1004 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1005 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1006 &process_sp->GetTarget()) {
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +01001007 ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
1008
1009 if (!thread_sp || !thread_sp->IsValid())
1010 return false;
1011
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 const bool only_threads_with_stop_reason = true;
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +01001013 const uint32_t start_frame = thread_sp->GetSelectedFrameIndex();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014 const uint32_t num_frames = 1;
1015 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001016 const bool stop_format = true;
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +01001017
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 process_sp->GetStatus(*stream);
1019 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1020 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001021 num_frames_with_source,
1022 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 if (curr_thread_stop_info_sp) {
1024 lldb::addr_t crashing_address;
1025 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1026 curr_thread_stop_info_sp, &crashing_address);
1027 if (valobj_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028 const ValueObject::GetExpressionPathFormat format =
1029 ValueObject::GetExpressionPathFormat::
1030 eGetExpressionPathFormatHonorPointers;
1031 stream->PutCString("Likely cause: ");
Alex Langford3014efe2020-02-02 14:17:02 -08001032 valobj_sp->GetExpressionPath(*stream, format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1034 }
1035 }
1036 } else {
1037 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1038 process_sp->GetTarget().shared_from_this());
1039 if (target_idx != UINT32_MAX)
1040 stream->Printf("Target %d: (", target_idx);
1041 else
1042 stream->Printf("Target <unknown index>: (");
1043 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1044 stream->Printf(") stopped.\n");
1045 }
1046 }
1047
1048 // Pop the process IO handler
1049 pop_process_io_handler = true;
1050 }
1051 break;
1052 }
1053
1054 if (handle_pop && pop_process_io_handler)
1055 process_sp->PopProcessIOHandler();
1056
1057 return true;
1058}
1059
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1061 if (listener_sp) {
1062 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1063 eBroadcastBitInterrupt);
1064 } else
1065 return false;
1066}
Greg Claytondc6224e2014-10-21 01:00:42 +00001067
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001069
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001070StateType Process::GetStateChangedEvents(EventSP &event_sp,
1071 const Timeout<std::micro> &timeout,
1072 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001074 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001075
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 ListenerSP listener_sp = hijack_listener_sp;
1077 if (!listener_sp)
1078 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001079
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001081 if (listener_sp->GetEventForBroadcasterWithType(
1082 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001083 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1085 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001086 else
1087 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001089
Pavel Labathd02b1c82017-02-10 11:49:33 +00001090 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001091 return state;
1092}
Greg Claytondc6224e2014-10-21 01:00:42 +00001093
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094Event *Process::PeekAtStateChangedEvents() {
1095 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001096
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001097 LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001098
Kate Stoneb9c1b512016-09-06 20:57:50 +00001099 Event *event_ptr;
1100 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1101 this, eBroadcastBitStateChanged);
1102 if (log) {
1103 if (event_ptr) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001104 LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
1105 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001107 LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001108 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 }
1110 return event_ptr;
1111}
Greg Claytondc6224e2014-10-21 01:00:42 +00001112
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001113StateType
1114Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1115 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001117 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118
1119 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001120 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1121 &m_private_state_broadcaster,
1122 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001123 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1125 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1126
Pavel Labathd02b1c82017-02-10 11:49:33 +00001127 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1128 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129 return state;
1130}
1131
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001132bool Process::GetEventsPrivate(EventSP &event_sp,
1133 const Timeout<std::micro> &timeout,
1134 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001135 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001136 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001137
1138 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001139 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001140 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001141 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001142 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001143}
1144
1145bool Process::IsRunning() const {
1146 return StateIsRunningState(m_public_state.GetValue());
1147}
1148
1149int Process::GetExitStatus() {
1150 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1151
1152 if (m_public_state.GetValue() == eStateExited)
1153 return m_exit_status;
1154 return -1;
1155}
1156
1157const char *Process::GetExitDescription() {
1158 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1159
1160 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1161 return m_exit_string.c_str();
1162 return nullptr;
1163}
1164
1165bool Process::SetExitStatus(int status, const char *cstr) {
1166 // Use a mutex to protect setting the exit status.
1167 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1168
1169 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1170 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001171 LLDB_LOGF(
1172 log, "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1173 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", cstr ? "\"" : "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174
1175 // We were already in the exited state
1176 if (m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001177 LLDB_LOGF(log, "Process::SetExitStatus () ignoring exit status because "
1178 "state was already set to eStateExited");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001179 return false;
1180 }
1181
1182 m_exit_status = status;
1183 if (cstr)
1184 m_exit_string = cstr;
1185 else
1186 m_exit_string.clear();
1187
Adrian Prantl05097242018-04-30 16:49:04 +00001188 // Clear the last natural stop ID since it has a strong reference to this
1189 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1191
1192 SetPrivateState(eStateExited);
1193
1194 // Allow subclasses to do some cleanup
1195 DidExit();
1196
1197 return true;
1198}
1199
1200bool Process::IsAlive() {
1201 switch (m_private_state.GetValue()) {
1202 case eStateConnected:
1203 case eStateAttaching:
1204 case eStateLaunching:
1205 case eStateStopped:
1206 case eStateRunning:
1207 case eStateStepping:
1208 case eStateCrashed:
1209 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001210 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 default:
1212 return false;
1213 }
Jason Molendaa814f702015-11-05 23:03:44 +00001214}
1215
Adrian Prantl05097242018-04-30 16:49:04 +00001216// This static callback can be used to watch for local child processes on the
1217// current host. The child process exits, the process will be found in the
1218// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001219// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220bool Process::SetProcessExitStatus(
1221 lldb::pid_t pid, bool exited,
1222 int signo, // Zero for no signal
1223 int exit_status // Exit value of process if signal is zero
1224 ) {
1225 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001226 LLDB_LOGF(log,
1227 "Process::SetProcessExitStatus (pid=%" PRIu64
1228 ", exited=%i, signal=%i, exit_status=%i)\n",
1229 pid, exited, signo, exit_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230
1231 if (exited) {
1232 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1233 if (target_sp) {
1234 ProcessSP process_sp(target_sp->GetProcessSP());
1235 if (process_sp) {
1236 const char *signal_cstr = nullptr;
1237 if (signo)
1238 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1239
1240 process_sp->SetExitStatus(exit_status, signal_cstr);
1241 }
1242 }
1243 return true;
1244 }
1245 return false;
1246}
1247
1248void Process::UpdateThreadListIfNeeded() {
1249 const uint32_t stop_id = GetStopID();
1250 if (m_thread_list.GetSize(false) == 0 ||
1251 stop_id != m_thread_list.GetStopID()) {
Jim Ingham18930652020-03-18 12:05:08 -07001252 bool clear_unused_threads = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253 const StateType state = GetPrivateState();
1254 if (StateIsStoppedState(state, true)) {
1255 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Jim Ingham18930652020-03-18 12:05:08 -07001256 m_thread_list.SetStopID(stop_id);
1257
Adrian Prantl05097242018-04-30 16:49:04 +00001258 // m_thread_list does have its own mutex, but we need to hold onto the
1259 // mutex between the call to UpdateThreadList(...) and the
1260 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 ThreadList &old_thread_list = m_thread_list;
1262 ThreadList real_thread_list(this);
1263 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001264 // Always update the thread list with the protocol specific thread list,
1265 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1267 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001268 // are shutting down, since that may call back into the SBAPI's,
1269 // requiring the API lock which is already held by whoever is shutting
1270 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 OperatingSystem *os = GetOperatingSystem();
1272 if (os && !m_destroy_in_process) {
1273 // Clear any old backing threads where memory threads might have been
1274 // backed by actual threads from the lldb_private::Process subclass
1275 size_t num_old_threads = old_thread_list.GetSize(false);
1276 for (size_t i = 0; i < num_old_threads; ++i)
1277 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Jim Ingham18930652020-03-18 12:05:08 -07001278 // See if the OS plugin reports all threads. If it does, then
Jonas Devlieghere32d35fb2020-07-13 13:44:01 -07001279 // it is safe to clear unseen thread's plans here. Otherwise we
Jim Ingham18930652020-03-18 12:05:08 -07001280 // should preserve them in case they show up again:
Jonas Devlieghere018e5a92020-05-19 11:16:57 -07001281 clear_unused_threads = GetOSPluginReportsAllThreads();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282
1283 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001284 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001285 // dynamic type or not and we need to avoid this. OperatingSystem
1286 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287
1288 Target &target = GetTarget();
1289 const lldb::DynamicValueType saved_prefer_dynamic =
1290 target.GetPreferDynamicValue();
1291 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1292 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1293
1294 // Now let the OperatingSystem plug-in update the thread list
1295
1296 os->UpdateThreadList(
1297 old_thread_list, // Old list full of threads created by OS plug-in
1298 real_thread_list, // The actual thread list full of threads
1299 // created by each lldb_private::Process
1300 // subclass
1301 new_thread_list); // The new thread list that we will show to the
1302 // user that gets filled in
1303
1304 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1305 target.SetPreferDynamicValue(saved_prefer_dynamic);
1306 } else {
1307 // No OS plug-in, the new thread list is the same as the real thread
Jim Ingham18930652020-03-18 12:05:08 -07001308 // list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309 new_thread_list = real_thread_list;
1310 }
1311
1312 m_thread_list_real.Update(real_thread_list);
1313 m_thread_list.Update(new_thread_list);
1314 m_thread_list.SetStopID(stop_id);
1315
1316 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1317 // Clear any extended threads that we may have accumulated previously
1318 m_extended_thread_list.Clear();
1319 m_extended_thread_stop_id = GetLastNaturalStopID();
1320
1321 m_queue_list.Clear();
1322 m_queue_list_stop_id = GetLastNaturalStopID();
1323 }
1324 }
Jim Ingham18930652020-03-18 12:05:08 -07001325 // Now update the plan stack map.
1326 // If we do have an OS plugin, any absent real threads in the
1327 // m_thread_list have already been removed from the ThreadPlanStackMap.
1328 // So any remaining threads are OS Plugin threads, and those we want to
1329 // preserve in case they show up again.
1330 m_thread_plans.Update(m_thread_list, clear_unused_threads);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331 }
1332 }
1333}
1334
Jim Ingham61e8e682020-03-10 16:18:11 -07001335ThreadPlanStack *Process::FindThreadPlans(lldb::tid_t tid) {
1336 return m_thread_plans.Find(tid);
1337}
1338
Jim Ingham18930652020-03-18 12:05:08 -07001339bool Process::PruneThreadPlansForTID(lldb::tid_t tid) {
1340 return m_thread_plans.PrunePlansForTID(tid);
Jim Ingham61e8e682020-03-10 16:18:11 -07001341}
1342
Jim Ingham18930652020-03-18 12:05:08 -07001343void Process::PruneThreadPlans() {
1344 m_thread_plans.Update(GetThreadList(), true, false);
1345}
1346
1347bool Process::DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid,
1348 lldb::DescriptionLevel desc_level,
1349 bool internal, bool condense_trivial,
1350 bool skip_unreported_plans) {
1351 return m_thread_plans.DumpPlansForTID(
1352 strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
1353}
1354void Process::DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,
1355 bool internal, bool condense_trivial,
1356 bool skip_unreported_plans) {
1357 m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
1358 skip_unreported_plans);
Jim Ingham61e8e682020-03-10 16:18:11 -07001359}
1360
Kate Stoneb9c1b512016-09-06 20:57:50 +00001361void Process::UpdateQueueListIfNeeded() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001362 if (m_system_runtime_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001363 if (m_queue_list.GetSize() == 0 ||
1364 m_queue_list_stop_id != GetLastNaturalStopID()) {
1365 const StateType state = GetPrivateState();
1366 if (StateIsStoppedState(state, true)) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001367 m_system_runtime_up->PopulateQueueList(m_queue_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001368 m_queue_list_stop_id = GetLastNaturalStopID();
1369 }
1370 }
1371 }
1372}
1373
1374ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1375 OperatingSystem *os = GetOperatingSystem();
1376 if (os)
1377 return os->CreateThread(tid, context);
1378 return ThreadSP();
1379}
1380
1381uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1382 return AssignIndexIDToThread(thread_id);
1383}
1384
1385bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1386 return (m_thread_id_to_index_id_map.find(thread_id) !=
1387 m_thread_id_to_index_id_map.end());
1388}
1389
1390uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1391 uint32_t result = 0;
1392 std::map<uint64_t, uint32_t>::iterator iterator =
1393 m_thread_id_to_index_id_map.find(thread_id);
1394 if (iterator == m_thread_id_to_index_id_map.end()) {
1395 result = ++m_thread_index_id;
1396 m_thread_id_to_index_id_map[thread_id] = result;
1397 } else {
1398 result = iterator->second;
1399 }
1400
1401 return result;
1402}
1403
1404StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001405 return m_public_state.GetValue();
1406}
1407
Kate Stoneb9c1b512016-09-06 20:57:50 +00001408void Process::SetPublicState(StateType new_state, bool restarted) {
1409 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1410 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001411 LLDB_LOGF(log, "Process::SetPublicState (state = %s, restarted = %i)",
1412 StateAsCString(new_state), restarted);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001413 const StateType old_state = m_public_state.GetValue();
1414 m_public_state.SetValue(new_state);
1415
Adrian Prantl05097242018-04-30 16:49:04 +00001416 // On the transition from Run to Stopped, we unlock the writer end of the run
1417 // lock. The lock gets locked in Resume, which is the public API to tell the
1418 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001419 if (!StateChangedIsExternallyHijacked()) {
1420 if (new_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001421 LLDB_LOGF(log,
1422 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1423 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424 m_public_run_lock.SetStopped();
1425 } else {
1426 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1427 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1428 if ((old_state_is_stopped != new_state_is_stopped)) {
1429 if (new_state_is_stopped && !restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001430 LLDB_LOGF(log, "Process::SetPublicState (%s) -- unlocking run lock",
1431 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001432 m_public_run_lock.SetStopped();
1433 }
1434 }
1435 }
1436 }
1437}
1438
Zachary Turner97206d52017-05-12 04:51:55 +00001439Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1441 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001442 LLDB_LOGF(log, "Process::Resume -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001444 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001445 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001446 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001447 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001448 Status error = PrivateResume();
1449 if (!error.Success()) {
1450 // Undo running state change
1451 m_public_run_lock.SetStopped();
1452 }
1453 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001454}
1455
Jim Ingham3139fc92019-03-01 18:13:38 +00001456static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1457
Zachary Turner97206d52017-05-12 04:51:55 +00001458Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001459 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1460 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001461 LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001462 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001463 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001464 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001465 return error;
1466 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001467
Kate Stoneb9c1b512016-09-06 20:57:50 +00001468 ListenerSP listener_sp(
Jim Ingham3139fc92019-03-01 18:13:38 +00001469 Listener::MakeListener(g_resume_sync_name));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001470 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001471
Zachary Turner97206d52017-05-12 04:51:55 +00001472 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001473 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001474 StateType state =
Konrad Kleine248a1302019-05-23 11:14:47 +00001475 WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476 const bool must_be_alive =
1477 false; // eStateExited is ok, so this must be false
1478 if (!StateIsStoppedState(state, must_be_alive))
1479 error.SetErrorStringWithFormat(
1480 "process not in stopped state after synchronous resume: %s",
1481 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001482 } else {
1483 // Undo running state change
1484 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001485 }
Ed Mastec29693f2013-07-02 16:35:47 +00001486
Kate Stoneb9c1b512016-09-06 20:57:50 +00001487 // Undo the hijacking of process events...
1488 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001489
Kate Stoneb9c1b512016-09-06 20:57:50 +00001490 return error;
1491}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001492
Jim Ingham3139fc92019-03-01 18:13:38 +00001493bool Process::StateChangedIsExternallyHijacked() {
1494 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1495 const char *hijacking_name = GetHijackingListenerName();
1496 if (hijacking_name &&
1497 strcmp(hijacking_name, g_resume_sync_name))
1498 return true;
1499 }
1500 return false;
1501}
1502
1503bool Process::StateChangedIsHijackedForSynchronousResume() {
1504 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1505 const char *hijacking_name = GetHijackingListenerName();
1506 if (hijacking_name &&
1507 strcmp(hijacking_name, g_resume_sync_name) == 0)
1508 return true;
1509 }
1510 return false;
1511}
1512
Kate Stoneb9c1b512016-09-06 20:57:50 +00001513StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001514
Kate Stoneb9c1b512016-09-06 20:57:50 +00001515void Process::SetPrivateState(StateType new_state) {
1516 if (m_finalize_called)
1517 return;
1518
1519 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1520 LIBLLDB_LOG_PROCESS));
1521 bool state_changed = false;
1522
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001523 LLDB_LOGF(log, "Process::SetPrivateState (%s)", StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001524
1525 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1526 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1527
1528 const StateType old_state = m_private_state.GetValueNoLock();
1529 state_changed = old_state != new_state;
1530
1531 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1532 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1533 if (old_state_is_stopped != new_state_is_stopped) {
1534 if (new_state_is_stopped)
1535 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001536 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001537 m_private_run_lock.SetRunning();
1538 }
1539
1540 if (state_changed) {
1541 m_private_state.SetValueNoLock(new_state);
1542 EventSP event_sp(
1543 new Event(eBroadcastBitStateChanged,
1544 new ProcessEventData(shared_from_this(), new_state)));
1545 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001546 // Note, this currently assumes that all threads in the list stop when
1547 // the process stops. In the future we will want to support a debugging
1548 // model where some threads continue to run while others are stopped.
1549 // When that happens we will either need a way for the thread list to
1550 // identify which threads are stopping or create a special thread list
1551 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001552 //
Adrian Prantl05097242018-04-30 16:49:04 +00001553 // The process plugin is responsible for managing the actual behavior of
1554 // the threads and should have stopped any threads that are going to stop
1555 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001556 m_thread_list.DidStop();
1557
1558 m_mod_id.BumpStopID();
1559 if (!m_mod_id.IsLastResumeForUserExpression())
1560 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1561 m_memory_cache.Clear();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001562 LLDB_LOGF(log, "Process::SetPrivateState (%s) stop_id = %u",
1563 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001564 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001565
Kate Stoneb9c1b512016-09-06 20:57:50 +00001566 // Use our target to get a shared pointer to ourselves...
1567 if (m_finalize_called && !PrivateStateThreadIsValid())
1568 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001569 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570 m_private_state_broadcaster.BroadcastEvent(event_sp);
1571 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001572 LLDB_LOGF(log,
1573 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1574 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001575 }
Jim Ingham22777012010-09-23 02:01:19 +00001576}
1577
Kate Stoneb9c1b512016-09-06 20:57:50 +00001578void Process::SetRunningUserExpression(bool on) {
1579 m_mod_id.SetRunningUserExpression(on);
1580}
1581
Raphael Isemannc01783a2018-08-29 22:50:54 +00001582void Process::SetRunningUtilityFunction(bool on) {
1583 m_mod_id.SetRunningUtilityFunction(on);
1584}
1585
Kate Stoneb9c1b512016-09-06 20:57:50 +00001586addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1587
1588const lldb::ABISP &Process::GetABI() {
1589 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001590 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001591 return m_abi_sp;
1592}
1593
Davide Italianocec82632019-12-03 16:54:04 -08001594std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
Alex Langford03e1a822019-05-29 18:08:22 +00001595 std::vector<LanguageRuntime *> language_runtimes;
1596
1597 if (m_finalizing)
1598 return language_runtimes;
1599
1600 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1601 // Before we pass off a copy of the language runtimes, we must make sure that
1602 // our collection is properly populated. It's possible that some of the
1603 // language runtimes were not loaded yet, either because nobody requested it
1604 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1605 // hadn't been loaded).
1606 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
Davide Italianocec82632019-12-03 16:54:04 -08001607 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
Alex Langford03e1a822019-05-29 18:08:22 +00001608 language_runtimes.emplace_back(runtime);
1609 }
1610
1611 return language_runtimes;
1612}
1613
Davide Italianocec82632019-12-03 16:54:04 -08001614LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001615 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001616 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001617
Alex Langford7d3e97f2019-05-29 21:07:53 +00001618 LanguageRuntime *runtime = nullptr;
1619
Alex Langford74eb76f2019-05-22 23:01:18 +00001620 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001621 LanguageRuntimeCollection::iterator pos;
1622 pos = m_language_runtimes.find(language);
Davide Italianocec82632019-12-03 16:54:04 -08001623 if (pos == m_language_runtimes.end() || !pos->second) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001624 lldb::LanguageRuntimeSP runtime_sp(
1625 LanguageRuntime::FindPlugin(this, language));
1626
1627 m_language_runtimes[language] = runtime_sp;
Alex Langford7d3e97f2019-05-29 21:07:53 +00001628 runtime = runtime_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001629 } else
Alex Langford7d3e97f2019-05-29 21:07:53 +00001630 runtime = pos->second.get();
1631
1632 if (runtime)
1633 // It's possible that a language runtime can support multiple LanguageTypes,
1634 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1635 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1636 // primary language type and make sure that our runtime supports it.
1637 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1638
1639 return runtime;
Jim Ingham22777012010-09-23 02:01:19 +00001640}
1641
Kate Stoneb9c1b512016-09-06 20:57:50 +00001642bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1643 if (m_finalizing)
1644 return false;
1645
1646 if (in_value.IsDynamic())
1647 return false;
1648 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1649
1650 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1651 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1652 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1653 }
1654
Alex Langford41dc5522019-05-30 21:03:53 +00001655 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1656 if (runtime->CouldHaveDynamicValue(in_value))
1657 return true;
1658 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001659
Alex Langford41dc5522019-05-30 21:03:53 +00001660 return false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001661}
1662
Kate Stoneb9c1b512016-09-06 20:57:50 +00001663void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001664 m_dynamic_checkers_up.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001665}
1666
Kate Stoneb9c1b512016-09-06 20:57:50 +00001667BreakpointSiteList &Process::GetBreakpointSiteList() {
1668 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001669}
1670
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1672 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001673}
1674
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675void Process::DisableAllBreakpointSites() {
1676 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1677 // bp_site->SetEnabled(true);
1678 DisableBreakpointSite(bp_site);
1679 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001680}
1681
Zachary Turner97206d52017-05-12 04:51:55 +00001682Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1683 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001684
Kate Stoneb9c1b512016-09-06 20:57:50 +00001685 if (error.Success())
1686 m_breakpoint_site_list.Remove(break_id);
1687
1688 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001689}
1690
Zachary Turner97206d52017-05-12 04:51:55 +00001691Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1692 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001693 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1694 if (bp_site_sp) {
1695 if (bp_site_sp->IsEnabled())
1696 error = DisableBreakpointSite(bp_site_sp.get());
1697 } else {
1698 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1699 break_id);
1700 }
1701
1702 return error;
1703}
1704
Zachary Turner97206d52017-05-12 04:51:55 +00001705Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1706 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001707 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1708 if (bp_site_sp) {
1709 if (!bp_site_sp->IsEnabled())
1710 error = EnableBreakpointSite(bp_site_sp.get());
1711 } else {
1712 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1713 break_id);
1714 }
1715 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001716}
1717
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001718lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001719Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1720 bool use_hardware) {
1721 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001722
Kate Stoneb9c1b512016-09-06 20:57:50 +00001723 bool show_error = true;
1724 switch (GetState()) {
1725 case eStateInvalid:
1726 case eStateUnloaded:
1727 case eStateConnected:
1728 case eStateAttaching:
1729 case eStateLaunching:
1730 case eStateDetached:
1731 case eStateExited:
1732 show_error = false;
1733 break;
1734
1735 case eStateStopped:
1736 case eStateRunning:
1737 case eStateStepping:
1738 case eStateCrashed:
1739 case eStateSuspended:
1740 show_error = IsAlive();
1741 break;
1742 }
1743
Adrian Prantl05097242018-04-30 16:49:04 +00001744 // Reset the IsIndirect flag here, in case the location changes from pointing
1745 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001746 owner->SetIsIndirect(false);
1747
1748 if (owner->ShouldResolveIndirectFunctions()) {
1749 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1750 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001751 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752 Address symbol_address = symbol->GetAddress();
1753 load_addr = ResolveIndirectFunction(&symbol_address, error);
1754 if (!error.Success() && show_error) {
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001755 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001756 "warning: failed to resolve indirect function at 0x%" PRIx64
1757 " for breakpoint %i.%i: %s\n",
1758 symbol->GetLoadAddress(&GetTarget()),
1759 owner->GetBreakpoint().GetID(), owner->GetID(),
1760 error.AsCString() ? error.AsCString() : "unknown error");
1761 return LLDB_INVALID_BREAK_ID;
1762 }
1763 Address resolved_address(load_addr);
1764 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1765 owner->SetIsIndirect(true);
1766 } else
1767 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1768 } else
1769 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1770
1771 if (load_addr != LLDB_INVALID_ADDRESS) {
1772 BreakpointSiteSP bp_site_sp;
1773
1774 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001775 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001776
1777 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1778
1779 if (bp_site_sp) {
1780 bp_site_sp->AddOwner(owner);
1781 owner->SetBreakpointSite(bp_site_sp);
1782 return bp_site_sp->GetID();
1783 } else {
1784 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1785 load_addr, use_hardware));
1786 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001787 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001788 if (error.Success()) {
1789 owner->SetBreakpointSite(bp_site_sp);
1790 return m_breakpoint_site_list.Add(bp_site_sp);
1791 } else {
Jonas Devliegheree103ae92018-11-15 01:18:15 +00001792 if (show_error || use_hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001793 // Report error for setting breakpoint...
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001794 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795 "warning: failed to set breakpoint site at 0x%" PRIx64
1796 " for breakpoint %i.%i: %s\n",
1797 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1798 error.AsCString() ? error.AsCString() : "unknown error");
1799 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001800 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001801 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001802 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001803 }
1804 // We failed to enable the breakpoint
1805 return LLDB_INVALID_BREAK_ID;
1806}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001807
Kate Stoneb9c1b512016-09-06 20:57:50 +00001808void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1809 lldb::user_id_t owner_loc_id,
1810 BreakpointSiteSP &bp_site_sp) {
1811 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1812 if (num_owners == 0) {
1813 // Don't try to disable the site if we don't have a live process anymore.
1814 if (IsAlive())
1815 DisableBreakpointSite(bp_site_sp.get());
1816 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1817 }
1818}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819
Kate Stoneb9c1b512016-09-06 20:57:50 +00001820size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1821 uint8_t *buf) const {
1822 size_t bytes_removed = 0;
1823 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001824
Kate Stoneb9c1b512016-09-06 20:57:50 +00001825 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1826 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001827 bp_sites_in_range.ForEach([bp_addr, size,
1828 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001829 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1830 addr_t intersect_addr;
1831 size_t intersect_size;
1832 size_t opcode_offset;
1833 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1834 &intersect_size, &opcode_offset)) {
1835 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1836 assert(bp_addr < intersect_addr + intersect_size &&
1837 intersect_addr + intersect_size <= bp_addr + size);
1838 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1839 size_t buf_offset = intersect_addr - bp_addr;
1840 ::memcpy(buf + buf_offset,
1841 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1842 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001843 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001844 }
1845 });
1846 }
1847 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001848}
1849
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1851 PlatformSP platform_sp(GetTarget().GetPlatform());
1852 if (platform_sp)
1853 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1854 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001855}
1856
Zachary Turner97206d52017-05-12 04:51:55 +00001857Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1858 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001859 assert(bp_site != nullptr);
1860 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1861 const addr_t bp_addr = bp_site->GetLoadAddress();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001862 LLDB_LOGF(
1863 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1864 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001865 if (bp_site->IsEnabled()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001866 LLDB_LOGF(
1867 log,
1868 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1869 " -- already enabled",
1870 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001871 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001872 }
1873
1874 if (bp_addr == LLDB_INVALID_ADDRESS) {
1875 error.SetErrorString("BreakpointSite contains an invalid load address.");
1876 return error;
1877 }
1878 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1879 // trap for the breakpoint site
1880 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1881
1882 if (bp_opcode_size == 0) {
1883 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1884 "returned zero, unable to get breakpoint "
1885 "trap for address 0x%" PRIx64,
1886 bp_addr);
1887 } else {
1888 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1889
1890 if (bp_opcode_bytes == nullptr) {
1891 error.SetErrorString(
1892 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1893 return error;
1894 }
1895
1896 // Save the original opcode by reading it
1897 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1898 error) == bp_opcode_size) {
1899 // Write a software breakpoint in place of the original opcode
1900 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1901 bp_opcode_size) {
1902 uint8_t verify_bp_opcode_bytes[64];
1903 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1904 error) == bp_opcode_size) {
1905 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1906 bp_opcode_size) == 0) {
1907 bp_site->SetEnabled(true);
1908 bp_site->SetType(BreakpointSite::eSoftware);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001909 LLDB_LOGF(log,
1910 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1911 "addr = 0x%" PRIx64 " -- SUCCESS",
1912 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001913 } else
1914 error.SetErrorString(
1915 "failed to verify the breakpoint trap in memory.");
1916 } else
1917 error.SetErrorString(
1918 "Unable to read memory to verify breakpoint trap.");
1919 } else
1920 error.SetErrorString("Unable to write breakpoint trap to memory.");
1921 } else
1922 error.SetErrorString("Unable to read memory at breakpoint address.");
1923 }
1924 if (log && error.Fail())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001925 LLDB_LOGF(
1926 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001927 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1928 " -- FAILED: %s",
1929 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1930 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001931}
1932
Zachary Turner97206d52017-05-12 04:51:55 +00001933Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1934 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935 assert(bp_site != nullptr);
1936 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1937 addr_t bp_addr = bp_site->GetLoadAddress();
1938 lldb::user_id_t breakID = bp_site->GetID();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001939 LLDB_LOGF(log,
1940 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1941 ") addr = 0x%" PRIx64,
1942 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001943
Kate Stoneb9c1b512016-09-06 20:57:50 +00001944 if (bp_site->IsHardware()) {
1945 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1946 } else if (bp_site->IsEnabled()) {
1947 const size_t break_op_size = bp_site->GetByteSize();
1948 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1949 if (break_op_size > 0) {
1950 // Clear a software breakpoint instruction
1951 uint8_t curr_break_op[8];
1952 assert(break_op_size <= sizeof(curr_break_op));
1953 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001954
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 // Read the breakpoint opcode
1956 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1957 break_op_size) {
1958 bool verify = false;
1959 // Make sure the breakpoint opcode exists at this address
1960 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1961 break_op_found = true;
1962 // We found a valid breakpoint opcode at this address, now restore
1963 // the saved opcode.
1964 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1965 break_op_size, error) == break_op_size) {
1966 verify = true;
1967 } else
1968 error.SetErrorString(
1969 "Memory write failed when restoring original opcode.");
1970 } else {
1971 error.SetErrorString(
1972 "Original breakpoint trap is no longer in memory.");
1973 // Set verify to true and so we can check if the original opcode has
1974 // already been restored
1975 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001976 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001977
Kate Stoneb9c1b512016-09-06 20:57:50 +00001978 if (verify) {
1979 uint8_t verify_opcode[8];
1980 assert(break_op_size < sizeof(verify_opcode));
1981 // Verify that our original opcode made it back to the inferior
1982 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1983 break_op_size) {
1984 // compare the memory we just read with the original opcode
1985 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1986 break_op_size) == 0) {
1987 // SUCCESS
1988 bp_site->SetEnabled(false);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001989 LLDB_LOGF(log,
1990 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1991 "addr = 0x%" PRIx64 " -- SUCCESS",
1992 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001993 return error;
1994 } else {
1995 if (break_op_found)
1996 error.SetErrorString("Failed to restore original opcode.");
1997 }
1998 } else
1999 error.SetErrorString("Failed to read memory to verify that "
2000 "breakpoint trap was restored.");
2001 }
2002 } else
2003 error.SetErrorString(
2004 "Unable to read memory that should contain the breakpoint trap.");
2005 }
2006 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002007 LLDB_LOGF(
2008 log,
2009 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2010 " -- already disabled",
2011 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002013 }
2014
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002015 LLDB_LOGF(
2016 log,
2017 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2018 " -- FAILED: %s",
2019 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002020 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002021}
2022
Adrian Prantl05097242018-04-30 16:49:04 +00002023// Uncomment to verify memory caching works after making changes to caching
2024// code
Greg Clayton58be07b2011-01-07 06:08:19 +00002025//#define VERIFY_MEMORY_READS
2026
Zachary Turner97206d52017-05-12 04:51:55 +00002027size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002028 error.Clear();
2029 if (!GetDisableMemoryCache()) {
2030#if defined(VERIFY_MEMORY_READS)
2031 // Memory caching is enabled, with debug verification
2032
2033 if (buf && size) {
2034 // Uncomment the line below to make sure memory caching is working.
2035 // I ran this through the test suite and got no assertions, so I am
2036 // pretty confident this is working well. If any changes are made to
2037 // memory caching, uncomment the line below and test your changes!
2038
2039 // Verify all memory reads by using the cache first, then redundantly
2040 // reading the same memory from the inferior and comparing to make sure
2041 // everything is exactly the same.
2042 std::string verify_buf(size, '\0');
2043 assert(verify_buf.size() == size);
2044 const size_t cache_bytes_read =
2045 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00002046 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002047 const size_t verify_bytes_read =
2048 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2049 verify_buf.size(), verify_error);
2050 assert(cache_bytes_read == verify_bytes_read);
2051 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2052 assert(verify_error.Success() == error.Success());
2053 return cache_bytes_read;
2054 }
2055 return 0;
2056#else // !defined(VERIFY_MEMORY_READS)
2057 // Memory caching is enabled, without debug verification
2058
2059 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002060#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002061 } else {
2062 // Memory caching is disabled
2063
2064 return ReadMemoryFromInferior(addr, buf, size, error);
2065 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002066}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002067
2068size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00002069 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002070 char buf[256];
2071 out_str.clear();
2072 addr_t curr_addr = addr;
2073 while (true) {
2074 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2075 if (length == 0)
2076 break;
2077 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00002078 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2079 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00002080 if (length == sizeof(buf) - 1)
2081 curr_addr += length;
2082 else
2083 break;
2084 }
2085 return out_str.size();
2086}
2087
2088size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00002089 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002090 size_t total_bytes_read = 0;
2091 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00002092 // Ensure a null terminator independent of the number of bytes that is
2093 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002094 memset(dst, 0, max_bytes);
2095 size_t bytes_left = max_bytes - type_width;
2096
2097 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2098 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2099 "string with more than 4 bytes "
2100 "per character!");
2101
Greg Clayton4c82d422012-05-18 23:20:01 +00002102 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002103 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2104 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002105
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106 error.Clear();
2107 while (bytes_left > 0 && error.Success()) {
2108 addr_t cache_line_bytes_left =
2109 cache_line_size - (curr_addr % cache_line_size);
2110 addr_t bytes_to_read =
2111 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2112 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002113
Kate Stoneb9c1b512016-09-06 20:57:50 +00002114 if (bytes_read == 0)
2115 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002116
Kate Stoneb9c1b512016-09-06 20:57:50 +00002117 // Search for a null terminator of correct size and alignment in
2118 // bytes_read
2119 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2120 for (size_t i = aligned_start;
2121 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2122 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2123 error.Clear();
2124 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002125 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002126
2127 total_bytes_read += bytes_read;
2128 curr_dst += bytes_read;
2129 curr_addr += bytes_read;
2130 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002131 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132 } else {
2133 if (max_bytes)
2134 error.SetErrorString("invalid arguments");
2135 }
2136 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002137}
2138
Kate Stoneb9c1b512016-09-06 20:57:50 +00002139// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002140// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002142 size_t dst_max_len,
2143 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002144 size_t total_cstr_len = 0;
2145 if (dst && dst_max_len) {
2146 result_error.Clear();
2147 // NULL out everything just to be safe
2148 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002149 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002150 addr_t curr_addr = addr;
2151 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2152 size_t bytes_left = dst_max_len - 1;
2153 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002154
Kate Stoneb9c1b512016-09-06 20:57:50 +00002155 while (bytes_left > 0) {
2156 addr_t cache_line_bytes_left =
2157 cache_line_size - (curr_addr % cache_line_size);
2158 addr_t bytes_to_read =
2159 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2160 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002161
Kate Stoneb9c1b512016-09-06 20:57:50 +00002162 if (bytes_read == 0) {
2163 result_error = error;
2164 dst[total_cstr_len] = '\0';
2165 break;
2166 }
2167 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002168
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 total_cstr_len += len;
2170
2171 if (len < bytes_to_read)
2172 break;
2173
2174 curr_dst += bytes_read;
2175 curr_addr += bytes_read;
2176 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002177 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002178 } else {
2179 if (dst == nullptr)
2180 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002181 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002182 result_error.Clear();
2183 }
2184 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002185}
2186
Kate Stoneb9c1b512016-09-06 20:57:50 +00002187size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002188 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189 if (buf == nullptr || size == 0)
2190 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002191
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192 size_t bytes_read = 0;
2193 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002194
Kate Stoneb9c1b512016-09-06 20:57:50 +00002195 while (bytes_read < size) {
2196 const size_t curr_size = size - bytes_read;
2197 const size_t curr_bytes_read =
2198 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2199 bytes_read += curr_bytes_read;
2200 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2201 break;
2202 }
2203
2204 // Replace any software breakpoint opcodes that fall into this range back
2205 // into "buf" before we return
2206 if (bytes_read > 0)
2207 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2208 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002209}
2210
Kate Stoneb9c1b512016-09-06 20:57:50 +00002211uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2212 size_t integer_byte_size,
2213 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002214 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002215 Scalar scalar;
2216 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2217 error))
2218 return scalar.ULongLong(fail_value);
2219 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002220}
2221
Kate Stoneb9c1b512016-09-06 20:57:50 +00002222int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2223 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002224 int64_t fail_value,
2225 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226 Scalar scalar;
2227 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2228 error))
2229 return scalar.SLongLong(fail_value);
2230 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002231}
2232
Zachary Turner97206d52017-05-12 04:51:55 +00002233addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 Scalar scalar;
2235 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2236 error))
2237 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2238 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002239}
2240
Kate Stoneb9c1b512016-09-06 20:57:50 +00002241bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002242 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002243 Scalar scalar;
2244 const uint32_t addr_byte_size = GetAddressByteSize();
2245 if (addr_byte_size <= 4)
2246 scalar = (uint32_t)ptr_value;
2247 else
2248 scalar = ptr_value;
2249 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2250 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002251}
2252
Kate Stoneb9c1b512016-09-06 20:57:50 +00002253size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002254 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002255 size_t bytes_written = 0;
2256 const uint8_t *bytes = (const uint8_t *)buf;
2257
2258 while (bytes_written < size) {
2259 const size_t curr_size = size - bytes_written;
2260 const size_t curr_bytes_written = DoWriteMemory(
2261 addr + bytes_written, bytes + bytes_written, curr_size, error);
2262 bytes_written += curr_bytes_written;
2263 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2264 break;
2265 }
2266 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002267}
2268
Kate Stoneb9c1b512016-09-06 20:57:50 +00002269size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002270 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002271#if defined(ENABLE_MEMORY_CACHING)
2272 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002273#endif
2274
Kate Stoneb9c1b512016-09-06 20:57:50 +00002275 if (buf == nullptr || size == 0)
2276 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002277
Kate Stoneb9c1b512016-09-06 20:57:50 +00002278 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002279
Kate Stoneb9c1b512016-09-06 20:57:50 +00002280 // We need to write any data that would go where any current software traps
2281 // (enabled software breakpoints) any software traps (breakpoints) that we
2282 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283
Kate Stoneb9c1b512016-09-06 20:57:50 +00002284 BreakpointSiteList bp_sites_in_range;
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002285 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002286 return WriteMemoryPrivate(addr, buf, size, error);
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002287
2288 // No breakpoint sites overlap
2289 if (bp_sites_in_range.IsEmpty())
2290 return WriteMemoryPrivate(addr, buf, size, error);
2291
2292 const uint8_t *ubuf = (const uint8_t *)buf;
2293 uint64_t bytes_written = 0;
2294
2295 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2296 &error](BreakpointSite *bp) -> void {
2297 if (error.Fail())
2298 return;
2299
Tatyana Krasnukhaf7ec3e32020-07-22 14:45:10 +03002300 if (bp->GetType() != BreakpointSite::eSoftware)
2301 return;
2302
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002303 addr_t intersect_addr;
2304 size_t intersect_size;
2305 size_t opcode_offset;
2306 const bool intersects = bp->IntersectsRange(
2307 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2308 UNUSED_IF_ASSERT_DISABLED(intersects);
2309 assert(intersects);
2310 assert(addr <= intersect_addr && intersect_addr < addr + size);
2311 assert(addr < intersect_addr + intersect_size &&
2312 intersect_addr + intersect_size <= addr + size);
2313 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2314
2315 // Check for bytes before this breakpoint
2316 const addr_t curr_addr = addr + bytes_written;
2317 if (intersect_addr > curr_addr) {
2318 // There are some bytes before this breakpoint that we need to just
2319 // write to memory
2320 size_t curr_size = intersect_addr - curr_addr;
2321 size_t curr_bytes_written =
2322 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2323 bytes_written += curr_bytes_written;
2324 if (curr_bytes_written != curr_size) {
2325 // We weren't able to write all of the requested bytes, we are
2326 // done looping and will return the number of bytes that we have
2327 // written so far.
2328 if (error.Success())
2329 error.SetErrorToGenericError();
2330 }
2331 }
2332 // Now write any bytes that would cover up any software breakpoints
2333 // directly into the breakpoint opcode buffer
2334 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2335 intersect_size);
2336 bytes_written += intersect_size;
2337 });
Kate Stoneb9c1b512016-09-06 20:57:50 +00002338
2339 // Write any remaining bytes after the last breakpoint if we have any left
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002340 if (bytes_written < size)
2341 bytes_written +=
2342 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2343 size - bytes_written, error);
2344
2345 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002346}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002347
Kate Stoneb9c1b512016-09-06 20:57:50 +00002348size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002349 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002350 if (byte_size == UINT32_MAX)
2351 byte_size = scalar.GetByteSize();
2352 if (byte_size > 0) {
2353 uint8_t buf[32];
2354 const size_t mem_size =
2355 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2356 if (mem_size > 0)
2357 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002358 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359 error.SetErrorString("failed to get scalar as memory data");
2360 } else {
2361 error.SetErrorString("invalid scalar value");
2362 }
2363 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002364}
2365
Kate Stoneb9c1b512016-09-06 20:57:50 +00002366size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2367 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002368 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002369 uint64_t uval = 0;
2370 if (byte_size == 0) {
2371 error.SetErrorString("byte size is zero");
2372 } else if (byte_size & (byte_size - 1)) {
2373 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2374 byte_size);
2375 } else if (byte_size <= sizeof(uval)) {
2376 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2377 if (bytes_read == byte_size) {
2378 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2379 GetAddressByteSize());
2380 lldb::offset_t offset = 0;
2381 if (byte_size <= 4)
2382 scalar = data.GetMaxU32(&offset, byte_size);
2383 else
2384 scalar = data.GetMaxU64(&offset, byte_size);
2385 if (is_signed)
2386 scalar.SignExtend(byte_size * 8);
2387 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002388 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002389 } else {
2390 error.SetErrorStringWithFormat(
2391 "byte size of %u is too large for integer scalar type", byte_size);
2392 }
2393 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002394}
2395
Pavel Labath16064d32018-03-20 11:56:24 +00002396Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2397 Status error;
2398 for (const auto &Entry : entries) {
2399 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2400 error);
2401 if (!error.Success())
2402 break;
2403 }
2404 return error;
2405}
2406
Greg Claytond495c532011-05-17 03:37:42 +00002407#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002408addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002409 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002410 if (GetPrivateState() != eStateStopped) {
2411 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002412 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002413 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002414
2415#if defined(USE_ALLOCATE_MEMORY_CACHE)
2416 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002417#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2419 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002420 LLDB_LOGF(log,
2421 "Process::AllocateMemory(size=%" PRIu64
2422 ", permissions=%s) => 0x%16.16" PRIx64
2423 " (m_stop_id = %u m_memory_id = %u)",
2424 (uint64_t)size, GetPermissionsAsCString(permissions),
2425 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2426 m_mod_id.GetMemoryID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002427 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002428#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429}
2430
Kate Stoneb9c1b512016-09-06 20:57:50 +00002431addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002432 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002433 addr_t return_addr = AllocateMemory(size, permissions, error);
2434 if (error.Success()) {
2435 std::string buffer(size, 0);
2436 WriteMemory(return_addr, buffer.c_str(), size, error);
2437 }
2438 return return_addr;
2439}
2440
2441bool Process::CanJIT() {
2442 if (m_can_jit == eCanJITDontKnow) {
2443 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002444 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002445
2446 uint64_t allocated_memory = AllocateMemory(
2447 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2448 err);
2449
2450 if (err.Success()) {
2451 m_can_jit = eCanJITYes;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002452 LLDB_LOGF(log,
2453 "Process::%s pid %" PRIu64
2454 " allocation test passed, CanJIT () is true",
2455 __FUNCTION__, GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002456 } else {
2457 m_can_jit = eCanJITNo;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002458 LLDB_LOGF(log,
2459 "Process::%s pid %" PRIu64
2460 " allocation test failed, CanJIT () is false: %s",
2461 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002462 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002463
2464 DeallocateMemory(allocated_memory);
2465 }
2466
2467 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002468}
2469
Kate Stoneb9c1b512016-09-06 20:57:50 +00002470void Process::SetCanJIT(bool can_jit) {
2471 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002472}
2473
Kate Stoneb9c1b512016-09-06 20:57:50 +00002474void Process::SetCanRunCode(bool can_run_code) {
2475 SetCanJIT(can_run_code);
2476 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002477}
2478
Zachary Turner97206d52017-05-12 04:51:55 +00002479Status Process::DeallocateMemory(addr_t ptr) {
2480 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002481#if defined(USE_ALLOCATE_MEMORY_CACHE)
2482 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2483 error.SetErrorStringWithFormat(
2484 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2485 }
Greg Claytond495c532011-05-17 03:37:42 +00002486#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002487 error = DoDeallocateMemory(ptr);
2488
2489 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002490 LLDB_LOGF(log,
2491 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2492 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2493 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2494 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002495#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002496 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002497}
2498
Kate Stoneb9c1b512016-09-06 20:57:50 +00002499ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2500 lldb::addr_t header_addr,
2501 size_t size_to_read) {
2502 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2503 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002504 LLDB_LOGF(log,
2505 "Process::ReadModuleFromMemory reading %s binary from memory",
2506 file_spec.GetPath().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002507 }
2508 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2509 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002510 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002511 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2512 shared_from_this(), header_addr, error, size_to_read);
2513 if (objfile)
2514 return module_sp;
2515 }
2516 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002517}
2518
Kate Stoneb9c1b512016-09-06 20:57:50 +00002519bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2520 uint32_t &permissions) {
2521 MemoryRegionInfo range_info;
2522 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002523 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002524 if (!error.Success())
2525 return false;
2526 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2527 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2528 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2529 return false;
2530 }
2531
2532 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2533 permissions |= lldb::ePermissionsReadable;
2534
2535 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2536 permissions |= lldb::ePermissionsWritable;
2537
2538 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2539 permissions |= lldb::ePermissionsExecutable;
2540
2541 return true;
2542}
2543
Zachary Turner97206d52017-05-12 04:51:55 +00002544Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2545 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002546 error.SetErrorString("watchpoints are not supported");
2547 return error;
2548}
2549
Zachary Turner97206d52017-05-12 04:51:55 +00002550Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2551 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552 error.SetErrorString("watchpoints are not supported");
2553 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002554}
2555
2556StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002557Process::WaitForProcessStopPrivate(EventSP &event_sp,
2558 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002559 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002560
Kate Stoneb9c1b512016-09-06 20:57:50 +00002561 while (true) {
2562 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002563 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002564
Kate Stoneb9c1b512016-09-06 20:57:50 +00002565 if (StateIsStoppedState(state, false))
2566 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002567
Kate Stoneb9c1b512016-09-06 20:57:50 +00002568 // If state is invalid, then we timed out
2569 if (state == eStateInvalid)
2570 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002571
Kate Stoneb9c1b512016-09-06 20:57:50 +00002572 if (event_sp)
2573 HandlePrivateEvent(event_sp);
2574 }
2575 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002576}
2577
Kate Stoneb9c1b512016-09-06 20:57:50 +00002578void Process::LoadOperatingSystemPlugin(bool flush) {
2579 if (flush)
2580 m_thread_list.Clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002581 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002582 if (flush)
2583 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002584}
2585
Zachary Turner97206d52017-05-12 04:51:55 +00002586Status Process::Launch(ProcessLaunchInfo &launch_info) {
2587 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002588 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002589 m_dyld_up.reset();
2590 m_jit_loaders_up.reset();
2591 m_system_runtime_up.reset();
2592 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002593 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002594
Kate Stoneb9c1b512016-09-06 20:57:50 +00002595 Module *exe_module = GetTarget().GetExecutableModulePointer();
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002596 if (!exe_module) {
2597 error.SetErrorString("executable module does not exist");
2598 return error;
2599 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002600
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002601 char local_exec_file_path[PATH_MAX];
2602 char platform_exec_file_path[PATH_MAX];
2603 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2604 sizeof(local_exec_file_path));
2605 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2606 sizeof(platform_exec_file_path));
2607 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2608 // Install anything that might need to be installed prior to launching.
2609 // For host systems, this will do nothing, but if we are connected to a
2610 // remote platform it will install any needed binaries
2611 error = GetTarget().Install(&launch_info);
2612 if (error.Fail())
2613 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002614
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002615 if (PrivateStateThreadIsValid())
2616 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002617
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002618 error = WillLaunch(exe_module);
2619 if (error.Success()) {
2620 const bool restarted = false;
2621 SetPublicState(eStateLaunching, restarted);
2622 m_should_detach = false;
2623
2624 if (m_public_run_lock.TrySetRunning()) {
2625 // Now launch using these arguments.
2626 error = DoLaunch(exe_module, launch_info);
2627 } else {
2628 // This shouldn't happen
2629 error.SetErrorString("failed to acquire process run lock");
2630 }
2631
2632 if (error.Fail()) {
2633 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2634 SetID(LLDB_INVALID_PROCESS_ID);
2635 const char *error_string = error.AsCString();
2636 if (error_string == nullptr)
2637 error_string = "launch failed";
2638 SetExitStatus(-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002639 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002640 } else {
2641 EventSP event_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002642
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002643 // Now wait for the process to launch and return control to us, and then
2644 // call DidLaunch:
2645 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Stella Stamenova36d457c2018-06-01 19:14:53 +00002646
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002647 if (state == eStateInvalid || !event_sp) {
2648 // We were able to launch the process, but we failed to catch the
2649 // initial stop.
2650 error.SetErrorString("failed to catch stop after launch");
2651 SetExitStatus(0, "failed to catch stop after launch");
2652 Destroy(false);
2653 } else if (state == eStateStopped || state == eStateCrashed) {
2654 DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002655
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002656 DynamicLoader *dyld = GetDynamicLoader();
2657 if (dyld)
2658 dyld->DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002659
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002660 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002661
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002662 SystemRuntime *system_runtime = GetSystemRuntime();
2663 if (system_runtime)
2664 system_runtime->DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002665
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002666 if (!m_os_up)
2667 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002668
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002669 // We successfully launched the process and stopped, now it the
2670 // right time to set up signal filters before resuming.
2671 UpdateAutomaticSignalFiltering();
Greg Clayton35824e32015-02-20 20:59:47 +00002672
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002673 // Note, the stop event was consumed above, but not handled. This
2674 // was done to give DidLaunch a chance to run. The target is either
2675 // stopped or crashed. Directly set the state. This is done to
2676 // prevent a stop message with a bunch of spurious output on thread
2677 // status, as well as not pop a ProcessIOHandler.
2678 SetPublicState(state, false);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002679
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002680 if (PrivateStateThreadIsValid())
2681 ResumePrivateStateThread();
2682 else
2683 StartPrivateStateThread();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002684
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002685 // Target was stopped at entry as was intended. Need to notify the
2686 // listeners about it.
2687 if (state == eStateStopped &&
2688 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002689 HandlePrivateEvent(event_sp);
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002690 } else if (state == eStateExited) {
2691 // We exited while trying to launch somehow. Don't call DidLaunch
2692 // as that's not likely to work, and return an invalid pid.
2693 HandlePrivateEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002694 }
2695 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002696 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002697 } else {
2698 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2699 local_exec_file_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002700 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002701
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002703}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002704
Zachary Turner97206d52017-05-12 04:51:55 +00002705Status Process::LoadCore() {
2706 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002707 if (error.Success()) {
2708 ListenerSP listener_sp(
2709 Listener::MakeListener("lldb.process.load_core_listener"));
2710 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002711
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712 if (PrivateStateThreadIsValid())
2713 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002714 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002715 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002716
Kate Stoneb9c1b512016-09-06 20:57:50 +00002717 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002718 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002719 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002720
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002721 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002722
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002724 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002725 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002726
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002727 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00002728 LoadOperatingSystemPlugin(false);
2729
Kate Stoneb9c1b512016-09-06 20:57:50 +00002730 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002731 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002732 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002733
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002734 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002735 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002736 StateType state =
Pavel Labath7ada1c52019-06-25 07:14:29 +00002737 WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002738
2739 if (!StateIsStoppedState(state, false)) {
2740 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002741 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2742 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002743 error.SetErrorString(
2744 "Did not get stopped event after loading the core file.");
2745 }
2746 RestoreProcessEvents();
2747 }
2748 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002749}
2750
Kate Stoneb9c1b512016-09-06 20:57:50 +00002751DynamicLoader *Process::GetDynamicLoader() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002752 if (!m_dyld_up)
2753 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2754 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002755}
2756
Antonio Afonso943faef2019-06-11 20:16:13 +00002757DataExtractor Process::GetAuxvData() { return DataExtractor(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002758
2759JITLoaderList &Process::GetJITLoaders() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002760 if (!m_jit_loaders_up) {
Jonas Devlieghere06412da2020-06-24 17:44:33 -07002761 m_jit_loaders_up = std::make_unique<JITLoaderList>();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002762 JITLoader::LoadPlugins(this, *m_jit_loaders_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002763 }
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002764 return *m_jit_loaders_up;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002765}
2766
2767SystemRuntime *Process::GetSystemRuntime() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002768 if (!m_system_runtime_up)
2769 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2770 return m_system_runtime_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002771}
2772
2773Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2774 uint32_t exec_count)
2775 : NextEventAction(process), m_exec_count(exec_count) {
2776 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002777 LLDB_LOGF(
2778 log,
2779 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2780 __FUNCTION__, static_cast<void *>(process), exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002781}
2782
2783Process::NextEventAction::EventActionResult
2784Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2785 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2786
2787 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002788 LLDB_LOGF(log,
2789 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2790 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791
2792 switch (state) {
2793 case eStateAttaching:
2794 return eEventActionSuccess;
2795
2796 case eStateRunning:
2797 case eStateConnected:
2798 return eEventActionRetry;
2799
2800 case eStateStopped:
2801 case eStateCrashed:
2802 // During attach, prior to sending the eStateStopped event,
2803 // lldb_private::Process subclasses must set the new process ID.
2804 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002805 // We don't want these events to be reported, so go set the
2806 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2808
2809 if (m_exec_count > 0) {
2810 --m_exec_count;
2811
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002812 LLDB_LOGF(log,
2813 "Process::AttachCompletionHandler::%s state %s: reduced "
2814 "remaining exec count to %" PRIu32 ", requesting resume",
2815 __FUNCTION__, StateAsCString(state), m_exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002816
2817 RequestResume();
2818 return eEventActionRetry;
2819 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002820 LLDB_LOGF(log,
2821 "Process::AttachCompletionHandler::%s state %s: no more "
2822 "execs expected to start, continuing with attach",
2823 __FUNCTION__, StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002824
2825 m_process->CompleteAttach();
2826 return eEventActionSuccess;
2827 }
2828 break;
2829
2830 default:
2831 case eStateExited:
2832 case eStateInvalid:
2833 break;
2834 }
2835
2836 m_exit_string.assign("No valid Process");
2837 return eEventActionExit;
2838}
2839
2840Process::NextEventAction::EventActionResult
2841Process::AttachCompletionHandler::HandleBeingInterrupted() {
2842 return eEventActionSuccess;
2843}
2844
2845const char *Process::AttachCompletionHandler::GetExitString() {
2846 return m_exit_string.c_str();
2847}
2848
2849ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2850 if (m_listener_sp)
2851 return m_listener_sp;
2852 else
2853 return debugger.GetListener();
2854}
2855
Zachary Turner97206d52017-05-12 04:51:55 +00002856Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002857 m_abi_sp.reset();
2858 m_process_input_reader.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002859 m_dyld_up.reset();
2860 m_jit_loaders_up.reset();
2861 m_system_runtime_up.reset();
2862 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002863
2864 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002865 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2867 char process_name[PATH_MAX];
2868
2869 if (attach_info.GetExecutableFile().GetPath(process_name,
2870 sizeof(process_name))) {
2871 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2872
2873 if (wait_for_launch) {
2874 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2875 if (error.Success()) {
2876 if (m_public_run_lock.TrySetRunning()) {
2877 m_should_detach = true;
2878 const bool restarted = false;
2879 SetPublicState(eStateAttaching, restarted);
2880 // Now attach using these arguments.
2881 error = DoAttachToProcessWithName(process_name, attach_info);
2882 } else {
2883 // This shouldn't happen
2884 error.SetErrorString("failed to acquire process run lock");
2885 }
2886
2887 if (error.Fail()) {
2888 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2889 SetID(LLDB_INVALID_PROCESS_ID);
2890 if (error.AsCString() == nullptr)
2891 error.SetErrorString("attach failed");
2892
2893 SetExitStatus(-1, error.AsCString());
2894 }
2895 } else {
2896 SetNextEventAction(new Process::AttachCompletionHandler(
2897 this, attach_info.GetResumeCount()));
2898 StartPrivateStateThread();
2899 }
2900 return error;
2901 }
2902 } else {
2903 ProcessInstanceInfoList process_infos;
2904 PlatformSP platform_sp(GetTarget().GetPlatform());
2905
2906 if (platform_sp) {
2907 ProcessInstanceInfoMatch match_info;
2908 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00002909 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002910 platform_sp->FindProcesses(match_info, process_infos);
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002911 const uint32_t num_matches = process_infos.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002912 if (num_matches == 1) {
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002913 attach_pid = process_infos[0].GetProcessID();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002914 // Fall through and attach using the above process ID
2915 } else {
2916 match_info.GetProcessInfo().GetExecutableFile().GetPath(
2917 process_name, sizeof(process_name));
2918 if (num_matches > 1) {
2919 StreamString s;
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002920 ProcessInstanceInfo::DumpTableHeader(s, true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921 for (size_t i = 0; i < num_matches; i++) {
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002922 process_infos[i].DumpAsTableRow(
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002923 s, platform_sp->GetUserIDResolver(), true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002924 }
2925 error.SetErrorStringWithFormat(
2926 "more than one process named %s:\n%s", process_name,
2927 s.GetData());
2928 } else
2929 error.SetErrorStringWithFormat(
2930 "could not find a process named %s", process_name);
2931 }
2932 } else {
2933 error.SetErrorString(
2934 "invalid platform, can't find processes by name");
2935 return error;
2936 }
2937 }
2938 } else {
2939 error.SetErrorString("invalid process name");
2940 }
2941 }
2942
2943 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2944 error = WillAttachToProcessWithID(attach_pid);
2945 if (error.Success()) {
2946
2947 if (m_public_run_lock.TrySetRunning()) {
2948 // Now attach using these arguments.
2949 m_should_detach = true;
2950 const bool restarted = false;
2951 SetPublicState(eStateAttaching, restarted);
2952 error = DoAttachToProcessWithID(attach_pid, attach_info);
2953 } else {
2954 // This shouldn't happen
2955 error.SetErrorString("failed to acquire process run lock");
2956 }
2957
2958 if (error.Success()) {
2959 SetNextEventAction(new Process::AttachCompletionHandler(
2960 this, attach_info.GetResumeCount()));
2961 StartPrivateStateThread();
2962 } else {
Greg Clayton71337622011-02-24 22:24:29 +00002963 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002965
Kate Stoneb9c1b512016-09-06 20:57:50 +00002966 const char *error_string = error.AsCString();
2967 if (error_string == nullptr)
2968 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00002969
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970 SetExitStatus(-1, error_string);
2971 }
Greg Claytonb766a732011-02-04 01:58:07 +00002972 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 }
2974 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00002975}
2976
Kate Stoneb9c1b512016-09-06 20:57:50 +00002977void Process::CompleteAttach() {
2978 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2979 LIBLLDB_LOG_TARGET));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002980 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002981
2982 // Let the process subclass figure out at much as it can about the process
2983 // before we go looking for a dynamic loader plug-in.
2984 ArchSpec process_arch;
2985 DidAttach(process_arch);
2986
2987 if (process_arch.IsValid()) {
2988 GetTarget().SetArchitecture(process_arch);
2989 if (log) {
2990 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002991 LLDB_LOGF(log,
2992 "Process::%s replacing process architecture with DidAttach() "
2993 "architecture: %s",
2994 __FUNCTION__, triple_str ? triple_str : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995 }
2996 }
2997
2998 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00002999 // architecture, and if it isn't the same as the one we've already set,
3000 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003001 PlatformSP platform_sp(GetTarget().GetPlatform());
3002 assert(platform_sp);
3003 if (platform_sp) {
3004 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3005 if (target_arch.IsValid() &&
3006 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3007 ArchSpec platform_arch;
3008 platform_sp =
3009 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3010 if (platform_sp) {
3011 GetTarget().SetPlatform(platform_sp);
3012 GetTarget().SetArchitecture(platform_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003013 LLDB_LOGF(log,
3014 "Process::%s switching platform to %s and architecture "
3015 "to %s based on info from attach",
3016 __FUNCTION__, platform_sp->GetName().AsCString(""),
3017 platform_arch.GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003018 }
3019 } else if (!process_arch.IsValid()) {
3020 ProcessInstanceInfo process_info;
3021 GetProcessInfo(process_info);
3022 const ArchSpec &process_arch = process_info.GetArchitecture();
3023 if (process_arch.IsValid() &&
3024 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3025 GetTarget().SetArchitecture(process_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003026 LLDB_LOGF(log,
3027 "Process::%s switching architecture to %s based on info "
3028 "the platform retrieved for pid %" PRIu64,
3029 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
3030 GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003031 }
3032 }
3033 }
3034
3035 // We have completed the attach, now it is time to find the dynamic loader
3036 // plug-in
3037 DynamicLoader *dyld = GetDynamicLoader();
3038 if (dyld) {
3039 dyld->DidAttach();
3040 if (log) {
3041 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003042 LLDB_LOGF(log,
3043 "Process::%s after DynamicLoader::DidAttach(), target "
3044 "executable is %s (using %s plugin)",
3045 __FUNCTION__,
3046 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3047 : "<none>",
3048 dyld->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003049 }
3050 }
3051
3052 GetJITLoaders().DidAttach();
3053
3054 SystemRuntime *system_runtime = GetSystemRuntime();
3055 if (system_runtime) {
3056 system_runtime->DidAttach();
3057 if (log) {
3058 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003059 LLDB_LOGF(log,
3060 "Process::%s after SystemRuntime::DidAttach(), target "
3061 "executable is %s (using %s plugin)",
3062 __FUNCTION__,
3063 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3064 : "<none>",
3065 system_runtime->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003066 }
3067 }
3068
Jim Ingham8864b432019-06-28 17:57:19 +00003069 if (!m_os_up) {
Greg Clayton29eeea02017-02-09 18:55:41 +00003070 LoadOperatingSystemPlugin(false);
Jim Ingham8864b432019-06-28 17:57:19 +00003071 if (m_os_up) {
3072 // Somebody might have gotten threads before now, but we need to force the
3073 // update after we've loaded the OperatingSystem plugin or it won't get a
3074 // chance to process the threads.
3075 m_thread_list.Clear();
3076 UpdateThreadListIfNeeded();
3077 }
3078 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003079 // Figure out which one is the executable, and set that in our target:
3080 const ModuleList &target_modules = GetTarget().GetImages();
3081 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3082 size_t num_modules = target_modules.GetSize();
3083 ModuleSP new_executable_module_sp;
3084
3085 for (size_t i = 0; i < num_modules; i++) {
3086 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3087 if (module_sp && module_sp->IsExecutable()) {
3088 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3089 new_executable_module_sp = module_sp;
3090 break;
3091 }
3092 }
3093 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00003094 GetTarget().SetExecutableModule(new_executable_module_sp,
3095 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096 if (log) {
3097 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003098 LLDB_LOGF(
3099 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003100 "Process::%s after looping through modules, target executable is %s",
3101 __FUNCTION__,
3102 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3103 : "<none>");
3104 }
3105 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003106}
3107
Jonas Devlieghere32d35fb2020-07-13 13:44:01 -07003108Status Process::ConnectRemote(llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003109 m_abi_sp.reset();
3110 m_process_input_reader.reset();
3111
3112 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003113 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003114
Jonas Devlieghere32d35fb2020-07-13 13:44:01 -07003115 Status error(DoConnectRemote(remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003116 if (error.Success()) {
3117 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3118 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003119 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120
3121 if (state == eStateStopped || state == eStateCrashed) {
3122 // If we attached and actually have a process on the other end, then
3123 // this ended up being the equivalent of an attach.
3124 CompleteAttach();
3125
3126 // This delays passing the stopped event to listeners till
3127 // CompleteAttach gets a chance to complete...
3128 HandlePrivateEvent(event_sp);
3129 }
3130 }
3131
3132 if (PrivateStateThreadIsValid())
3133 ResumePrivateStateThread();
3134 else
3135 StartPrivateStateThread();
3136 }
3137 return error;
3138}
3139
Zachary Turner97206d52017-05-12 04:51:55 +00003140Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003141 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3142 LIBLLDB_LOG_STEP));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003143 LLDB_LOGF(log,
3144 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3145 "private state: %s",
3146 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3147 StateAsCString(m_private_state.GetValue()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003148
Adrian Prantl05097242018-04-30 16:49:04 +00003149 // If signals handing status changed we might want to update our signal
3150 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003151 UpdateAutomaticSignalFiltering();
3152
Zachary Turner97206d52017-05-12 04:51:55 +00003153 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003154 // Tell the process it is about to resume before the thread list
3155 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003156 // Now let the thread list know we are about to resume so it can let all of
3157 // our threads know that they are about to be resumed. Threads will each be
3158 // called with Thread::WillResume(StateType) where StateType contains the
3159 // state that they are supposed to have when the process is resumed
3160 // (suspended/running/stepping). Threads should also check their resume
3161 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3162 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163 if (m_thread_list.WillResume()) {
3164 // Last thing, do the PreResumeActions.
3165 if (!RunPreResumeActions()) {
Jonas Devlieghere89533762020-07-20 22:57:06 -07003166 error.SetErrorString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003167 "Process::PrivateResume PreResumeActions failed, not resuming.");
3168 } else {
3169 m_mod_id.BumpResumeID();
3170 error = DoResume();
3171 if (error.Success()) {
3172 DidResume();
3173 m_thread_list.DidResume();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003174 LLDB_LOGF(log, "Process thinks the process has resumed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003175 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003176 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003177 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003178 }
3179 }
3180 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003181 // Somebody wanted to run without running (e.g. we were faking a step
3182 // from one frame of a set of inlined frames that share the same PC to
3183 // another.) So generate a continue & a stopped event, and let the world
3184 // handle them.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003185 LLDB_LOGF(log,
3186 "Process::PrivateResume() asked to simulate a start & stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003187
3188 SetPrivateState(eStateRunning);
3189 SetPrivateState(eStateStopped);
3190 }
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003191 } else
3192 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3193 error.AsCString("<unknown error>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003194 return error;
3195}
3196
Zachary Turner97206d52017-05-12 04:51:55 +00003197Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003198 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003199 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003200
Adrian Prantl05097242018-04-30 16:49:04 +00003201 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3202 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003203 m_clear_thread_plans_on_stop |= clear_thread_plans;
3204
3205 ListenerSP halt_listener_sp(
3206 Listener::MakeListener("lldb.process.halt_listener"));
3207 HijackProcessEvents(halt_listener_sp);
3208
3209 EventSP event_sp;
3210
3211 SendAsyncInterrupt();
3212
3213 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003214 // Don't hijack and eat the eStateExited as the code that was doing the
3215 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003216 RestoreProcessEvents();
3217 SetExitStatus(SIGKILL, "Cancelled async attach.");
3218 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003219 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003220 }
3221
3222 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003223 StateType state = WaitForProcessToStop(
3224 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003225 RestoreProcessEvents();
3226
3227 if (state == eStateInvalid || !event_sp) {
3228 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003229 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003230 }
3231
3232 BroadcastEvent(event_sp);
3233
Zachary Turner97206d52017-05-12 04:51:55 +00003234 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003235}
3236
Zachary Turner97206d52017-05-12 04:51:55 +00003237Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3238 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003239
3240 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003241 // expression, for instance, then the public state will be stopped, but we
3242 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003243 if (m_public_state.GetValue() == eStateRunning ||
3244 m_private_state.GetValue() == eStateRunning) {
3245 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003246 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003247
Kate Stoneb9c1b512016-09-06 20:57:50 +00003248 ListenerSP listener_sp(
3249 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3250 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003251
Pavel Labath19da1f12015-12-07 12:36:52 +00003252 SendAsyncInterrupt();
3253
Kate Stoneb9c1b512016-09-06 20:57:50 +00003254 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003255 StateType state =
3256 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003257
Pavel Labath19da1f12015-12-07 12:36:52 +00003258 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003259
Kate Stoneb9c1b512016-09-06 20:57:50 +00003260 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003261 // exited event into the shared pointer passed in and return. Our caller
3262 // doesn't need to do anything else, since they don't have a process
3263 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003264
3265 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003266 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3267 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003268 return error;
3269 } else
3270 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3271
3272 if (state != eStateStopped) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003273 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3274 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003275 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003276 // here, but if the lower levels just bobbled sending the event and we
3277 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003278 StateType private_state = m_private_state.GetValue();
3279 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003280 return Status(
3281 "Attempt to stop the target in order to detach timed out. "
3282 "State = %s",
3283 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003284 }
3285 }
3286 }
3287 return error;
3288}
3289
Zachary Turner97206d52017-05-12 04:51:55 +00003290Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003291 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003292 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003293 m_destroy_in_process = true;
3294
3295 error = WillDetach();
3296
3297 if (error.Success()) {
3298 if (DetachRequiresHalt()) {
3299 error = StopForDestroyOrDetach(exit_event_sp);
3300 if (!error.Success()) {
3301 m_destroy_in_process = false;
3302 return error;
3303 } else if (exit_event_sp) {
3304 // We shouldn't need to do anything else here. There's no process left
3305 // to detach from...
3306 StopPrivateStateThread();
3307 m_destroy_in_process = false;
3308 return error;
3309 }
3310 }
3311
3312 m_thread_list.DiscardThreadPlans();
3313 DisableAllBreakpointSites();
3314
3315 error = DoDetach(keep_stopped);
3316 if (error.Success()) {
3317 DidDetach();
3318 StopPrivateStateThread();
3319 } else {
3320 return error;
3321 }
3322 }
3323 m_destroy_in_process = false;
3324
Adrian Prantl05097242018-04-30 16:49:04 +00003325 // If we exited when we were waiting for a process to stop, then forward the
3326 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003327 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003328 // Directly broadcast our exited event because we shut down our private
3329 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003330 BroadcastEvent(exit_event_sp);
3331 }
3332
3333 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003334 // not end up propagating the last events through the event system, in which
3335 // case we might strand the write lock. Unlock it here so when we do to tear
3336 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003337
3338 m_public_run_lock.SetStopped();
3339 return error;
3340}
3341
Zachary Turner97206d52017-05-12 04:51:55 +00003342Status Process::Destroy(bool force_kill) {
Jim Ingham61e8e682020-03-10 16:18:11 -07003343 // If we've already called Process::Finalize then there's nothing useful to
3344 // be done here. Finalize has actually called Destroy already.
3345 if (m_finalize_called)
3346 return {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003347
3348 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003349 // don't do any unnecessary work that might hinder the destruction. Remember
3350 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003351 // failed and the process stays around for some reason it won't be in a
3352 // confused state.
3353
3354 if (force_kill)
3355 m_should_detach = false;
3356
3357 if (GetShouldDetach()) {
3358 // FIXME: This will have to be a process setting:
3359 bool keep_stopped = false;
3360 Detach(keep_stopped);
3361 }
3362
3363 m_destroy_in_process = true;
3364
Zachary Turner97206d52017-05-12 04:51:55 +00003365 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003366 if (error.Success()) {
3367 EventSP exit_event_sp;
3368 if (DestroyRequiresHalt()) {
3369 error = StopForDestroyOrDetach(exit_event_sp);
3370 }
3371
3372 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003373 // Ditch all thread plans, and remove all our breakpoints: in case we
3374 // have to restart the target to kill it, we don't want it hitting a
3375 // breakpoint... Only do this if we've stopped, however, since if we
3376 // didn't manage to halt it above, then we're not going to have much luck
3377 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003378 m_thread_list.DiscardThreadPlans();
3379 DisableAllBreakpointSites();
3380 }
3381
3382 error = DoDestroy();
3383 if (error.Success()) {
3384 DidDestroy();
3385 StopPrivateStateThread();
3386 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003387 m_stdio_communication.StopReadThread();
Pavel Labath93212552020-04-23 16:27:01 +02003388 m_stdio_communication.Disconnect();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003389 m_stdin_forward = false;
3390
3391 if (m_process_input_reader) {
3392 m_process_input_reader->SetIsDone(true);
3393 m_process_input_reader->Cancel();
3394 m_process_input_reader.reset();
3395 }
3396
Adrian Prantl05097242018-04-30 16:49:04 +00003397 // If we exited when we were waiting for a process to stop, then forward
3398 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003399 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003400 // Directly broadcast our exited event because we shut down our private
3401 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003402 BroadcastEvent(exit_event_sp);
3403 }
3404
Adrian Prantl05097242018-04-30 16:49:04 +00003405 // If we have been interrupted (to kill us) in the middle of running, we
3406 // may not end up propagating the last events through the event system, in
3407 // which case we might strand the write lock. Unlock it here so when we do
3408 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003409 m_public_run_lock.SetStopped();
3410 }
3411
3412 m_destroy_in_process = false;
3413
3414 return error;
3415}
3416
Zachary Turner97206d52017-05-12 04:51:55 +00003417Status Process::Signal(int signal) {
3418 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003419 if (error.Success()) {
3420 error = DoSignal(signal);
3421 if (error.Success())
3422 DidSignal();
3423 }
3424 return error;
3425}
3426
3427void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3428 assert(signals_sp && "null signals_sp");
3429 m_unix_signals_sp = signals_sp;
3430}
3431
3432const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3433 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3434 return m_unix_signals_sp;
3435}
3436
3437lldb::ByteOrder Process::GetByteOrder() const {
3438 return GetTarget().GetArchitecture().GetByteOrder();
3439}
3440
3441uint32_t Process::GetAddressByteSize() const {
3442 return GetTarget().GetArchitecture().GetAddressByteSize();
3443}
3444
3445bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3446 const StateType state =
3447 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3448 bool return_value = true;
3449 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3450 LIBLLDB_LOG_PROCESS));
3451
3452 switch (state) {
3453 case eStateDetached:
3454 case eStateExited:
3455 case eStateUnloaded:
3456 m_stdio_communication.SynchronizeWithReadThread();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003457 m_stdio_communication.StopReadThread();
Jonas Devlieghereb424b0b2020-04-22 16:51:56 -07003458 m_stdio_communication.Disconnect();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003459 m_stdin_forward = false;
3460
3461 LLVM_FALLTHROUGH;
3462 case eStateConnected:
3463 case eStateAttaching:
3464 case eStateLaunching:
3465 // These events indicate changes in the state of the debugging session,
3466 // always report them.
3467 return_value = true;
3468 break;
3469 case eStateInvalid:
3470 // We stopped for no apparent reason, don't report it.
3471 return_value = false;
3472 break;
3473 case eStateRunning:
3474 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003475 // If we've started the target running, we handle the cases where we are
3476 // already running and where there is a transition from stopped to running
3477 // differently. running -> running: Automatically suppress extra running
3478 // events stopped -> running: Report except when there is one or more no
3479 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003480 // and no yes votes.
3481 SynchronouslyNotifyStateChanged(state);
3482 if (m_force_next_event_delivery)
3483 return_value = true;
3484 else {
3485 switch (m_last_broadcast_state) {
3486 case eStateRunning:
3487 case eStateStepping:
3488 // We always suppress multiple runnings with no PUBLIC stop in between.
3489 return_value = false;
3490 break;
3491 default:
3492 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003493 // run if we aren't running so we don't miss any running events. If I
3494 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3495 // and hit the breakpoints on multiple threads, then somehow during the
3496 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003497
3498 // This is a transition from stop to run.
3499 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3500 case eVoteYes:
3501 case eVoteNoOpinion:
3502 return_value = true;
3503 break;
3504 case eVoteNo:
3505 return_value = false;
3506 break;
3507 }
3508 break;
3509 }
3510 }
3511 break;
3512 case eStateStopped:
3513 case eStateCrashed:
3514 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003515 // We've stopped. First see if we're going to restart the target. If we
3516 // are going to stop, then we always broadcast the event. If we aren't
3517 // going to stop, let the thread plans decide if we're going to report this
3518 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003519
3520 m_stdio_communication.SynchronizeWithReadThread();
3521 RefreshStateAfterStop();
3522 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003523 LLDB_LOGF(log,
3524 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3525 "interrupt, state: %s",
3526 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003527 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003528 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003529 m_thread_list.ShouldStop(event_ptr);
3530 return_value = true;
3531 } else {
3532 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3533 bool should_resume = false;
3534
3535 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003536 // restarted... Asking the thread list is also not likely to go well,
3537 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003538
3539 if (!was_restarted)
3540 should_resume = !m_thread_list.ShouldStop(event_ptr);
3541
3542 if (was_restarted || should_resume || m_resume_requested) {
3543 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003544 LLDB_LOGF(log,
3545 "Process::ShouldBroadcastEvent: should_resume: %i state: "
3546 "%s was_restarted: %i stop_vote: %d.",
3547 should_resume, StateAsCString(state), was_restarted,
3548 stop_vote);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003549
3550 switch (stop_vote) {
3551 case eVoteYes:
3552 return_value = true;
3553 break;
3554 case eVoteNoOpinion:
3555 case eVoteNo:
3556 return_value = false;
3557 break;
3558 }
3559
3560 if (!was_restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003561 LLDB_LOGF(log,
3562 "Process::ShouldBroadcastEvent (%p) Restarting process "
3563 "from state: %s",
3564 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003565 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3566 PrivateResume();
3567 }
3568 } else {
3569 return_value = true;
3570 SynchronouslyNotifyStateChanged(state);
3571 }
3572 }
3573 break;
3574 }
3575
3576 // Forcing the next event delivery is a one shot deal. So reset it here.
3577 m_force_next_event_delivery = false;
3578
3579 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003580 // events get coalesced.) But we only coalesce against events we actually
3581 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3582 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3583 // done, because the PublicState reflects the last event pulled off the
3584 // queue, and there may be several events stacked up on the queue unserviced.
3585 // So the PublicState may not reflect the last broadcasted event yet.
3586 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003587
3588 if (return_value)
3589 m_last_broadcast_state = state;
3590
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003591 LLDB_LOGF(log,
3592 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3593 "broadcast state: %s - %s",
3594 static_cast<void *>(event_ptr), StateAsCString(state),
3595 StateAsCString(m_last_broadcast_state),
3596 return_value ? "YES" : "NO");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003597 return return_value;
3598}
3599
3600bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3601 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3602
3603 bool already_running = PrivateStateThreadIsValid();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003604 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
3605 already_running ? " already running"
3606 : " starting private state thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003607
3608 if (!is_secondary_thread && already_running)
3609 return true;
3610
Adrian Prantl05097242018-04-30 16:49:04 +00003611 // Create a thread that watches our internal state and controls which events
3612 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003613 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003614 uint32_t max_len = llvm::get_max_thread_name_length();
3615 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003616 // On platforms with abbreviated thread name lengths, choose thread names
3617 // that fit within the limit.
3618 if (already_running)
3619 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3620 else
3621 snprintf(thread_name, sizeof(thread_name), "intern-state");
3622 } else {
3623 if (already_running)
3624 snprintf(thread_name, sizeof(thread_name),
3625 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3626 GetID());
3627 else
3628 snprintf(thread_name, sizeof(thread_name),
3629 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3630 }
3631
3632 // Create the private state thread, and start it running.
3633 PrivateStateThreadArgs *args_ptr =
3634 new PrivateStateThreadArgs(this, is_secondary_thread);
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003635 llvm::Expected<HostThread> private_state_thread =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003636 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003637 (void *)args_ptr, 8 * 1024 * 1024);
3638 if (!private_state_thread) {
3639 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3640 "failed to launch host thread: {}",
3641 llvm::toString(private_state_thread.takeError()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003642 return false;
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003643 }
3644
3645 assert(private_state_thread->IsJoinable());
3646 m_private_state_thread = *private_state_thread;
3647 ResumePrivateStateThread();
3648 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003649}
3650
3651void Process::PausePrivateStateThread() {
3652 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3653}
3654
3655void Process::ResumePrivateStateThread() {
3656 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3657}
3658
3659void Process::StopPrivateStateThread() {
3660 if (m_private_state_thread.IsJoinable())
3661 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3662 else {
3663 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003664 LLDB_LOGF(
3665 log,
3666 "Went to stop the private state thread, but it was already invalid.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003667 }
3668}
3669
3670void Process::ControlPrivateStateThread(uint32_t signal) {
3671 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3672
3673 assert(signal == eBroadcastInternalStateControlStop ||
3674 signal == eBroadcastInternalStateControlPause ||
3675 signal == eBroadcastInternalStateControlResume);
3676
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003677 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003678
3679 // Signal the private state thread
3680 if (m_private_state_thread.IsJoinable()) {
3681 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003682 // It is important to do this outside of the if below, because it's
3683 // possible that the thread state is invalid but that the thread is waiting
3684 // on a control event instead of simply being on its way out (this should
3685 // not happen, but it apparently can).
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003686 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003687 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3688 m_private_state_control_broadcaster.BroadcastEvent(signal,
3689 event_receipt_sp);
3690
3691 // Wait for the event receipt or for the private state thread to exit
3692 bool receipt_received = false;
3693 if (PrivateStateThreadIsValid()) {
3694 while (!receipt_received) {
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003695 // Check for a receipt for n seconds and then check if the private
Adrian Prantl05097242018-04-30 16:49:04 +00003696 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003697 receipt_received =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003698 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003699 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003700 // Check if the private state thread is still around. If it isn't
3701 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003702 if (!PrivateStateThreadIsValid())
3703 break; // Private state thread exited or is exiting, we are done
3704 }
3705 }
3706 }
3707
3708 if (signal == eBroadcastInternalStateControlStop) {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003709 thread_result_t result = {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003710 m_private_state_thread.Join(&result);
3711 m_private_state_thread.Reset();
3712 }
3713 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003714 LLDB_LOGF(
3715 log,
3716 "Private state thread already dead, no need to signal it to stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003717 }
3718}
3719
3720void Process::SendAsyncInterrupt() {
3721 if (PrivateStateThreadIsValid())
3722 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3723 nullptr);
3724 else
3725 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3726}
3727
3728void Process::HandlePrivateEvent(EventSP &event_sp) {
3729 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3730 m_resume_requested = false;
3731
3732 const StateType new_state =
3733 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3734
3735 // First check to see if anybody wants a shot at this event:
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003736 if (m_next_event_action_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003737 NextEventAction::EventActionResult action_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003738 m_next_event_action_up->PerformAction(event_sp);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003739 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003740
3741 switch (action_result) {
3742 case NextEventAction::eEventActionSuccess:
3743 SetNextEventAction(nullptr);
3744 break;
3745
3746 case NextEventAction::eEventActionRetry:
3747 break;
3748
3749 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003750 // Handle Exiting Here. If we already got an exited event, we should
3751 // just propagate it. Otherwise, swallow this event, and set our state
3752 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003753 if (new_state != eStateExited) {
3754 // FIXME: should cons up an exited event, and discard this one.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003755 SetExitStatus(0, m_next_event_action_up->GetExitString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003756 SetNextEventAction(nullptr);
3757 return;
3758 }
3759 SetNextEventAction(nullptr);
3760 break;
3761 }
3762 }
3763
3764 // See if we should broadcast this state to external clients?
3765 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3766
3767 if (should_broadcast) {
3768 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3769 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003770 LLDB_LOGF(log,
3771 "Process::%s (pid = %" PRIu64
3772 ") broadcasting new state %s (old state %s) to %s",
3773 __FUNCTION__, GetID(), StateAsCString(new_state),
3774 StateAsCString(GetState()),
3775 is_hijacked ? "hijacked" : "public");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003776 }
3777 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3778 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003779 // Only push the input handler if we aren't fowarding events, as this
3780 // means the curses GUI is in use... Or don't push it if we are launching
3781 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003782 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3783 new_state != eStateLaunching && new_state != eStateAttaching) {
3784 PushProcessIOHandler();
3785 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3786 eBroadcastAlways);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003787 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
3788 __FUNCTION__, m_iohandler_sync.GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003789 }
3790 } else if (StateIsStoppedState(new_state, false)) {
3791 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003792 // If the lldb_private::Debugger is handling the events, we don't want
3793 // to pop the process IOHandler here, we want to do it when we receive
3794 // the stopped event so we can carefully control when the process
3795 // IOHandler is popped because when we stop we want to display some
3796 // text stating how and why we stopped, then maybe some
3797 // process/thread/frame info, and then we want the "(lldb) " prompt to
3798 // show up. If we pop the process IOHandler here, then we will cause
3799 // the command interpreter to become the top IOHandler after the
3800 // process pops off and it will update its prompt right away... See the
3801 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003802 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3803 // Otherwise we end up getting overlapping "(lldb) " prompts and
3804 // garbled output.
3805 //
3806 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003807 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3808 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003809 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003810 // thread plans, or when commands want to run in synchronous mode and
3811 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003812 // that will hijack the events is a simple expression:
3813 //
3814 // (lldb) expr (int)puts("hello")
3815 //
3816 // This will cause the internal process state thread to resume and halt
3817 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3818 // events) and we do need the IO handler to be pushed and popped
3819 // correctly.
3820
3821 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3822 PopProcessIOHandler();
3823 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003824 }
3825
3826 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003827 } else {
3828 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003829 LLDB_LOGF(
3830 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003831 "Process::%s (pid = %" PRIu64
3832 ") suppressing state %s (old state %s): should_broadcast == false",
3833 __FUNCTION__, GetID(), StateAsCString(new_state),
3834 StateAsCString(GetState()));
3835 }
3836 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003837}
3838
Zachary Turner97206d52017-05-12 04:51:55 +00003839Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003840 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003841 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003842 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003843 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003844
3845 // Ask the process subclass to actually halt our process
3846 bool caused_stop;
3847 error = DoHalt(caused_stop);
3848
3849 DidHalt();
3850 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003851}
3852
Kate Stoneb9c1b512016-09-06 20:57:50 +00003853thread_result_t Process::PrivateStateThread(void *arg) {
3854 std::unique_ptr<PrivateStateThreadArgs> args_up(
3855 static_cast<PrivateStateThreadArgs *>(arg));
3856 thread_result_t result =
3857 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3858 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003859}
3860
Kate Stoneb9c1b512016-09-06 20:57:50 +00003861thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3862 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003863
Kate Stoneb9c1b512016-09-06 20:57:50 +00003864 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003865 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3866 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003867
Kate Stoneb9c1b512016-09-06 20:57:50 +00003868 bool exit_now = false;
3869 bool interrupt_requested = false;
3870 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003871 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003872 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003873 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003874 LLDB_LOGF(log,
3875 "Process::%s (arg = %p, pid = %" PRIu64
3876 ") got a control event: %d",
3877 __FUNCTION__, static_cast<void *>(this), GetID(),
3878 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003879
Kate Stoneb9c1b512016-09-06 20:57:50 +00003880 switch (event_sp->GetType()) {
3881 case eBroadcastInternalStateControlStop:
3882 exit_now = true;
3883 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003884
Kate Stoneb9c1b512016-09-06 20:57:50 +00003885 case eBroadcastInternalStateControlPause:
3886 control_only = true;
3887 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003888
Kate Stoneb9c1b512016-09-06 20:57:50 +00003889 case eBroadcastInternalStateControlResume:
3890 control_only = false;
3891 break;
3892 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003893
Kate Stoneb9c1b512016-09-06 20:57:50 +00003894 continue;
3895 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3896 if (m_public_state.GetValue() == eStateAttaching) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003897 LLDB_LOGF(log,
3898 "Process::%s (arg = %p, pid = %" PRIu64
3899 ") woke up with an interrupt while attaching - "
3900 "forwarding interrupt.",
3901 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003902 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3903 } else if (StateIsRunningState(m_last_broadcast_state)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003904 LLDB_LOGF(log,
3905 "Process::%s (arg = %p, pid = %" PRIu64
3906 ") woke up with an interrupt - Halting.",
3907 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00003908 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003909 if (error.Fail() && log)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003910 LLDB_LOGF(log,
3911 "Process::%s (arg = %p, pid = %" PRIu64
3912 ") failed to halt the process: %s",
3913 __FUNCTION__, static_cast<void *>(this), GetID(),
3914 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00003915 // Halt should generate a stopped event. Make a note of the fact that
3916 // we were doing the interrupt, so we can set the interrupted flag
3917 // after we receive the event. We deliberately set this to true even if
3918 // HaltPrivate failed, so that we can interrupt on the next natural
3919 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003920 interrupt_requested = true;
3921 } else {
3922 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00003923 // running and sends an interrupt request, but the process actually
3924 // stops before we receive it. In that case, we can just ignore the
3925 // request. We use m_last_broadcast_state, because the Stopped event
3926 // may not have been popped of the event queue yet, which is when the
3927 // public state gets updated.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003928 LLDB_LOGF(log,
3929 "Process::%s ignoring interrupt as we have already stopped.",
3930 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003931 }
3932 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003933 }
3934
Kate Stoneb9c1b512016-09-06 20:57:50 +00003935 const StateType internal_state =
3936 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003937
Kate Stoneb9c1b512016-09-06 20:57:50 +00003938 if (internal_state != eStateInvalid) {
3939 if (m_clear_thread_plans_on_stop &&
3940 StateIsStoppedState(internal_state, true)) {
3941 m_clear_thread_plans_on_stop = false;
3942 m_thread_list.DiscardThreadPlans();
3943 }
3944
3945 if (interrupt_requested) {
3946 if (StateIsStoppedState(internal_state, true)) {
3947 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00003948 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00003949 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3950 interrupt_requested = false;
3951 } else if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003952 LLDB_LOGF(log,
3953 "Process::%s interrupt_requested, but a non-stopped "
3954 "state '%s' received.",
3955 __FUNCTION__, StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003956 }
3957 }
3958
3959 HandlePrivateEvent(event_sp);
3960 }
3961
3962 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3963 internal_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003964 LLDB_LOGF(log,
3965 "Process::%s (arg = %p, pid = %" PRIu64
3966 ") about to exit with internal state %s...",
3967 __FUNCTION__, static_cast<void *>(this), GetID(),
3968 StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003969
3970 break;
3971 }
3972 }
3973
3974 // Verify log is still enabled before attempting to write to it...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003975 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3976 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003977
3978 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00003979 // will have already acquired the public_run_lock, and isn't done with what
3980 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003981 if (!is_secondary_thread)
3982 m_public_run_lock.SetStopped();
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003983 return {};
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003984}
3985
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003986// Process Event Data
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003987
Kate Stoneb9c1b512016-09-06 20:57:50 +00003988Process::ProcessEventData::ProcessEventData()
3989 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3990 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003991
Kate Stoneb9c1b512016-09-06 20:57:50 +00003992Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3993 StateType state)
3994 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3995 m_update_state(0), m_interrupted(false) {
3996 if (process_sp)
3997 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003998}
3999
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004000Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004001
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004002ConstString Process::ProcessEventData::GetFlavorString() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004003 static ConstString g_flavor("Process::ProcessEventData");
4004 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004005}
4006
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004007ConstString Process::ProcessEventData::GetFlavor() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004008 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004009}
4010
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004011bool Process::ProcessEventData::ShouldStop(Event *event_ptr,
4012 bool &found_valid_stopinfo) {
4013 found_valid_stopinfo = false;
4014
4015 ProcessSP process_sp(m_process_wp.lock());
4016 if (!process_sp)
4017 return false;
4018
4019 ThreadList &curr_thread_list = process_sp->GetThreadList();
4020 uint32_t num_threads = curr_thread_list.GetSize();
4021 uint32_t idx;
4022
4023 // The actions might change one of the thread's stop_info's opinions about
4024 // whether we should stop the process, so we need to query that as we go.
4025
4026 // One other complication here, is that we try to catch any case where the
4027 // target has run (except for expressions) and immediately exit, but if we
4028 // get that wrong (which is possible) then the thread list might have
4029 // changed, and that would cause our iteration here to crash. We could
4030 // make a copy of the thread list, but we'd really like to also know if it
4031 // has changed at all, so we make up a vector of the thread ID's and check
4032 // what we get back against this list & bag out if anything differs.
4033 ThreadList not_suspended_thread_list(process_sp.get());
4034 std::vector<uint32_t> thread_index_array(num_threads);
4035 uint32_t not_suspended_idx = 0;
4036 for (idx = 0; idx < num_threads; ++idx) {
4037 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4038
4039 /*
4040 Filter out all suspended threads, they could not be the reason
4041 of stop and no need to perform any actions on them.
4042 */
4043 if (thread_sp->GetResumeState() != eStateSuspended) {
4044 not_suspended_thread_list.AddThread(thread_sp);
4045 thread_index_array[not_suspended_idx] = thread_sp->GetIndexID();
4046 not_suspended_idx++;
4047 }
4048 }
4049
4050 // Use this to track whether we should continue from here. We will only
4051 // continue the target running if no thread says we should stop. Of course
4052 // if some thread's PerformAction actually sets the target running, then it
4053 // doesn't matter what the other threads say...
4054
4055 bool still_should_stop = false;
4056
4057 // Sometimes - for instance if we have a bug in the stub we are talking to,
4058 // we stop but no thread has a valid stop reason. In that case we should
4059 // just stop, because we have no way of telling what the right thing to do
4060 // is, and it's better to let the user decide than continue behind their
4061 // backs.
4062
4063 for (idx = 0; idx < not_suspended_thread_list.GetSize(); ++idx) {
4064 curr_thread_list = process_sp->GetThreadList();
4065 if (curr_thread_list.GetSize() != num_threads) {
4066 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4067 LIBLLDB_LOG_PROCESS));
4068 LLDB_LOGF(
4069 log,
4070 "Number of threads changed from %u to %u while processing event.",
4071 num_threads, curr_thread_list.GetSize());
4072 break;
4073 }
4074
4075 lldb::ThreadSP thread_sp = not_suspended_thread_list.GetThreadAtIndex(idx);
4076
4077 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4078 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4079 LIBLLDB_LOG_PROCESS));
4080 LLDB_LOGF(log,
4081 "The thread at position %u changed from %u to %u while "
4082 "processing event.",
4083 idx, thread_index_array[idx], thread_sp->GetIndexID());
4084 break;
4085 }
4086
4087 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4088 if (stop_info_sp && stop_info_sp->IsValid()) {
4089 found_valid_stopinfo = true;
4090 bool this_thread_wants_to_stop;
4091 if (stop_info_sp->GetOverrideShouldStop()) {
4092 this_thread_wants_to_stop =
4093 stop_info_sp->GetOverriddenShouldStopValue();
4094 } else {
4095 stop_info_sp->PerformAction(event_ptr);
4096 // The stop action might restart the target. If it does, then we
4097 // want to mark that in the event so that whoever is receiving it
4098 // will know to wait for the running event and reflect that state
4099 // appropriately. We also need to stop processing actions, since they
4100 // aren't expecting the target to be running.
4101
4102 // FIXME: we might have run.
4103 if (stop_info_sp->HasTargetRunSinceMe()) {
4104 SetRestarted(true);
4105 break;
4106 }
4107
4108 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4109 }
4110
4111 if (!still_should_stop)
4112 still_should_stop = this_thread_wants_to_stop;
4113 }
4114 }
4115
4116 return still_should_stop;
4117}
4118
Kate Stoneb9c1b512016-09-06 20:57:50 +00004119void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4120 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004121
Kate Stoneb9c1b512016-09-06 20:57:50 +00004122 if (!process_sp)
4123 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004124
Kate Stoneb9c1b512016-09-06 20:57:50 +00004125 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00004126 // pulled off of the private process event queue, and then any number of
4127 // times, first when it gets pulled off of the public event queue, then other
4128 // times when we're pretending that this is where we stopped at the end of
4129 // expression evaluation. m_update_state is used to distinguish these three
4130 // cases; it is 0 when we're just pulling it off for private handling, and >
4131 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00004132 // command handling then.
4133 if (m_update_state != 1)
4134 return;
4135
4136 process_sp->SetPublicState(
4137 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4138
Jason Molendab3a3cd12016-12-08 06:27:29 +00004139 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00004140 // Let process subclasses know we are about to do a public stop and do
4141 // anything they might need to in order to speed up register and memory
4142 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00004143 process_sp->WillPublicStop();
4144 }
4145
Kate Stoneb9c1b512016-09-06 20:57:50 +00004146 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00004147 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4148 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00004149 // end up restarting the process.
4150 if (m_interrupted)
4151 return;
4152
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004153 // If we're not stopped or have restarted, then skip the StopInfo actions:
4154 if (m_state != eStateStopped || m_restarted) {
4155 return;
4156 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004157
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004158 bool does_anybody_have_an_opinion = false;
4159 bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004160
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004161 if (GetRestarted()) {
4162 return;
4163 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004164
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004165 if (!still_should_stop && does_anybody_have_an_opinion) {
4166 // We've been asked to continue, so do that here.
4167 SetRestarted(true);
4168 // Use the public resume method here, since this is just extending a
4169 // public resume.
4170 process_sp->PrivateResume();
4171 } else {
4172 bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4173 !process_sp->StateChangedIsHijackedForSynchronousResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004174
Ilya Bukonkin3b43f002020-06-11 14:59:19 -07004175 if (!hijacked) {
4176 // If we didn't restart, run the Stop Hooks here.
4177 // Don't do that if state changed events aren't hooked up to the
4178 // public (or SyncResume) broadcasters. StopHooks are just for
4179 // real public stops. They might also restart the target,
4180 // so watch for that.
Jim Inghambe669872020-10-02 12:43:24 -07004181 if (process_sp->GetTarget().RunStopHooks())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004182 SetRestarted(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004183 }
4184 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004185}
4186
Kate Stoneb9c1b512016-09-06 20:57:50 +00004187void Process::ProcessEventData::Dump(Stream *s) const {
4188 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004189
Kate Stoneb9c1b512016-09-06 20:57:50 +00004190 if (process_sp)
4191 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4192 static_cast<void *>(process_sp.get()), process_sp->GetID());
4193 else
4194 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004195
Kate Stoneb9c1b512016-09-06 20:57:50 +00004196 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004197}
4198
4199const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004200Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4201 if (event_ptr) {
4202 const EventData *event_data = event_ptr->GetData();
4203 if (event_data &&
4204 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4205 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4206 }
4207 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004208}
4209
4210ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004211Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4212 ProcessSP process_sp;
4213 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4214 if (data)
4215 process_sp = data->GetProcessSP();
4216 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004217}
4218
Kate Stoneb9c1b512016-09-06 20:57:50 +00004219StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4220 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4221 if (data == nullptr)
4222 return eStateInvalid;
4223 else
4224 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004225}
4226
Kate Stoneb9c1b512016-09-06 20:57:50 +00004227bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4228 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4229 if (data == nullptr)
4230 return false;
4231 else
4232 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004233}
4234
Kate Stoneb9c1b512016-09-06 20:57:50 +00004235void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4236 bool new_value) {
4237 ProcessEventData *data =
4238 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4239 if (data != nullptr)
4240 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004241}
4242
Jim Ingham0161b492013-02-09 01:29:05 +00004243size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004244Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4245 ProcessEventData *data =
4246 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4247 if (data != nullptr)
4248 return data->GetNumRestartedReasons();
4249 else
4250 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004251}
4252
4253const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004254Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4255 size_t idx) {
4256 ProcessEventData *data =
4257 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4258 if (data != nullptr)
4259 return data->GetRestartedReasonAtIndex(idx);
4260 else
4261 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004262}
4263
Kate Stoneb9c1b512016-09-06 20:57:50 +00004264void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4265 const char *reason) {
4266 ProcessEventData *data =
4267 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4268 if (data != nullptr)
4269 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004270}
4271
Kate Stoneb9c1b512016-09-06 20:57:50 +00004272bool Process::ProcessEventData::GetInterruptedFromEvent(
4273 const Event *event_ptr) {
4274 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4275 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004276 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004277 else
4278 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004279}
4280
Kate Stoneb9c1b512016-09-06 20:57:50 +00004281void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4282 bool new_value) {
4283 ProcessEventData *data =
4284 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4285 if (data != nullptr)
4286 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004287}
4288
Kate Stoneb9c1b512016-09-06 20:57:50 +00004289bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4290 ProcessEventData *data =
4291 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4292 if (data) {
4293 data->SetUpdateStateOnRemoval();
4294 return true;
4295 }
4296 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004297}
4298
Jim Inghamb87b9e62018-06-26 23:38:58 +00004299lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004300
4301void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4302 exe_ctx.SetTargetPtr(&GetTarget());
4303 exe_ctx.SetProcessPtr(this);
4304 exe_ctx.SetThreadPtr(nullptr);
4305 exe_ctx.SetFramePtr(nullptr);
4306}
4307
4308// uint32_t
4309// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4310// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004311//{
4312// return 0;
4313//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004314//
4315// ArchSpec
4316// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004317//{
4318// return Host::GetArchSpecForExistingProcess (pid);
4319//}
4320//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004321// ArchSpec
4322// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004323//{
4324// return Host::GetArchSpecForExistingProcess (process_name);
4325//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004326
Kate Stoneb9c1b512016-09-06 20:57:50 +00004327void Process::AppendSTDOUT(const char *s, size_t len) {
4328 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4329 m_stdout_data.append(s, len);
4330 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4331 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004332}
4333
Kate Stoneb9c1b512016-09-06 20:57:50 +00004334void Process::AppendSTDERR(const char *s, size_t len) {
4335 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4336 m_stderr_data.append(s, len);
4337 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4338 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004339}
4340
Kate Stoneb9c1b512016-09-06 20:57:50 +00004341void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4342 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4343 m_profile_data.push_back(one_profile_data);
4344 BroadcastEventIfUnique(eBroadcastBitProfileData,
4345 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004346}
4347
Kate Stoneb9c1b512016-09-06 20:57:50 +00004348void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4349 const StructuredDataPluginSP &plugin_sp) {
4350 BroadcastEvent(
4351 eBroadcastBitStructuredData,
4352 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004353}
4354
4355StructuredDataPluginSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004356Process::GetStructuredDataPlugin(ConstString type_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004357 auto find_it = m_structured_data_plugin_map.find(type_name);
4358 if (find_it != m_structured_data_plugin_map.end())
4359 return find_it->second;
4360 else
4361 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004362}
4363
Zachary Turner97206d52017-05-12 04:51:55 +00004364size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004365 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4366 if (m_profile_data.empty())
4367 return 0;
4368
4369 std::string &one_profile_data = m_profile_data.front();
4370 size_t bytes_available = one_profile_data.size();
4371 if (bytes_available > 0) {
4372 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004373 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4374 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004375 if (bytes_available > buf_size) {
4376 memcpy(buf, one_profile_data.c_str(), buf_size);
4377 one_profile_data.erase(0, buf_size);
4378 bytes_available = buf_size;
4379 } else {
4380 memcpy(buf, one_profile_data.c_str(), bytes_available);
4381 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004382 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004383 }
4384 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004385}
4386
Greg Clayton93e86192011-11-13 04:45:22 +00004387// Process STDIO
Greg Clayton93e86192011-11-13 04:45:22 +00004388
Zachary Turner97206d52017-05-12 04:51:55 +00004389size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004390 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4391 size_t bytes_available = m_stdout_data.size();
4392 if (bytes_available > 0) {
4393 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004394 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4395 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004396 if (bytes_available > buf_size) {
4397 memcpy(buf, m_stdout_data.c_str(), buf_size);
4398 m_stdout_data.erase(0, buf_size);
4399 bytes_available = buf_size;
4400 } else {
4401 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4402 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004403 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004404 }
4405 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004406}
4407
Zachary Turner97206d52017-05-12 04:51:55 +00004408size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004409 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4410 size_t bytes_available = m_stderr_data.size();
4411 if (bytes_available > 0) {
4412 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004413 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4414 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004415 if (bytes_available > buf_size) {
4416 memcpy(buf, m_stderr_data.c_str(), buf_size);
4417 m_stderr_data.erase(0, buf_size);
4418 bytes_available = buf_size;
4419 } else {
4420 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4421 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004422 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004423 }
4424 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004425}
4426
Kate Stoneb9c1b512016-09-06 20:57:50 +00004427void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4428 size_t src_len) {
4429 Process *process = (Process *)baton;
4430 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004431}
4432
Kate Stoneb9c1b512016-09-06 20:57:50 +00004433class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004434public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004435 IOHandlerProcessSTDIO(Process *process, int write_fd)
4436 : IOHandler(process->GetTarget().GetDebugger(),
4437 IOHandler::Type::ProcessIO),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004438 m_process(process),
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00004439 m_read_file(GetInputFD(), File::eOpenOptionRead, false),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004440 m_write_file(write_fd, File::eOpenOptionWrite, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004441 m_pipe.CreateNew(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004442 }
4443
4444 ~IOHandlerProcessSTDIO() override = default;
4445
Adrian Prantl05097242018-04-30 16:49:04 +00004446 // Each IOHandler gets to run until it is done. It should read data from the
4447 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004448 void Run() override {
4449 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4450 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4451 SetIsDone(true);
4452 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004453 }
4454
Kate Stoneb9c1b512016-09-06 20:57:50 +00004455 SetIsDone(false);
4456 const int read_fd = m_read_file.GetDescriptor();
4457 TerminalState terminal_state;
4458 terminal_state.Save(read_fd, false);
4459 Terminal terminal(read_fd);
4460 terminal.SetCanonical(false);
4461 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004462// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004463#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004464 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4465 m_is_running = true;
4466 while (!GetIsDone()) {
4467 SelectHelper select_helper;
4468 select_helper.FDSetRead(read_fd);
4469 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004470 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004471
Kate Stoneb9c1b512016-09-06 20:57:50 +00004472 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004473 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004474 } else {
4475 char ch = 0;
4476 size_t n;
4477 if (select_helper.FDIsSetRead(read_fd)) {
4478 n = 1;
4479 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4480 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4481 SetIsDone(true);
4482 } else
4483 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004484 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004485 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4486 size_t bytes_read;
4487 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004488 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004489 if (error.Success()) {
4490 switch (ch) {
4491 case 'q':
4492 SetIsDone(true);
4493 break;
4494 case 'i':
4495 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004496 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004497 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004498 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004499 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004500 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004501 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004502 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004503 m_is_running = false;
4504#endif
4505 terminal_state.Restore();
4506 }
4507
4508 void Cancel() override {
4509 SetIsDone(true);
4510 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004511 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4512 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004513 //
4514 // (lldb) step_process_thousands_of_times
4515 //
4516 // In this case the command interpreter will be in the middle of handling
4517 // the command and if the process pushes and pops the IOHandler thousands
4518 // of times, we can end up writing to m_pipe without ever consuming the
4519 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4520 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4521 if (m_is_running) {
4522 char ch = 'q'; // Send 'q' for quit
4523 size_t bytes_written = 0;
4524 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004525 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004526 }
4527
4528 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004529 // Do only things that are safe to do in an interrupt context (like in a
4530 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004531 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4532 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004533 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004534 if (m_active) {
4535 char ch = 'i'; // Send 'i' for interrupt
4536 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004537 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004538 return result.Success();
4539 } else {
4540 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004541 // currently so do the right thing if we aren't actively watching for
4542 // STDIN by sending the interrupt to the process. Otherwise the write to
4543 // the pipe above would do nothing. This can happen when the command
4544 // interpreter is running and gets a "expression ...". It will be on the
4545 // IOHandler thread and sending the input is complete to the delegate
4546 // which will cause the expression to run, which will push the process IO
4547 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004548
4549 if (StateIsRunningState(m_process->GetState())) {
4550 m_process->SendAsyncInterrupt();
4551 return true;
4552 }
4553 }
4554 return false;
4555 }
4556
4557 void GotEOF() override {}
4558
Greg Clayton44d93782014-01-27 23:43:24 +00004559protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004560 Process *m_process;
Lawrence D'Annaf913fd62019-10-03 04:31:46 +00004561 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
4562 NativeFile m_write_file; // Write to this file (usually the master pty for
4563 // getting io to debuggee)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004564 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004565 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004566};
4567
Kate Stoneb9c1b512016-09-06 20:57:50 +00004568void Process::SetSTDIOFileDescriptor(int fd) {
4569 // First set up the Read Thread for reading/handling process I/O
Pavel Labath451741a2020-04-02 14:40:59 +02004570 m_stdio_communication.SetConnection(
4571 std::make_unique<ConnectionFileDescriptor>(fd, true));
4572 if (m_stdio_communication.IsConnected()) {
4573 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4574 STDIOReadThreadBytesReceived, this);
4575 m_stdio_communication.StartReadThread();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004576
Pavel Labath451741a2020-04-02 14:40:59 +02004577 // Now read thread is set up, set up input reader.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004578
Pavel Labath451741a2020-04-02 14:40:59 +02004579 if (!m_process_input_reader)
4580 m_process_input_reader =
4581 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004582 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004583}
4584
Kate Stoneb9c1b512016-09-06 20:57:50 +00004585bool Process::ProcessIOHandlerIsActive() {
4586 IOHandlerSP io_handler_sp(m_process_input_reader);
4587 if (io_handler_sp)
4588 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4589 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004590}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004591bool Process::PushProcessIOHandler() {
4592 IOHandlerSP io_handler_sp(m_process_input_reader);
4593 if (io_handler_sp) {
4594 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004595 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004596
Kate Stoneb9c1b512016-09-06 20:57:50 +00004597 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004598 // If we evaluate an utility function, then we don't cancel the current
4599 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4600 // existing IOHandler that potentially provides the user interface (e.g.
4601 // the IOHandler for Editline).
4602 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004603 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
4604 cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004605 return true;
4606 }
4607 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004608}
4609
Kate Stoneb9c1b512016-09-06 20:57:50 +00004610bool Process::PopProcessIOHandler() {
4611 IOHandlerSP io_handler_sp(m_process_input_reader);
4612 if (io_handler_sp)
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004613 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004614 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004615}
4616
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004617// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004618void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004619
Kate Stoneb9c1b512016-09-06 20:57:50 +00004620void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004621
Kate Stoneb9c1b512016-09-06 20:57:50 +00004622namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004623// RestorePlanState is used to record the "is private", "is master" and "okay
4624// to discard" fields of the plan we are running, and reset it on Clean or on
4625// destruction. It will only reset the state once, so you can call Clean and
4626// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004627
Kate Stoneb9c1b512016-09-06 20:57:50 +00004628class RestorePlanState {
4629public:
4630 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4631 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4632 if (m_thread_plan_sp) {
4633 m_private = m_thread_plan_sp->GetPrivate();
4634 m_is_master = m_thread_plan_sp->IsMasterPlan();
4635 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4636 }
4637 }
4638
4639 ~RestorePlanState() { Clean(); }
4640
4641 void Clean() {
4642 if (!m_already_reset && m_thread_plan_sp) {
4643 m_already_reset = true;
4644 m_thread_plan_sp->SetPrivate(m_private);
4645 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4646 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4647 }
4648 }
4649
4650private:
4651 lldb::ThreadPlanSP m_thread_plan_sp;
4652 bool m_already_reset;
4653 bool m_private;
4654 bool m_is_master;
4655 bool m_okay_to_discard;
4656};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004657} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004658
Pavel Labath2ce22162016-12-01 10:57:30 +00004659static microseconds
4660GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4661 const milliseconds default_one_thread_timeout(250);
4662
4663 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004664 if (!options.GetTimeout()) {
4665 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4666 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004667 }
4668
4669 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004670 if (options.GetOneThreadTimeout())
4671 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004672
4673 // Otherwise use half the total timeout, bounded by the
4674 // default_one_thread_timeout.
4675 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004676 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004677}
4678
4679static Timeout<std::micro>
4680GetExpressionTimeout(const EvaluateExpressionOptions &options,
4681 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004682 // If we are going to run all threads the whole time, or if we are only going
4683 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004684 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004685 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004686
4687 if (before_first_timeout)
4688 return GetOneThreadExpressionTimeout(options);
4689
Pavel Labath43d35412016-12-06 11:24:51 +00004690 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004691 return llvm::None;
4692 else
Pavel Labath43d35412016-12-06 11:24:51 +00004693 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004694}
4695
Pavel Labath45dde232017-05-25 10:50:06 +00004696static llvm::Optional<ExpressionResults>
Jim Inghamdbbed972020-05-20 18:00:56 -07004697HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
Pavel Labath45dde232017-05-25 10:50:06 +00004698 RestorePlanState &restorer, const EventSP &event_sp,
4699 EventSP &event_to_broadcast_sp,
Jim Inghamdbbed972020-05-20 18:00:56 -07004700 const EvaluateExpressionOptions &options,
4701 bool handle_interrupts) {
Pavel Labath45dde232017-05-25 10:50:06 +00004702 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4703
Jim Inghamdbbed972020-05-20 18:00:56 -07004704 ThreadSP thread_sp = thread_plan_sp->GetTarget()
4705 .GetProcessSP()
4706 ->GetThreadList()
4707 .FindThreadByID(thread_id);
4708 if (!thread_sp) {
4709 LLDB_LOG(log,
4710 "The thread on which we were running the "
4711 "expression: tid = {0}, exited while "
4712 "the expression was running.",
4713 thread_id);
4714 return eExpressionThreadVanished;
4715 }
4716
4717 ThreadPlanSP plan = thread_sp->GetCompletedPlan();
Pavel Labath45dde232017-05-25 10:50:06 +00004718 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4719 LLDB_LOG(log, "execution completed successfully");
4720
4721 // Restore the plan state so it will get reported as intended when we are
4722 // done.
4723 restorer.Clean();
4724 return eExpressionCompleted;
4725 }
4726
Jim Inghamdbbed972020-05-20 18:00:56 -07004727 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Pavel Labath45dde232017-05-25 10:50:06 +00004728 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4729 stop_info_sp->ShouldNotify(event_sp.get())) {
4730 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4731 if (!options.DoesIgnoreBreakpoints()) {
4732 // Restore the plan state and then force Private to false. We are going
4733 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004734 // it won't report correctly when we continue to its termination later
4735 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004736 restorer.Clean();
4737 thread_plan_sp->SetPrivate(false);
4738 event_to_broadcast_sp = event_sp;
4739 }
4740 return eExpressionHitBreakpoint;
4741 }
4742
4743 if (!handle_interrupts &&
4744 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4745 return llvm::None;
4746
4747 LLDB_LOG(log, "thread plan did not successfully complete");
4748 if (!options.DoesUnwindOnError())
4749 event_to_broadcast_sp = event_sp;
4750 return eExpressionInterrupted;
4751}
4752
Jim Ingham1624a2d2014-05-05 02:26:40 +00004753ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004754Process::RunThreadPlan(ExecutionContext &exe_ctx,
4755 lldb::ThreadPlanSP &thread_plan_sp,
4756 const EvaluateExpressionOptions &options,
4757 DiagnosticManager &diagnostic_manager) {
4758 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004759
Kate Stoneb9c1b512016-09-06 20:57:50 +00004760 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4761
4762 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004763 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004764 eDiagnosticSeverityError,
4765 "RunThreadPlan called with empty thread plan.");
4766 return eExpressionSetupError;
4767 }
4768
4769 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004770 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004771 eDiagnosticSeverityError,
4772 "RunThreadPlan called with an invalid thread plan.");
4773 return eExpressionSetupError;
4774 }
4775
4776 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004777 diagnostic_manager.PutString(eDiagnosticSeverityError,
4778 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004779 return eExpressionSetupError;
4780 }
4781
4782 Thread *thread = exe_ctx.GetThreadPtr();
4783 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004784 diagnostic_manager.PutString(eDiagnosticSeverityError,
4785 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004786 return eExpressionSetupError;
4787 }
4788
Jim Inghamdbbed972020-05-20 18:00:56 -07004789 // Record the thread's id so we can tell when a thread we were using
4790 // to run the expression exits during the expression evaluation.
4791 lldb::tid_t expr_thread_id = thread->GetID();
4792
Kate Stoneb9c1b512016-09-06 20:57:50 +00004793 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004794 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004795
4796 RestorePlanState thread_plan_restorer(thread_plan_sp);
4797
Adrian Prantl05097242018-04-30 16:49:04 +00004798 // We rely on the thread plan we are running returning "PlanCompleted" if
4799 // when it successfully completes. For that to be true the plan can't be
4800 // private - since private plans suppress themselves in the GetCompletedPlan
4801 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004802
4803 thread_plan_sp->SetPrivate(false);
4804
4805 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004806 // when they are done we will end up asking the plan above us whether we
4807 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004808
4809 thread_plan_sp->SetIsMasterPlan(true);
4810 thread_plan_sp->SetOkayToDiscard(false);
4811
Raphael Isemannc01783a2018-08-29 22:50:54 +00004812 // If we are running some utility expression for LLDB, we now have to mark
4813 // this in the ProcesModID of this process. This RAII takes care of marking
4814 // and reverting the mark it once we are done running the expression.
4815 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4816
Kate Stoneb9c1b512016-09-06 20:57:50 +00004817 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004818 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004819 eDiagnosticSeverityError,
4820 "RunThreadPlan called while the private state was not stopped.");
4821 return eExpressionSetupError;
4822 }
4823
4824 // Save the thread & frame from the exe_ctx for restoration after we run
4825 const uint32_t thread_idx_id = thread->GetIndexID();
4826 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4827 if (!selected_frame_sp) {
4828 thread->SetSelectedFrame(nullptr);
4829 selected_frame_sp = thread->GetSelectedFrame();
4830 if (!selected_frame_sp) {
4831 diagnostic_manager.Printf(
4832 eDiagnosticSeverityError,
4833 "RunThreadPlan called without a selected frame on thread %d",
4834 thread_idx_id);
4835 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004836 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004837 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004838
Adrian Prantl05097242018-04-30 16:49:04 +00004839 // Make sure the timeout values make sense. The one thread timeout needs to
4840 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004841 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4842 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004843 diagnostic_manager.PutString(eDiagnosticSeverityError,
4844 "RunThreadPlan called with one thread "
4845 "timeout greater than total timeout");
4846 return eExpressionSetupError;
4847 }
4848
Kate Stoneb9c1b512016-09-06 20:57:50 +00004849 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004850
Kate Stoneb9c1b512016-09-06 20:57:50 +00004851 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004852 // We don't want to do that either, so we should arrange to reset them as
4853 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004854
Kate Stoneb9c1b512016-09-06 20:57:50 +00004855 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004856
Kate Stoneb9c1b512016-09-06 20:57:50 +00004857 uint32_t selected_tid;
4858 StackID selected_stack_id;
4859 if (selected_thread_sp) {
4860 selected_tid = selected_thread_sp->GetIndexID();
4861 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4862 } else {
4863 selected_tid = LLDB_INVALID_THREAD_ID;
4864 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004865
Kate Stoneb9c1b512016-09-06 20:57:50 +00004866 HostThread backup_private_state_thread;
4867 lldb::StateType old_state = eStateInvalid;
4868 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004869
Kate Stoneb9c1b512016-09-06 20:57:50 +00004870 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4871 LIBLLDB_LOG_PROCESS));
4872 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4873 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004874 // public events on this thread, since we are the thread that is generating
4875 // public events. The simplest thing to do is to spin up a temporary thread
4876 // to handle private state thread events while we are fielding public
4877 // events here.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004878 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4879 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004880
Kate Stoneb9c1b512016-09-06 20:57:50 +00004881 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004882
Kate Stoneb9c1b512016-09-06 20:57:50 +00004883 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004884 // anything it pushes, and then stop, returning control here. But in the
4885 // normal course of things, the plan above us on the stack would be given a
4886 // shot at the stop event before deciding to stop, and we don't want that.
4887 // So we insert a "stopper" base plan on the stack before the plan we want
4888 // to run. Since base plans always stop and return control to the user,
4889 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004890 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4891 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4892 // Have to make sure our public state is stopped, since otherwise the
4893 // reporting logic below doesn't work correctly.
4894 old_state = m_public_state.GetValue();
4895 m_public_state.SetValueNoLock(eStateStopped);
4896
4897 // Now spin up the private state thread:
4898 StartPrivateStateThread(true);
4899 }
4900
4901 thread->QueueThreadPlan(
4902 thread_plan_sp, false); // This used to pass "true" does that make sense?
4903
4904 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004905 // In this case, we aren't actually going to run, we just want to stop
4906 // right away. Flush this thread so we will refetch the stacks and show the
4907 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004908 // FIXME: To make this prettier we should invent some stop reason for this,
4909 // but that
4910 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004911 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004912 thread->Flush();
4913 return eExpressionStoppedForDebug;
4914 }
4915
4916 ListenerSP listener_sp(
4917 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4918
4919 lldb::EventSP event_to_broadcast_sp;
4920
4921 {
4922 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004923 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004924 //
4925 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004926 // exits during execution), then the event is put into
4927 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004928
4929 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4930
4931 if (log) {
4932 StreamString s;
4933 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004934 LLDB_LOGF(log,
4935 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4936 " to run thread plan \"%s\".",
Jim Inghamdbbed972020-05-20 18:00:56 -07004937 thread_idx_id, expr_thread_id, s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004938 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004939
4940 bool got_event;
4941 lldb::EventSP event_sp;
4942 lldb::StateType stop_state = lldb::eStateInvalid;
4943
4944 bool before_first_timeout = true; // This is set to false the first time
4945 // that we have to halt the target.
4946 bool do_resume = true;
4947 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004948
4949 // This is just for accounting:
4950 uint32_t num_resumes = 0;
4951
Kate Stoneb9c1b512016-09-06 20:57:50 +00004952 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00004953 // going to run one thread, then we don't need the first timeout. So we
4954 // pretend we are after the first timeout already.
4955 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004956 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00004957
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004958 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4959 options.GetStopOthers(), options.GetTryAllThreads(),
4960 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004961
Adrian Prantl05097242018-04-30 16:49:04 +00004962 // This isn't going to work if there are unfetched events on the queue. Are
4963 // there cases where we might want to run the remaining events here, and
4964 // then try to call the function? That's probably being too tricky for our
4965 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004966
4967 Event *other_events = listener_sp->PeekAtNextEvent();
4968 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004969 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004970 eDiagnosticSeverityError,
4971 "RunThreadPlan called with pending events on the queue.");
4972 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00004973 }
4974
Kate Stoneb9c1b512016-09-06 20:57:50 +00004975 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00004976 // calling a function as part of a thread plan, in which case the last
4977 // delivered event could be the running event, and we don't want event
4978 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004979 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00004980
Kate Stoneb9c1b512016-09-06 20:57:50 +00004981// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00004982// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00004983
Kate Stoneb9c1b512016-09-06 20:57:50 +00004984#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00004985 // It's pretty much impossible to write test cases for things like: One
4986 // thread timeout expires, I go to halt, but the process already stopped on
4987 // the function call stop breakpoint. Turning on this define will make us
4988 // not fetch the first event till after the halt. So if you run a quick
4989 // function, it will have completed, and the completion event will be
4990 // waiting, when you interrupt for halt. The expression evaluation should
4991 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004992 bool miss_first_event = true;
4993#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00004994 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00004995 // We usually want to resume the process if we get to the top of the
4996 // loop. The only exception is if we get two running events with no
4997 // intervening stop, which can happen, we will just wait for then next
4998 // stop event.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004999 LLDB_LOGF(log,
5000 "Top of while loop: do_resume: %i handle_running_event: %i "
5001 "before_first_timeout: %i.",
5002 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00005003
Kate Stoneb9c1b512016-09-06 20:57:50 +00005004 if (do_resume || handle_running_event) {
5005 // Do the initial resume and wait for the running event before going
5006 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00005007
Kate Stoneb9c1b512016-09-06 20:57:50 +00005008 if (do_resume) {
5009 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00005010 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005011 if (!resume_error.Success()) {
5012 diagnostic_manager.Printf(
5013 eDiagnosticSeverityError,
5014 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5015 resume_error.AsCString());
5016 return_value = eExpressionSetupError;
5017 break;
5018 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005019 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005020
Pavel Labathd35031e12016-11-30 10:41:42 +00005021 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00005022 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005023 if (!got_event) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005024 LLDB_LOGF(log,
5025 "Process::RunThreadPlan(): didn't get any event after "
5026 "resume %" PRIu32 ", exiting.",
5027 num_resumes);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005028
5029 diagnostic_manager.Printf(eDiagnosticSeverityError,
5030 "didn't get any event after resume %" PRIu32
5031 ", exiting.",
5032 num_resumes);
5033 return_value = eExpressionSetupError;
5034 break;
5035 }
5036
5037 stop_state =
5038 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5039
5040 if (stop_state != eStateRunning) {
5041 bool restarted = false;
5042
5043 if (stop_state == eStateStopped) {
5044 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5045 event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005046 LLDB_LOGF(
5047 log,
5048 "Process::RunThreadPlan(): didn't get running event after "
5049 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5050 "handle_running_event: %i).",
5051 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5052 handle_running_event);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005053 }
5054
5055 if (restarted) {
5056 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00005057 // should ever get a stopped & restarted event here. But if I do,
5058 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005059 const bool clear_thread_plans = false;
5060 const bool use_run_lock = false;
5061 Halt(clear_thread_plans, use_run_lock);
5062 }
5063
5064 diagnostic_manager.Printf(
5065 eDiagnosticSeverityError,
5066 "didn't get running event after initial resume, got %s instead.",
5067 StateAsCString(stop_state));
5068 return_value = eExpressionSetupError;
5069 break;
5070 }
5071
5072 if (log)
5073 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00005074 // We need to call the function synchronously, so spin waiting for it
5075 // to return. If we get interrupted while executing, we're going to
5076 // lose our context, and won't be able to gather the result at this
5077 // point. We set the timeout AFTER the resume, since the resume takes
5078 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005079 } else {
5080 if (log)
5081 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5082 }
5083
Kate Stoneb9c1b512016-09-06 20:57:50 +00005084 do_resume = true;
5085 handle_running_event = true;
5086
5087 // Now wait for the process to stop again:
5088 event_sp.reset();
5089
Pavel Labath2ce22162016-12-01 10:57:30 +00005090 Timeout<std::micro> timeout =
5091 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005092 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005093 if (timeout) {
5094 auto now = system_clock::now();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005095 LLDB_LOGF(log,
5096 "Process::RunThreadPlan(): about to wait - now is %s - "
5097 "endpoint is %s",
5098 llvm::to_string(now).c_str(),
5099 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005100 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005101 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005102 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005103 }
5104
5105#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5106 // See comment above...
5107 if (miss_first_event) {
Pavel Labath3d4f7652019-08-05 08:23:25 +00005108 std::this_thread::sleep_for(std::chrono::milliseconds(1));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005109 miss_first_event = false;
5110 got_event = false;
5111 } else
5112#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005113 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005114
5115 if (got_event) {
5116 if (event_sp) {
5117 bool keep_going = false;
5118 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5119 const bool clear_thread_plans = false;
5120 const bool use_run_lock = false;
5121 Halt(clear_thread_plans, use_run_lock);
5122 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005123 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5124 "execution halted by user interrupt.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005125 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
5126 "eBroadcastBitInterrupted, exiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005127 break;
5128 } else {
5129 stop_state =
5130 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005131 LLDB_LOGF(log,
5132 "Process::RunThreadPlan(): in while loop, got event: %s.",
5133 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005134
5135 switch (stop_state) {
5136 case lldb::eStateStopped: {
Jim Inghamdbbed972020-05-20 18:00:56 -07005137 if (Process::ProcessEventData::GetRestartedFromEvent(
5138 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005139 // If we were restarted, we just need to go back up to fetch
5140 // another event.
Jim Inghamdbbed972020-05-20 18:00:56 -07005141 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5142 "restart, so we'll continue waiting.");
Pavel Labath45dde232017-05-25 10:50:06 +00005143 keep_going = true;
5144 do_resume = false;
5145 handle_running_event = true;
5146 } else {
5147 const bool handle_interrupts = true;
5148 return_value = *HandleStoppedEvent(
Jim Inghamdbbed972020-05-20 18:00:56 -07005149 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5150 event_sp, event_to_broadcast_sp, options,
5151 handle_interrupts);
5152 if (return_value == eExpressionThreadVanished)
5153 keep_going = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005154 }
5155 } break;
5156
5157 case lldb::eStateRunning:
5158 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005159 // running events without an intervening stop, and in that case
5160 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005161 do_resume = false;
5162 keep_going = true;
5163 handle_running_event = false;
5164 break;
5165
5166 default:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005167 LLDB_LOGF(log,
5168 "Process::RunThreadPlan(): execution stopped with "
5169 "unexpected state: %s.",
5170 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005171
5172 if (stop_state == eStateExited)
5173 event_to_broadcast_sp = event_sp;
5174
Zachary Turnere2411fa2016-11-12 19:12:56 +00005175 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005176 eDiagnosticSeverityError,
5177 "execution stopped with unexpected state.");
5178 return_value = eExpressionInterrupted;
5179 break;
5180 }
5181 }
5182
5183 if (keep_going)
5184 continue;
5185 else
5186 break;
5187 } else {
5188 if (log)
5189 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5190 "the event pointer was null. How odd...");
5191 return_value = eExpressionInterrupted;
5192 break;
5193 }
5194 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005195 // If we didn't get an event that means we've timed out... We will
5196 // interrupt the process here. Depending on what we were asked to do
5197 // we will either exit, or try with all threads running for the same
5198 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005199
5200 if (log) {
5201 if (options.GetTryAllThreads()) {
5202 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005203 LLDB_LOG(log,
5204 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005205 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005206 LLDB_LOG(log, "Restarting function with all threads enabled and "
5207 "timeout: {0} timed out, abandoning execution.",
5208 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005209 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005210 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5211 "abandoning execution.",
5212 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005213 }
5214
5215 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005216 // around to calling Halt the target could have stopped. That's fine,
5217 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005218 // BUT it is also possible that we stopped & restarted (e.g. hit a
5219 // signal with "stop" set to false.) In
5220 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005221 // back to waiting for the Halt's stopped event. That's what this
5222 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005223
5224 bool back_to_top = true;
5225 uint32_t try_halt_again = 0;
5226 bool do_halt = true;
5227 const uint32_t num_retries = 5;
5228 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005229 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005230 if (do_halt) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005231 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005232 const bool clear_thread_plans = false;
5233 const bool use_run_lock = false;
5234 Halt(clear_thread_plans, use_run_lock);
5235 }
5236 if (halt_error.Success()) {
5237 if (log)
5238 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5239
Pavel Labathd35031e12016-11-30 10:41:42 +00005240 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00005241 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005242
5243 if (got_event) {
5244 stop_state =
5245 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5246 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005247 LLDB_LOGF(log,
5248 "Process::RunThreadPlan(): Stopped with event: %s",
5249 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005250 if (stop_state == lldb::eStateStopped &&
5251 Process::ProcessEventData::GetInterruptedFromEvent(
5252 event_sp.get()))
5253 log->PutCString(" Event was the Halt interruption event.");
5254 }
5255
5256 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005257 if (Process::ProcessEventData::GetRestartedFromEvent(
5258 event_sp.get())) {
5259 if (log)
5260 log->PutCString("Process::RunThreadPlan(): Went to halt "
5261 "but got a restarted event, there must be "
5262 "an un-restarted stopped event so try "
5263 "again... "
5264 "Exiting wait loop.");
5265 try_halt_again++;
5266 do_halt = false;
5267 continue;
5268 }
5269
Pavel Labath45dde232017-05-25 10:50:06 +00005270 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005271 // delivered it, the process could have already finished its
5272 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005273 const bool handle_interrupts = false;
5274 if (auto result = HandleStoppedEvent(
Jim Inghamdbbed972020-05-20 18:00:56 -07005275 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5276 event_sp, event_to_broadcast_sp, options,
5277 handle_interrupts)) {
Pavel Labath45dde232017-05-25 10:50:06 +00005278 return_value = *result;
5279 back_to_top = false;
5280 break;
5281 }
5282
Kate Stoneb9c1b512016-09-06 20:57:50 +00005283 if (!options.GetTryAllThreads()) {
5284 if (log)
5285 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5286 "was false, we stopped so now we're "
5287 "quitting.");
5288 return_value = eExpressionInterrupted;
5289 back_to_top = false;
5290 break;
5291 }
5292
5293 if (before_first_timeout) {
5294 // Set all the other threads to run, and return to the top of
5295 // the loop, which will continue;
5296 before_first_timeout = false;
5297 thread_plan_sp->SetStopOthers(false);
5298 if (log)
5299 log->PutCString(
5300 "Process::RunThreadPlan(): about to resume.");
5301
5302 back_to_top = true;
5303 break;
5304 } else {
5305 // Running all threads failed, so return Interrupted.
5306 if (log)
5307 log->PutCString("Process::RunThreadPlan(): running all "
5308 "threads timed out.");
5309 return_value = eExpressionInterrupted;
5310 back_to_top = false;
5311 break;
5312 }
5313 }
5314 } else {
5315 if (log)
5316 log->PutCString("Process::RunThreadPlan(): halt said it "
5317 "succeeded, but I got no event. "
5318 "I'm getting out of here passing Interrupted.");
5319 return_value = eExpressionInterrupted;
5320 back_to_top = false;
5321 break;
5322 }
5323 } else {
5324 try_halt_again++;
5325 continue;
5326 }
5327 }
5328
5329 if (!back_to_top || try_halt_again > num_retries)
5330 break;
5331 else
5332 continue;
5333 }
5334 } // END WAIT LOOP
5335
Adrian Prantl05097242018-04-30 16:49:04 +00005336 // If we had to start up a temporary private state thread to run this
5337 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005338 if (backup_private_state_thread.IsJoinable()) {
5339 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005340 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005341 m_private_state_thread = backup_private_state_thread;
5342 if (stopper_base_plan_sp) {
5343 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5344 }
5345 if (old_state != eStateInvalid)
5346 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005347 }
5348
Jim Inghamdbbed972020-05-20 18:00:56 -07005349 // If our thread went away on us, we need to get out of here without
5350 // doing any more work. We don't have to clean up the thread plan, that
5351 // will have happened when the Thread was destroyed.
5352 if (return_value == eExpressionThreadVanished) {
5353 return return_value;
5354 }
5355
Kate Stoneb9c1b512016-09-06 20:57:50 +00005356 if (return_value != eExpressionCompleted && log) {
5357 // Print a backtrace into the log so we can figure out where we are:
5358 StreamString s;
5359 s.PutCString("Thread state after unsuccessful completion: \n");
5360 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005361 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005362 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005363 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005364 // There are three cases where this could happen: 1) The execution
5365 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5366 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005367 bool should_unwind = (return_value == eExpressionInterrupted &&
5368 options.DoesUnwindOnError()) ||
5369 (return_value == eExpressionHitBreakpoint &&
5370 options.DoesIgnoreBreakpoints());
5371
5372 if (return_value == eExpressionCompleted || should_unwind) {
5373 thread_plan_sp->RestoreThreadState();
5374 }
5375
5376 // Now do some processing on the results of the run:
5377 if (return_value == eExpressionInterrupted ||
5378 return_value == eExpressionHitBreakpoint) {
5379 if (log) {
5380 StreamString s;
5381 if (event_sp)
5382 event_sp->Dump(&s);
5383 else {
5384 log->PutCString("Process::RunThreadPlan(): Stop event that "
5385 "interrupted us is NULL.");
5386 }
5387
5388 StreamString ts;
5389
5390 const char *event_explanation = nullptr;
5391
5392 do {
5393 if (!event_sp) {
5394 event_explanation = "<no event>";
5395 break;
5396 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5397 event_explanation = "<user interrupt>";
5398 break;
5399 } else {
5400 const Process::ProcessEventData *event_data =
5401 Process::ProcessEventData::GetEventDataFromEvent(
5402 event_sp.get());
5403
5404 if (!event_data) {
5405 event_explanation = "<no event data>";
5406 break;
5407 }
5408
5409 Process *process = event_data->GetProcessSP().get();
5410
5411 if (!process) {
5412 event_explanation = "<no process>";
5413 break;
5414 }
5415
5416 ThreadList &thread_list = process->GetThreadList();
5417
5418 uint32_t num_threads = thread_list.GetSize();
5419 uint32_t thread_index;
5420
5421 ts.Printf("<%u threads> ", num_threads);
5422
5423 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5424 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5425
5426 if (!thread) {
5427 ts.Printf("<?> ");
5428 continue;
5429 }
5430
5431 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5432 RegisterContext *register_context =
5433 thread->GetRegisterContext().get();
5434
5435 if (register_context)
5436 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5437 else
5438 ts.Printf("[ip unknown] ");
5439
5440 // Show the private stop info here, the public stop info will be
5441 // from the last natural stop.
5442 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5443 if (stop_info_sp) {
5444 const char *stop_desc = stop_info_sp->GetDescription();
5445 if (stop_desc)
5446 ts.PutCString(stop_desc);
5447 }
5448 ts.Printf(">");
5449 }
5450
5451 event_explanation = ts.GetData();
5452 }
Jonas Devlieghere09ad8c82019-05-24 00:44:33 +00005453 } while (false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005454
5455 if (event_explanation)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005456 LLDB_LOGF(log,
5457 "Process::RunThreadPlan(): execution interrupted: %s %s",
5458 s.GetData(), event_explanation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005459 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005460 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
5461 s.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005462 }
5463
5464 if (should_unwind) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005465 LLDB_LOGF(log,
5466 "Process::RunThreadPlan: ExecutionInterrupted - "
5467 "discarding thread plans up to %p.",
5468 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005469 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5470 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005471 LLDB_LOGF(log,
5472 "Process::RunThreadPlan: ExecutionInterrupted - for "
5473 "plan: %p not discarding.",
5474 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005475 }
5476 } else if (return_value == eExpressionSetupError) {
5477 if (log)
5478 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5479
5480 if (options.DoesUnwindOnError()) {
5481 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5482 }
5483 } else {
5484 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5485 if (log)
5486 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5487 return_value = eExpressionCompleted;
5488 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5489 if (log)
5490 log->PutCString(
5491 "Process::RunThreadPlan(): thread plan was discarded");
5492 return_value = eExpressionDiscarded;
5493 } else {
5494 if (log)
5495 log->PutCString(
5496 "Process::RunThreadPlan(): thread plan stopped in mid course");
5497 if (options.DoesUnwindOnError() && thread_plan_sp) {
5498 if (log)
5499 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5500 "'cause unwind_on_error is set.");
5501 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5502 }
5503 }
5504 }
5505
5506 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005507 // target Check that it's still there, and if it is put it back in the
5508 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005509 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5510 if (thread) {
5511 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5512 }
5513
5514 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005515 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005516
5517 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5518 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5519 selected_stack_id.IsValid()) {
5520 // We were able to restore the selected thread, now restore the frame:
5521 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5522 StackFrameSP old_frame_sp =
5523 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5524 selected_stack_id);
5525 if (old_frame_sp)
5526 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5527 old_frame_sp.get());
5528 }
5529 }
5530 }
5531
5532 // If the process exited during the run of the thread plan, notify everyone.
5533
5534 if (event_to_broadcast_sp) {
5535 if (log)
5536 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5537 BroadcastEvent(event_to_broadcast_sp);
5538 }
5539
5540 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005541}
5542
Kate Stoneb9c1b512016-09-06 20:57:50 +00005543const char *Process::ExecutionResultAsCString(ExpressionResults result) {
Jim Inghamdbbed972020-05-20 18:00:56 -07005544 const char *result_name = "<unknown>";
Kate Stoneb9c1b512016-09-06 20:57:50 +00005545
5546 switch (result) {
5547 case eExpressionCompleted:
5548 result_name = "eExpressionCompleted";
5549 break;
5550 case eExpressionDiscarded:
5551 result_name = "eExpressionDiscarded";
5552 break;
5553 case eExpressionInterrupted:
5554 result_name = "eExpressionInterrupted";
5555 break;
5556 case eExpressionHitBreakpoint:
5557 result_name = "eExpressionHitBreakpoint";
5558 break;
5559 case eExpressionSetupError:
5560 result_name = "eExpressionSetupError";
5561 break;
5562 case eExpressionParseError:
5563 result_name = "eExpressionParseError";
5564 break;
5565 case eExpressionResultUnavailable:
5566 result_name = "eExpressionResultUnavailable";
5567 break;
5568 case eExpressionTimedOut:
5569 result_name = "eExpressionTimedOut";
5570 break;
5571 case eExpressionStoppedForDebug:
5572 result_name = "eExpressionStoppedForDebug";
5573 break;
Jim Inghamdbbed972020-05-20 18:00:56 -07005574 case eExpressionThreadVanished:
5575 result_name = "eExpressionThreadVanished";
Kate Stoneb9c1b512016-09-06 20:57:50 +00005576 }
5577 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005578}
5579
Kate Stoneb9c1b512016-09-06 20:57:50 +00005580void Process::GetStatus(Stream &strm) {
5581 const StateType state = GetState();
5582 if (StateIsStoppedState(state, false)) {
5583 if (state == eStateExited) {
5584 int exit_status = GetExitStatus();
5585 const char *exit_description = GetExitDescription();
5586 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5587 GetID(), exit_status, exit_status,
5588 exit_description ? exit_description : "");
5589 } else {
5590 if (state == eStateConnected)
5591 strm.Printf("Connected to remote target.\n");
5592 else
5593 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5594 }
5595 } else {
5596 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5597 }
Pavel Labatha933d512016-04-05 13:07:16 +00005598}
5599
Kate Stoneb9c1b512016-09-06 20:57:50 +00005600size_t Process::GetThreadStatus(Stream &strm,
5601 bool only_threads_with_stop_reason,
5602 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005603 uint32_t num_frames_with_source,
5604 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005605 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005606
Kate Stoneb9c1b512016-09-06 20:57:50 +00005607 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005608 // very well might run code (e.g. if we need it to get return values or
5609 // arguments.) For that to work the process has to be able to acquire it.
5610 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005611
5612 uint32_t num_threads;
5613 std::vector<lldb::tid_t> thread_id_array;
5614 // Scope for thread list locker;
5615 {
5616 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5617 ThreadList &curr_thread_list = GetThreadList();
5618 num_threads = curr_thread_list.GetSize();
5619 uint32_t idx;
5620 thread_id_array.resize(num_threads);
5621 for (idx = 0; idx < num_threads; ++idx)
5622 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5623 }
5624
5625 for (uint32_t i = 0; i < num_threads; i++) {
5626 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5627 if (thread_sp) {
5628 if (only_threads_with_stop_reason) {
5629 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5630 if (!stop_info_sp || !stop_info_sp->IsValid())
5631 continue;
5632 }
5633 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005634 num_frames_with_source,
5635 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005636 ++num_thread_infos_dumped;
5637 } else {
5638 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005639 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
5640 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005641 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005642 }
5643 return num_thread_infos_dumped;
5644}
5645
5646void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5647 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5648}
5649
5650bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5651 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5652 region.GetByteSize());
5653}
5654
5655void Process::AddPreResumeAction(PreResumeActionCallback callback,
5656 void *baton) {
5657 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5658}
5659
5660bool Process::RunPreResumeActions() {
5661 bool result = true;
5662 while (!m_pre_resume_actions.empty()) {
5663 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5664 m_pre_resume_actions.pop_back();
5665 bool this_result = action.callback(action.baton);
5666 if (result)
5667 result = this_result;
5668 }
5669 return result;
5670}
5671
5672void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5673
Jim Inghamffd91752016-10-20 22:50:00 +00005674void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5675{
5676 PreResumeCallbackAndBaton element(callback, baton);
5677 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5678 if (found_iter != m_pre_resume_actions.end())
5679 {
5680 m_pre_resume_actions.erase(found_iter);
5681 }
5682}
5683
Kate Stoneb9c1b512016-09-06 20:57:50 +00005684ProcessRunLock &Process::GetRunLock() {
5685 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5686 return m_private_run_lock;
5687 else
5688 return m_public_run_lock;
5689}
5690
Jim Ingham58c3235e2019-10-01 00:47:25 +00005691bool Process::CurrentThreadIsPrivateStateThread()
5692{
5693 return m_private_state_thread.EqualsThread(Host::GetCurrentThread());
5694}
5695
5696
Kate Stoneb9c1b512016-09-06 20:57:50 +00005697void Process::Flush() {
5698 m_thread_list.Flush();
5699 m_extended_thread_list.Flush();
5700 m_extended_thread_stop_id = 0;
5701 m_queue_list.Clear();
5702 m_queue_list_stop_id = 0;
5703}
5704
5705void Process::DidExec() {
5706 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005707 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005708
5709 Target &target = GetTarget();
5710 target.CleanupProcess();
5711 target.ClearModules(false);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005712 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005713 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005714 m_system_runtime_up.reset();
5715 m_os_up.reset();
5716 m_dyld_up.reset();
5717 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005718 m_image_tokens.clear();
5719 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +00005720 {
5721 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5722 m_language_runtimes.clear();
5723 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005724 m_instrumentation_runtimes.clear();
5725 m_thread_list.DiscardThreadPlans();
5726 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005727 DoDidExec();
5728 CompleteAttach();
5729 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005730 // CompleteAttach() in case the dynamic loader loaded things in new
5731 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005732 Flush();
5733
Adrian Prantl05097242018-04-30 16:49:04 +00005734 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5735 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005736 target.DidExec();
5737}
5738
Zachary Turner97206d52017-05-12 04:51:55 +00005739addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005740 if (address == nullptr) {
5741 error.SetErrorString("Invalid address argument");
5742 return LLDB_INVALID_ADDRESS;
5743 }
5744
5745 addr_t function_addr = LLDB_INVALID_ADDRESS;
5746
5747 addr_t addr = address->GetLoadAddress(&GetTarget());
5748 std::map<addr_t, addr_t>::const_iterator iter =
5749 m_resolved_indirect_addresses.find(addr);
5750 if (iter != m_resolved_indirect_addresses.end()) {
5751 function_addr = (*iter).second;
5752 } else {
Alex Langford5b2b38e2019-09-13 00:02:05 +00005753 if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005754 Symbol *symbol = address->CalculateSymbolContextSymbol();
5755 error.SetErrorStringWithFormat(
5756 "Unable to call resolver for indirect function %s",
5757 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5758 function_addr = LLDB_INVALID_ADDRESS;
5759 } else {
5760 m_resolved_indirect_addresses.insert(
5761 std::pair<addr_t, addr_t>(addr, function_addr));
5762 }
5763 }
5764 return function_addr;
5765}
5766
5767void Process::ModulesDidLoad(ModuleList &module_list) {
Jonas Devlieghere0b339c02020-07-24 12:09:36 -07005768 // Inform the system runtime of the modified modules.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005769 SystemRuntime *sys_runtime = GetSystemRuntime();
Jonas Devlieghere0b339c02020-07-24 12:09:36 -07005770 if (sys_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005771 sys_runtime->ModulesDidLoad(module_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005772
5773 GetJITLoaders().ModulesDidLoad(module_list);
5774
Jonas Devlieghere0b339c02020-07-24 12:09:36 -07005775 // Give the instrumentation runtimes a chance to be created before informing
5776 // them of the modified modules.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005777 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5778 m_instrumentation_runtimes);
Jonas Devlieghere0b339c02020-07-24 12:09:36 -07005779 for (auto &runtime : m_instrumentation_runtimes)
5780 runtime.second->ModulesDidLoad(module_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005781
Jonas Devlieghere0b339c02020-07-24 12:09:36 -07005782 // Give the language runtimes a chance to be created before informing them of
5783 // the modified modules.
5784 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
5785 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
5786 runtime->ModulesDidLoad(module_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005787 }
5788
5789 // If we don't have an operating system plug-in, try to load one since
5790 // loading shared libraries might cause a new one to try and load
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005791 if (!m_os_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005792 LoadOperatingSystemPlugin(false);
5793
Jonas Devlieghere0b339c02020-07-24 12:09:36 -07005794 // Inform the structured-data plugins of the modified modules.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005795 for (auto pair : m_structured_data_plugin_map) {
5796 if (pair.second)
5797 pair.second->ModulesDidLoad(*this, module_list);
5798 }
5799}
5800
5801void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5802 const char *fmt, ...) {
5803 bool print_warning = true;
5804
5805 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5806 if (!stream_sp)
5807 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005808
5809 if (repeat_key != nullptr) {
5810 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5811 if (it == m_warnings_issued.end()) {
5812 m_warnings_issued[warning_type] = WarningsPointerSet();
5813 m_warnings_issued[warning_type].insert(repeat_key);
5814 } else {
5815 if (it->second.find(repeat_key) != it->second.end()) {
5816 print_warning = false;
5817 } else {
5818 it->second.insert(repeat_key);
5819 }
5820 }
5821 }
5822
5823 if (print_warning) {
5824 va_list args;
5825 va_start(args, fmt);
5826 stream_sp->PrintfVarArg(fmt, args);
5827 va_end(args);
5828 }
5829}
5830
5831void Process::PrintWarningOptimization(const SymbolContext &sc) {
Adrian Prantl220c17f2020-05-21 17:42:24 -07005832 if (!GetWarningsOptimization())
5833 return;
5834 if (!sc.module_sp)
5835 return;
5836 if (!sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
Kate Stoneb9c1b512016-09-06 20:57:50 +00005837 sc.function->GetIsOptimized()) {
5838 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5839 "%s was compiled with optimization - stepping may behave "
5840 "oddly; variables may not be available.\n",
5841 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5842 }
5843}
5844
Adrian Prantl220c17f2020-05-21 17:42:24 -07005845void Process::PrintWarningUnsupportedLanguage(const SymbolContext &sc) {
5846 if (!GetWarningsUnsupportedLanguage())
5847 return;
5848 if (!sc.module_sp)
5849 return;
5850 LanguageType language = sc.GetLanguage();
5851 if (language == eLanguageTypeUnknown)
5852 return;
5853 auto type_system_or_err = sc.module_sp->GetTypeSystemForLanguage(language);
5854 if (auto err = type_system_or_err.takeError()) {
5855 llvm::consumeError(std::move(err));
5856 PrintWarning(Process::Warnings::eWarningsUnsupportedLanguage,
5857 sc.module_sp.get(),
5858 "This version of LLDB has no plugin for the %s language. "
5859 "Inspection of frame variables will be limited.\n",
5860 Language::GetNameForLanguageType(language));
5861 }
5862}
5863
Kate Stoneb9c1b512016-09-06 20:57:50 +00005864bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5865 info.Clear();
5866
5867 PlatformSP platform_sp = GetTarget().GetPlatform();
5868 if (!platform_sp)
5869 return false;
5870
5871 return platform_sp->GetProcessInfo(GetID(), info);
5872}
5873
5874ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5875 ThreadCollectionSP threads;
5876
5877 const MemoryHistorySP &memory_history =
5878 MemoryHistory::FindPlugin(shared_from_this());
5879
5880 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005881 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005882 }
5883
Jonas Devlieghere796ac802019-02-11 23:13:08 +00005884 threads = std::make_shared<ThreadCollection>(
5885 memory_history->GetHistoryThreads(addr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005886
5887 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005888}
Kuba Brecka63927542014-10-11 01:59:32 +00005889
5890InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005891Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5892 InstrumentationRuntimeCollection::iterator pos;
5893 pos = m_instrumentation_runtimes.find(type);
5894 if (pos == m_instrumentation_runtimes.end()) {
5895 return InstrumentationRuntimeSP();
5896 } else
5897 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005898}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005899
Kate Stoneb9c1b512016-09-06 20:57:50 +00005900bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5901 const ArchSpec &arch, ModuleSpec &module_spec) {
5902 module_spec.Clear();
5903 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005904}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005905
Kate Stoneb9c1b512016-09-06 20:57:50 +00005906size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5907 m_image_tokens.push_back(image_ptr);
5908 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005909}
5910
Kate Stoneb9c1b512016-09-06 20:57:50 +00005911lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5912 if (token < m_image_tokens.size())
5913 return m_image_tokens[token];
Saleem Abdulrasool3775be22020-04-06 17:33:38 -07005914 return LLDB_INVALID_ADDRESS;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005915}
5916
Kate Stoneb9c1b512016-09-06 20:57:50 +00005917void Process::ResetImageToken(size_t token) {
5918 if (token < m_image_tokens.size())
Saleem Abdulrasool3775be22020-04-06 17:33:38 -07005919 m_image_tokens[token] = LLDB_INVALID_ADDRESS;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005920}
Jason Molendafd4cea52016-01-08 21:40:11 +00005921
5922Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005923Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5924 AddressRange range_bounds) {
5925 Target &target = GetTarget();
5926 DisassemblerSP disassembler_sp;
5927 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005928
Kate Stoneb9c1b512016-09-06 20:57:50 +00005929 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005930
Kate Stoneb9c1b512016-09-06 20:57:50 +00005931 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005932 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005933 if (!default_stop_addr.IsValid())
5934 return retval;
5935
Kate Stoneb9c1b512016-09-06 20:57:50 +00005936 const char *plugin_name = nullptr;
5937 const char *flavor = nullptr;
5938 const bool prefer_file_cache = true;
5939 disassembler_sp = Disassembler::DisassembleRange(
Pavel Labath04592d52020-03-05 13:03:26 +01005940 target.GetArchitecture(), plugin_name, flavor, GetTarget(), range_bounds,
Kate Stoneb9c1b512016-09-06 20:57:50 +00005941 prefer_file_cache);
5942 if (disassembler_sp)
5943 insn_list = &disassembler_sp->GetInstructionList();
5944
5945 if (insn_list == nullptr) {
5946 return retval;
5947 }
5948
5949 size_t insn_offset =
5950 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5951 if (insn_offset == UINT32_MAX) {
5952 return retval;
5953 }
5954
Ted Woodward3169d922020-07-30 13:37:43 -05005955 uint32_t branch_index = insn_list->GetIndexOfNextBranchInstruction(
5956 insn_offset, false /* ignore_calls*/, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005957 if (branch_index == UINT32_MAX) {
5958 return retval;
5959 }
5960
5961 if (branch_index > insn_offset) {
5962 Address next_branch_insn_address =
5963 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5964 if (next_branch_insn_address.IsValid() &&
5965 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5966 retval = next_branch_insn_address;
5967 }
5968 }
5969
5970 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00005971}
Howard Hellyerad007562016-07-07 08:21:28 +00005972
Zachary Turner97206d52017-05-12 04:51:55 +00005973Status
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005974Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00005975
Zachary Turner97206d52017-05-12 04:51:55 +00005976 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00005977
Kate Stoneb9c1b512016-09-06 20:57:50 +00005978 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00005979
Kate Stoneb9c1b512016-09-06 20:57:50 +00005980 region_list.clear();
5981 do {
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005982 lldb_private::MemoryRegionInfo region_info;
5983 error = GetMemoryRegionInfo(range_end, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005984 // GetMemoryRegionInfo should only return an error if it is unimplemented.
5985 if (error.Fail()) {
5986 region_list.clear();
5987 break;
Todd Fiala75930012016-08-19 04:21:48 +00005988 }
5989
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005990 range_end = region_info.GetRange().GetRangeEnd();
5991 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5992 region_list.push_back(std::move(region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005993 }
5994 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00005995
Kate Stoneb9c1b512016-09-06 20:57:50 +00005996 return error;
5997}
5998
Zachary Turner97206d52017-05-12 04:51:55 +00005999Status
Adrian Prantl0e4c4822019-03-06 21:22:25 +00006000Process::ConfigureStructuredData(ConstString type_name,
Zachary Turner97206d52017-05-12 04:51:55 +00006001 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00006002 // If you get this, the Process-derived class needs to implement a method to
6003 // enable an already-reported asynchronous structured data feature. See
6004 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00006005 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00006006}
6007
6008void Process::MapSupportedStructuredDataPlugins(
6009 const StructuredData::Array &supported_type_names) {
6010 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6011
6012 // Bail out early if there are no type names to map.
6013 if (supported_type_names.GetSize() == 0) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00006014 LLDB_LOGF(log, "Process::%s(): no structured data types supported",
6015 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006016 return;
6017 }
Todd Fiala75930012016-08-19 04:21:48 +00006018
Kate Stoneb9c1b512016-09-06 20:57:50 +00006019 // Convert StructuredData type names to ConstString instances.
6020 std::set<ConstString> const_type_names;
6021
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00006022 LLDB_LOGF(log,
6023 "Process::%s(): the process supports the following async "
6024 "structured data types:",
6025 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006026
6027 supported_type_names.ForEach(
6028 [&const_type_names, &log](StructuredData::Object *object) {
6029 if (!object) {
6030 // Invalid - shouldn't be null objects in the array.
6031 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006032 }
6033
6034 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006035 if (!type_name) {
6036 // Invalid format - all type names should be strings.
6037 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006038 }
6039
6040 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00006041 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00006042 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006043 });
Todd Fiala75930012016-08-19 04:21:48 +00006044
Adrian Prantl05097242018-04-30 16:49:04 +00006045 // For each StructuredDataPlugin, if the plugin handles any of the types in
6046 // the supported_type_names, map that type name to that plugin. Stop when
6047 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00006048 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00006049 // supports?
6050 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
6051 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00006052 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6053 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00006054 if (!create_instance)
6055 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00006056
Kate Stoneb9c1b512016-09-06 20:57:50 +00006057 // Create the plugin.
6058 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6059 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00006060 // This plugin doesn't think it can work with the process. Move on to the
6061 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006062 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006063 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006064
Adrian Prantl05097242018-04-30 16:49:04 +00006065 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006066 std::vector<ConstString> names_to_remove;
6067 for (auto &type_name : const_type_names) {
6068 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6069 m_structured_data_plugin_map.insert(
6070 std::make_pair(type_name, plugin_sp));
6071 names_to_remove.push_back(type_name);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00006072 LLDB_LOGF(log,
6073 "Process::%s(): using plugin %s for type name "
6074 "%s",
6075 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6076 type_name.GetCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00006077 }
6078 }
6079
6080 // Remove the type names that were consumed by this plugin.
6081 for (auto &type_name : names_to_remove)
6082 const_type_names.erase(type_name);
6083 }
Todd Fiala75930012016-08-19 04:21:48 +00006084}
6085
Kate Stoneb9c1b512016-09-06 20:57:50 +00006086bool Process::RouteAsyncStructuredData(
6087 const StructuredData::ObjectSP object_sp) {
6088 // Nothing to do if there's no data.
6089 if (!object_sp)
6090 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006091
Adrian Prantl05097242018-04-30 16:49:04 +00006092 // The contract is this must be a dictionary, so we can look up the routing
6093 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006094 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6095 if (!dictionary)
6096 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006097
Kate Stoneb9c1b512016-09-06 20:57:50 +00006098 // Grab the async structured type name (i.e. the feature/plugin name).
6099 ConstString type_name;
6100 if (!dictionary->GetValueForKeyAsString("type", type_name))
6101 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006102
Kate Stoneb9c1b512016-09-06 20:57:50 +00006103 // Check if there's a plugin registered for this type name.
6104 auto find_it = m_structured_data_plugin_map.find(type_name);
6105 if (find_it == m_structured_data_plugin_map.end()) {
6106 // We don't have a mapping for this structured data type.
6107 return false;
6108 }
Todd Fiala75930012016-08-19 04:21:48 +00006109
Kate Stoneb9c1b512016-09-06 20:57:50 +00006110 // Route the structured data to the plugin.
6111 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6112 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006113}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006114
Zachary Turner97206d52017-05-12 04:51:55 +00006115Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006116 // Default implementation does nothign.
6117 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00006118 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006119}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006120
Frederic Rissd10d3792018-05-11 18:21:11 +00006121UtilityFunction *Process::GetLoadImageUtilityFunction(
6122 Platform *platform,
6123 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006124 if (platform != GetTarget().GetPlatform().get())
6125 return nullptr;
Michal Gorny3276fff2019-09-03 12:31:24 +00006126 llvm::call_once(m_dlopen_utility_func_flag_once,
6127 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006128 return m_dlopen_utility_func_up.get();
6129}
Alex Langford5b2b38e2019-09-13 00:02:05 +00006130
6131bool Process::CallVoidArgVoidPtrReturn(const Address *address,
6132 addr_t &returned_func,
6133 bool trap_exceptions) {
6134 Thread *thread = GetThreadList().GetExpressionExecutionThread().get();
6135 if (thread == nullptr || address == nullptr)
6136 return false;
6137
6138 EvaluateExpressionOptions options;
6139 options.SetStopOthers(true);
6140 options.SetUnwindOnError(true);
6141 options.SetIgnoreBreakpoints(true);
6142 options.SetTryAllThreads(true);
6143 options.SetDebug(false);
6144 options.SetTimeout(GetUtilityExpressionTimeout());
6145 options.SetTrapExceptions(trap_exceptions);
6146
6147 auto type_system_or_err =
6148 GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC);
6149 if (!type_system_or_err) {
6150 llvm::consumeError(type_system_or_err.takeError());
6151 return false;
6152 }
6153 CompilerType void_ptr_type =
6154 type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
6155 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction(
6156 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
6157 if (call_plan_sp) {
6158 DiagnosticManager diagnostics;
6159
6160 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6161 if (frame) {
6162 ExecutionContext exe_ctx;
6163 frame->CalculateExecutionContext(exe_ctx);
6164 ExpressionResults result =
6165 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
6166 if (result == eExpressionCompleted) {
6167 returned_func =
6168 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6169 LLDB_INVALID_ADDRESS);
6170
6171 if (GetAddressByteSize() == 4) {
6172 if (returned_func == UINT32_MAX)
6173 return false;
6174 } else if (GetAddressByteSize() == 8) {
6175 if (returned_func == UINT64_MAX)
6176 return false;
6177 }
6178 return true;
6179 }
6180 }
6181 }
6182
6183 return false;
6184}