blob: 7797a4c60964dcbac5dcde5a4dbe794fb4cbeb6f [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"
Greg Clayton67cc0632012-08-22 17:17:09 +0000123};
124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125ProcessProperties::ProcessProperties(lldb_private::Process *process)
126 : Properties(),
127 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000128{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 if (process == nullptr) {
130 // Global process properties, set them up one time
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000131 m_collection_sp =
132 std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000133 m_collection_sp->Initialize(g_process_properties);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000134 m_collection_sp->AppendProperty(
135 ConstString("thread"), ConstString("Settings specific to threads."),
136 true, Thread::GetGlobalProperties()->GetValueProperties());
137 } else {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000138 m_collection_sp = std::make_shared<ProcessOptionValueProperties>(
139 Process::GetGlobalProperties().get());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 m_collection_sp->SetValueChangedCallback(
141 ePropertyPythonOSPluginPath,
Pavel Labath5c4661b2020-01-09 14:14:54 +0100142 [this] { m_process->LoadOperatingSystemPlugin(true); });
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000144}
145
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000146ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148bool ProcessProperties::GetDisableMemoryCache() const {
149 const uint32_t idx = ePropertyDisableMemCache;
150 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000151 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000152}
153
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
155 const uint32_t idx = ePropertyMemCacheLineSize;
156 return m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000157 nullptr, idx, g_process_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000158}
159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160Args ProcessProperties::GetExtraStartupCommands() const {
161 Args args;
162 const uint32_t idx = ePropertyExtraStartCommand;
163 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
164 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000165}
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167void ProcessProperties::SetExtraStartupCommands(const Args &args) {
168 const uint32_t idx = ePropertyExtraStartCommand;
169 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000170}
171
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172FileSpec ProcessProperties::GetPythonOSPluginPath() const {
173 const uint32_t idx = ePropertyPythonOSPluginPath;
174 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000175}
176
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
178 const uint32_t idx = ePropertyPythonOSPluginPath;
179 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000180}
181
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
183 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
184 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000185 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000186}
187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
189 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
190 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000191}
192
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
194 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
195 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000196 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000197}
198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
200 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
201 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000202}
203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
205 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
206 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000207 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000208}
209
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
211 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
212 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
213}
214
215bool ProcessProperties::GetDetachKeepsStopped() const {
216 const uint32_t idx = ePropertyDetachKeepsStopped;
217 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000218 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219}
220
221void ProcessProperties::SetDetachKeepsStopped(bool stop) {
222 const uint32_t idx = ePropertyDetachKeepsStopped;
223 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
224}
225
226bool ProcessProperties::GetWarningsOptimization() const {
227 const uint32_t idx = ePropertyWarningOptimization;
228 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000229 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230}
231
Jim Inghamba205c12017-12-05 02:50:45 +0000232bool ProcessProperties::GetStopOnExec() const {
233 const uint32_t idx = ePropertyStopOnExec;
234 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000235 nullptr, idx, g_process_properties[idx].default_uint_value != 0);
Jim Inghamba205c12017-12-05 02:50:45 +0000236}
237
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000238std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
239 const uint32_t idx = ePropertyUtilityExpressionTimeout;
240 uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000241 nullptr, idx, g_process_properties[idx].default_uint_value);
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000242 return std::chrono::seconds(value);
243}
244
Zachary Turner97206d52017-05-12 04:51:55 +0000245Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000246 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000248 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 const int short_option = m_getopt_table[option_idx].val;
250
251 switch (short_option) {
252 case 's': // Stop at program entry point
253 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
254 break;
255
256 case 'i': // STDIN for read only
257 {
258 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000259 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260 launch_info.AppendFileAction(action);
261 break;
262 }
263
264 case 'o': // Open STDOUT for write only
265 {
266 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000267 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 launch_info.AppendFileAction(action);
269 break;
270 }
271
272 case 'e': // STDERR for write only
273 {
274 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000275 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 launch_info.AppendFileAction(action);
277 break;
278 }
279
280 case 'p': // Process plug-in name
281 launch_info.SetProcessPluginName(option_arg);
282 break;
283
284 case 'n': // Disable STDIO
285 {
286 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000287 const FileSpec dev_null(FileSystem::DEV_NULL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000288 if (action.Open(STDIN_FILENO, dev_null, true, false))
289 launch_info.AppendFileAction(action);
290 if (action.Open(STDOUT_FILENO, dev_null, false, true))
291 launch_info.AppendFileAction(action);
292 if (action.Open(STDERR_FILENO, dev_null, false, true))
293 launch_info.AppendFileAction(action);
294 break;
295 }
296
297 case 'w':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000298 launch_info.SetWorkingDirectory(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 break;
300
301 case 't': // Open process in new terminal window
302 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
303 break;
304
305 case 'a': {
306 TargetSP target_sp =
307 execution_context ? execution_context->GetTargetSP() : TargetSP();
308 PlatformSP platform_sp =
309 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000310 launch_info.GetArchitecture() =
311 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312 } break;
313
314 case 'A': // Disable ASLR.
315 {
316 bool success;
317 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000318 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 if (success)
320 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000321 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322 error.SetErrorStringWithFormat(
323 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000324 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 break;
326 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000327
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 case 'X': // shell expand args.
329 {
330 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000331 const bool expand_args =
332 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 if (success)
334 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000335 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 error.SetErrorStringWithFormat(
337 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000338 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339 break;
340 }
341
342 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000343 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000344 launch_info.SetShell(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 else
346 launch_info.SetShell(HostInfo::GetDefaultShell());
347 break;
348
349 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000350 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 break;
352
353 default:
354 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
355 short_option);
356 break;
357 }
358 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000359}
360
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000361static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000363 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 "Stop at the entry point of the program when launching a process."},
365 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000366 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 "Set whether to disable address space layout randomization when launching "
368 "a process."},
369 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000370 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 "Name of the process plugin you want to use."},
372 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000373 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 eArgTypeDirectoryName,
375 "Set the current working directory to <path> when running the inferior."},
376 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000377 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378 "Set the architecture for the process to launch when ambiguous."},
379 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000380 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 "Specify an environment variable name/value string (--environment "
382 "NAME=VALUE). Can be specified multiple times for subsequent environment "
383 "entries."},
384 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000385 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000389 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000390 "Redirect stdin for the process to <filename>."},
391 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000392 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 "Redirect stdout for the process to <filename>."},
394 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000395 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000399 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000403 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 "Do not set up for terminal I/O to go to running process."},
405 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000406 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000408};
409
410llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000411 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000412}
Greg Clayton32e0a752011-03-30 18:16:51 +0000413
Zachary Turner31659452016-11-17 21:15:14 +0000414ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
415 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416 ListenerSP listener_sp,
417 const FileSpec *crash_file_path) {
418 static uint32_t g_process_unique_id = 0;
419
420 ProcessSP process_sp;
421 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000422 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 ConstString const_plugin_name(plugin_name);
424 create_callback =
425 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
426 if (create_callback) {
427 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
428 if (process_sp) {
429 if (process_sp->CanDebug(target_sp, true)) {
430 process_sp->m_process_unique_id = ++g_process_unique_id;
431 } else
432 process_sp.reset();
433 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000434 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435 } else {
436 for (uint32_t idx = 0;
437 (create_callback =
438 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
439 ++idx) {
440 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
441 if (process_sp) {
442 if (process_sp->CanDebug(target_sp, false)) {
443 process_sp->m_process_unique_id = ++g_process_unique_id;
444 break;
445 } else
446 process_sp.reset();
447 }
448 }
449 }
450 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000451}
452
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453ConstString &Process::GetStaticBroadcasterClass() {
454 static ConstString class_name("lldb.process");
455 return class_name;
456}
457
458Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
459 : Process(target_sp, listener_sp,
460 UnixSignals::Create(HostInfo::GetArchitecture())) {
461 // This constructor just delegates to the full Process constructor,
462 // defaulting to using the Host's UnixSignals.
463}
464
465Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
466 const UnixSignalsSP &unix_signals_sp)
467 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
468 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
469 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000470 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471 m_private_state(eStateUnloaded),
472 m_private_state_broadcaster(nullptr,
473 "lldb.process.internal_state_broadcaster"),
474 m_private_state_control_broadcaster(
475 nullptr, "lldb.process.internal_state_control_broadcaster"),
476 m_private_state_listener_sp(
477 Listener::MakeListener("lldb.process.internal_state_listener")),
478 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
479 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
480 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
Jim Ingham18930652020-03-18 12:05:08 -0700481 m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
483 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000484 m_breakpoint_site_list(), m_dynamic_checkers_up(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
486 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
487 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
488 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
489 m_memory_cache(*this), m_allocated_memory_cache(*this),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000490 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000491 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
493 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
494 m_can_interpret_function_calls(false), m_warnings_issued(),
495 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
496 CheckInWithManager();
497
498 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000499 LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500
501 if (!m_unix_signals_sp)
502 m_unix_signals_sp = std::make_shared<UnixSignals>();
503
504 SetEventName(eBroadcastBitStateChanged, "state-changed");
505 SetEventName(eBroadcastBitInterrupt, "interrupt");
506 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
507 SetEventName(eBroadcastBitSTDERR, "stderr-available");
508 SetEventName(eBroadcastBitProfileData, "profile-data-available");
509 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
510
511 m_private_state_control_broadcaster.SetEventName(
512 eBroadcastInternalStateControlStop, "control-stop");
513 m_private_state_control_broadcaster.SetEventName(
514 eBroadcastInternalStateControlPause, "control-pause");
515 m_private_state_control_broadcaster.SetEventName(
516 eBroadcastInternalStateControlResume, "control-resume");
517
518 m_listener_sp->StartListeningForEvents(
519 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
520 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
521 eBroadcastBitProfileData | eBroadcastBitStructuredData);
522
523 m_private_state_listener_sp->StartListeningForEvents(
524 &m_private_state_broadcaster,
525 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
526
527 m_private_state_listener_sp->StartListeningForEvents(
528 &m_private_state_control_broadcaster,
529 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
530 eBroadcastInternalStateControlResume);
531 // We need something valid here, even if just the default UnixSignalsSP.
532 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
533
534 // Allow the platform to override the default cache line size
535 OptionValueSP value_sp =
536 m_collection_sp
537 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
538 ->GetValue();
539 uint32_t platform_cache_line_size =
540 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
541 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
542 value_sp->SetUInt64Value(platform_cache_line_size);
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100543
544 RegisterAssertFrameRecognizer(this);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545}
546
547Process::~Process() {
548 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000549 LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 StopPrivateStateThread();
551
552 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000553 // explicitly clear the thread list here to ensure that the mutex is not
554 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 m_thread_list.Clear();
556}
557
558const ProcessPropertiesSP &Process::GetGlobalProperties() {
559 // NOTE: intentional leak so we don't crash if global destructor chain gets
560 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000561 static ProcessPropertiesSP *g_settings_sp_ptr =
562 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 return *g_settings_sp_ptr;
564}
565
566void Process::Finalize() {
567 m_finalizing = true;
568
569 // Destroy this process if needed
570 switch (GetPrivateState()) {
571 case eStateConnected:
572 case eStateAttaching:
573 case eStateLaunching:
574 case eStateStopped:
575 case eStateRunning:
576 case eStateStepping:
577 case eStateCrashed:
578 case eStateSuspended:
579 Destroy(false);
580 break;
581
582 case eStateInvalid:
583 case eStateUnloaded:
584 case eStateDetached:
585 case eStateExited:
586 break;
587 }
588
589 // Clear our broadcaster before we proceed with destroying
590 Broadcaster::Clear();
591
Adrian Prantl05097242018-04-30 16:49:04 +0000592 // Do any cleanup needed prior to being destructed... Subclasses that
593 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594
595 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000596 // destroyed since it is very likely that undoing the loader will require
597 // access to the real process.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000598 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000600 m_os_up.reset();
601 m_system_runtime_up.reset();
602 m_dyld_up.reset();
603 m_jit_loaders_up.reset();
Jim Ingham61e8e682020-03-10 16:18:11 -0700604 m_thread_plans.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 m_thread_list_real.Destroy();
606 m_thread_list.Destroy();
607 m_extended_thread_list.Destroy();
608 m_queue_list.Clear();
609 m_queue_list_stop_id = 0;
610 std::vector<Notifications> empty_notifications;
611 m_notifications.swap(empty_notifications);
612 m_image_tokens.clear();
613 m_memory_cache.Clear();
614 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +0000615 {
616 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
617 m_language_runtimes.clear();
618 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 m_instrumentation_runtimes.clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000620 m_next_event_action_up.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000621 // Clear the last natural stop ID since it has a strong reference to this
622 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
624 //#ifdef LLDB_CONFIGURATION_DEBUG
625 // StreamFile s(stdout, false);
626 // EventSP event_sp;
627 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
628 // {
629 // event_sp->Dump (&s);
630 // s.EOL();
631 // }
632 //#endif
633 // We have to be very careful here as the m_private_state_listener might
634 // contain events that have ProcessSP values in them which can keep this
635 // process around forever. These events need to be cleared out.
636 m_private_state_listener_sp->Clear();
637 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
638 m_public_run_lock.SetStopped();
639 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
640 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000641 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000642 m_finalize_called = true;
643}
644
645void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
646 m_notifications.push_back(callbacks);
647 if (callbacks.initialize != nullptr)
648 callbacks.initialize(callbacks.baton, this);
649}
650
651bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
652 std::vector<Notifications>::iterator pos, end = m_notifications.end();
653 for (pos = m_notifications.begin(); pos != end; ++pos) {
654 if (pos->baton == callbacks.baton &&
655 pos->initialize == callbacks.initialize &&
656 pos->process_state_changed == callbacks.process_state_changed) {
657 m_notifications.erase(pos);
658 return true;
659 }
660 }
661 return false;
662}
663
664void Process::SynchronouslyNotifyStateChanged(StateType state) {
665 std::vector<Notifications>::iterator notification_pos,
666 notification_end = m_notifications.end();
667 for (notification_pos = m_notifications.begin();
668 notification_pos != notification_end; ++notification_pos) {
669 if (notification_pos->process_state_changed)
670 notification_pos->process_state_changed(notification_pos->baton, this,
671 state);
672 }
673}
674
675// FIXME: We need to do some work on events before the general Listener sees
676// them.
677// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000678// we do the little "insert real insn, step & stop" trick. But we can't do
679// that when the event is delivered by the broadcaster - since that is done on
680// the thread that is waiting for new events, so if we needed more than one
681// event for our handling, we would stall. So instead we do it when we fetch
682// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000683//
684
Kate Stoneb9c1b512016-09-06 20:57:50 +0000685StateType Process::GetNextEvent(EventSP &event_sp) {
686 StateType state = eStateInvalid;
687
Pavel Labathd35031e12016-11-30 10:41:42 +0000688 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
689 std::chrono::seconds(0)) &&
690 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
692
693 return state;
694}
695
Pavel Labath3879fe02018-05-09 14:29:30 +0000696void Process::SyncIOHandler(uint32_t iohandler_id,
697 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 // don't sync (potentially context switch) in case where there is no process
699 // IO
700 if (!m_process_input_reader)
701 return;
702
Pavel Labath3879fe02018-05-09 14:29:30 +0000703 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704
705 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000706 if (Result) {
707 LLDB_LOG(
708 log,
709 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
710 iohandler_id, *Result);
711 } else {
712 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
713 iohandler_id);
714 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000715}
716
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000717StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
718 EventSP *event_sp_ptr, bool wait_always,
719 ListenerSP hijack_listener_sp,
720 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000722 // have restarted the target. We have to actually check each event, and in
723 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 if (event_sp_ptr)
725 event_sp_ptr->reset();
726 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000727 // If we are exited or detached, we won't ever get back to any other valid
728 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000733 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000734
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735 if (!wait_always && StateIsStoppedState(state, true) &&
736 StateIsStoppedState(GetPrivateState(), true)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000737 LLDB_LOGF(log,
738 "Process::%s returning without waiting for events; process "
739 "private and public states are already 'stopped'.",
740 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 // We need to toggle the run lock as this won't get done in
742 // SetPublicState() if the process is hijacked.
743 if (hijack_listener_sp && use_run_lock)
744 m_public_run_lock.SetStopped();
745 return state;
746 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000747
Kate Stoneb9c1b512016-09-06 20:57:50 +0000748 while (state != eStateInvalid) {
749 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000750 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751 if (event_sp_ptr && event_sp)
752 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +0000753
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
755 Process::HandleProcessStateChangedEvent(event_sp, stream,
756 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +0000757
Kate Stoneb9c1b512016-09-06 20:57:50 +0000758 switch (state) {
759 case eStateCrashed:
760 case eStateDetached:
761 case eStateExited:
762 case eStateUnloaded:
763 // We need to toggle the run lock as this won't get done in
764 // SetPublicState() if the process is hijacked.
765 if (hijack_listener_sp && use_run_lock)
766 m_public_run_lock.SetStopped();
767 return state;
768 case eStateStopped:
769 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
770 continue;
771 else {
Pavel Labath78521ef2015-03-06 10:52:47 +0000772 // We need to toggle the run lock as this won't get done in
773 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +0000774 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 m_public_run_lock.SetStopped();
776 return state;
777 }
778 default:
779 continue;
780 }
781 }
782 return state;
783}
784
785bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
786 Stream *stream,
787 bool &pop_process_io_handler) {
788 const bool handle_pop = pop_process_io_handler;
789
790 pop_process_io_handler = false;
791 ProcessSP process_sp =
792 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
793
794 if (!process_sp)
795 return false;
796
797 StateType event_state =
798 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
799 if (event_state == eStateInvalid)
800 return false;
801
802 switch (event_state) {
803 case eStateInvalid:
804 case eStateUnloaded:
805 case eStateAttaching:
806 case eStateLaunching:
807 case eStateStepping:
808 case eStateDetached:
809 if (stream)
810 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
811 StateAsCString(event_state));
812 if (event_state == eStateDetached)
813 pop_process_io_handler = true;
814 break;
815
816 case eStateConnected:
817 case eStateRunning:
818 // Don't be chatty when we run...
819 break;
820
821 case eStateExited:
822 if (stream)
823 process_sp->GetStatus(*stream);
824 pop_process_io_handler = true;
825 break;
826
827 case eStateStopped:
828 case eStateCrashed:
829 case eStateSuspended:
830 // Make sure the program hasn't been auto-restarted:
831 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
832 if (stream) {
833 size_t num_reasons =
834 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
835 if (num_reasons > 0) {
836 // FIXME: Do we want to report this, or would that just be annoyingly
837 // chatty?
838 if (num_reasons == 1) {
839 const char *reason =
840 Process::ProcessEventData::GetRestartedReasonAtIndex(
841 event_sp.get(), 0);
842 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
843 process_sp->GetID(),
844 reason ? reason : "<UNKNOWN REASON>");
845 } else {
846 stream->Printf("Process %" PRIu64
847 " stopped and restarted, reasons:\n",
848 process_sp->GetID());
849
850 for (size_t i = 0; i < num_reasons; i++) {
851 const char *reason =
852 Process::ProcessEventData::GetRestartedReasonAtIndex(
853 event_sp.get(), i);
854 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
855 }
856 }
857 }
858 }
859 } else {
860 StopInfoSP curr_thread_stop_info_sp;
861 // Lock the thread list so it doesn't change on us, this is the scope for
862 // the locker:
863 {
864 ThreadList &thread_list = process_sp->GetThreadList();
865 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
866
867 ThreadSP curr_thread(thread_list.GetSelectedThread());
868 ThreadSP thread;
869 StopReason curr_thread_stop_reason = eStopReasonInvalid;
870 if (curr_thread) {
871 curr_thread_stop_reason = curr_thread->GetStopReason();
872 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
873 }
874 if (!curr_thread || !curr_thread->IsValid() ||
875 curr_thread_stop_reason == eStopReasonInvalid ||
876 curr_thread_stop_reason == eStopReasonNone) {
877 // Prefer a thread that has just completed its plan over another
878 // thread as current thread.
879 ThreadSP plan_thread;
880 ThreadSP other_thread;
881
882 const size_t num_threads = thread_list.GetSize();
883 size_t i;
884 for (i = 0; i < num_threads; ++i) {
885 thread = thread_list.GetThreadAtIndex(i);
886 StopReason thread_stop_reason = thread->GetStopReason();
887 switch (thread_stop_reason) {
888 case eStopReasonInvalid:
889 case eStopReasonNone:
890 break;
891
892 case eStopReasonSignal: {
893 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +0000894 // that signal. We have to have had another reason for stopping
895 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 uint64_t signo = thread->GetStopInfo()->GetValue();
897 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
898 if (!other_thread)
899 other_thread = thread;
900 }
901 break;
902 }
903 case eStopReasonTrace:
904 case eStopReasonBreakpoint:
905 case eStopReasonWatchpoint:
906 case eStopReasonException:
907 case eStopReasonExec:
908 case eStopReasonThreadExiting:
909 case eStopReasonInstrumentation:
910 if (!other_thread)
911 other_thread = thread;
912 break;
913 case eStopReasonPlanComplete:
914 if (!plan_thread)
915 plan_thread = thread;
916 break;
917 }
918 }
919 if (plan_thread)
920 thread_list.SetSelectedThreadByID(plan_thread->GetID());
921 else if (other_thread)
922 thread_list.SetSelectedThreadByID(other_thread->GetID());
923 else {
924 if (curr_thread && curr_thread->IsValid())
925 thread = curr_thread;
926 else
927 thread = thread_list.GetThreadAtIndex(0);
928
929 if (thread)
930 thread_list.SetSelectedThreadByID(thread->GetID());
931 }
932 }
933 }
934 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +0000935 // have to run code, e.g. for Data formatters, and if we hold the
936 // ThreadList mutex, then the process is going to have a hard time
937 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000938 if (stream) {
939 Debugger &debugger = process_sp->GetTarget().GetDebugger();
940 if (debugger.GetTargetList().GetSelectedTarget().get() ==
941 &process_sp->GetTarget()) {
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100942 ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
943
944 if (!thread_sp || !thread_sp->IsValid())
945 return false;
946
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947 const bool only_threads_with_stop_reason = true;
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100948 const uint32_t start_frame = thread_sp->GetSelectedFrameIndex();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 const uint32_t num_frames = 1;
950 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +0000951 const bool stop_format = true;
Med Ismail Bennani7ebe9cc2020-02-04 17:53:26 +0100952
Kate Stoneb9c1b512016-09-06 20:57:50 +0000953 process_sp->GetStatus(*stream);
954 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
955 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000956 num_frames_with_source,
957 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958 if (curr_thread_stop_info_sp) {
959 lldb::addr_t crashing_address;
960 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
961 curr_thread_stop_info_sp, &crashing_address);
962 if (valobj_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963 const ValueObject::GetExpressionPathFormat format =
964 ValueObject::GetExpressionPathFormat::
965 eGetExpressionPathFormatHonorPointers;
966 stream->PutCString("Likely cause: ");
Alex Langford3014efe2020-02-02 14:17:02 -0800967 valobj_sp->GetExpressionPath(*stream, format);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
969 }
970 }
971 } else {
972 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
973 process_sp->GetTarget().shared_from_this());
974 if (target_idx != UINT32_MAX)
975 stream->Printf("Target %d: (", target_idx);
976 else
977 stream->Printf("Target <unknown index>: (");
978 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
979 stream->Printf(") stopped.\n");
980 }
981 }
982
983 // Pop the process IO handler
984 pop_process_io_handler = true;
985 }
986 break;
987 }
988
989 if (handle_pop && pop_process_io_handler)
990 process_sp->PopProcessIOHandler();
991
992 return true;
993}
994
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995bool Process::HijackProcessEvents(ListenerSP listener_sp) {
996 if (listener_sp) {
997 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
998 eBroadcastBitInterrupt);
999 } else
1000 return false;
1001}
Greg Claytondc6224e2014-10-21 01:00:42 +00001002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001004
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001005StateType Process::GetStateChangedEvents(EventSP &event_sp,
1006 const Timeout<std::micro> &timeout,
1007 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001009 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001010
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 ListenerSP listener_sp = hijack_listener_sp;
1012 if (!listener_sp)
1013 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001014
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001016 if (listener_sp->GetEventForBroadcasterWithType(
1017 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001018 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1020 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001021 else
1022 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001024
Pavel Labathd02b1c82017-02-10 11:49:33 +00001025 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026 return state;
1027}
Greg Claytondc6224e2014-10-21 01:00:42 +00001028
Kate Stoneb9c1b512016-09-06 20:57:50 +00001029Event *Process::PeekAtStateChangedEvents() {
1030 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001031
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001032 LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001033
Kate Stoneb9c1b512016-09-06 20:57:50 +00001034 Event *event_ptr;
1035 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1036 this, eBroadcastBitStateChanged);
1037 if (log) {
1038 if (event_ptr) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001039 LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
1040 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001041 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001042 LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001043 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044 }
1045 return event_ptr;
1046}
Greg Claytondc6224e2014-10-21 01:00:42 +00001047
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001048StateType
1049Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1050 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001052 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053
1054 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001055 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1056 &m_private_state_broadcaster,
1057 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001058 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1060 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1061
Pavel Labathd02b1c82017-02-10 11:49:33 +00001062 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1063 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001064 return state;
1065}
1066
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001067bool Process::GetEventsPrivate(EventSP &event_sp,
1068 const Timeout<std::micro> &timeout,
1069 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001071 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072
1073 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001074 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001075 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001077 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078}
1079
1080bool Process::IsRunning() const {
1081 return StateIsRunningState(m_public_state.GetValue());
1082}
1083
1084int Process::GetExitStatus() {
1085 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1086
1087 if (m_public_state.GetValue() == eStateExited)
1088 return m_exit_status;
1089 return -1;
1090}
1091
1092const char *Process::GetExitDescription() {
1093 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1094
1095 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1096 return m_exit_string.c_str();
1097 return nullptr;
1098}
1099
1100bool Process::SetExitStatus(int status, const char *cstr) {
1101 // Use a mutex to protect setting the exit status.
1102 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1103
1104 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1105 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001106 LLDB_LOGF(
1107 log, "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1108 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", cstr ? "\"" : "");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109
1110 // We were already in the exited state
1111 if (m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001112 LLDB_LOGF(log, "Process::SetExitStatus () ignoring exit status because "
1113 "state was already set to eStateExited");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001114 return false;
1115 }
1116
1117 m_exit_status = status;
1118 if (cstr)
1119 m_exit_string = cstr;
1120 else
1121 m_exit_string.clear();
1122
Adrian Prantl05097242018-04-30 16:49:04 +00001123 // Clear the last natural stop ID since it has a strong reference to this
1124 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1126
1127 SetPrivateState(eStateExited);
1128
1129 // Allow subclasses to do some cleanup
1130 DidExit();
1131
1132 return true;
1133}
1134
1135bool Process::IsAlive() {
1136 switch (m_private_state.GetValue()) {
1137 case eStateConnected:
1138 case eStateAttaching:
1139 case eStateLaunching:
1140 case eStateStopped:
1141 case eStateRunning:
1142 case eStateStepping:
1143 case eStateCrashed:
1144 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001145 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001146 default:
1147 return false;
1148 }
Jason Molendaa814f702015-11-05 23:03:44 +00001149}
1150
Adrian Prantl05097242018-04-30 16:49:04 +00001151// This static callback can be used to watch for local child processes on the
1152// current host. The child process exits, the process will be found in the
1153// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001154// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155bool Process::SetProcessExitStatus(
1156 lldb::pid_t pid, bool exited,
1157 int signo, // Zero for no signal
1158 int exit_status // Exit value of process if signal is zero
1159 ) {
1160 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001161 LLDB_LOGF(log,
1162 "Process::SetProcessExitStatus (pid=%" PRIu64
1163 ", exited=%i, signal=%i, exit_status=%i)\n",
1164 pid, exited, signo, exit_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165
1166 if (exited) {
1167 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1168 if (target_sp) {
1169 ProcessSP process_sp(target_sp->GetProcessSP());
1170 if (process_sp) {
1171 const char *signal_cstr = nullptr;
1172 if (signo)
1173 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1174
1175 process_sp->SetExitStatus(exit_status, signal_cstr);
1176 }
1177 }
1178 return true;
1179 }
1180 return false;
1181}
1182
1183void Process::UpdateThreadListIfNeeded() {
1184 const uint32_t stop_id = GetStopID();
1185 if (m_thread_list.GetSize(false) == 0 ||
1186 stop_id != m_thread_list.GetStopID()) {
Jim Ingham18930652020-03-18 12:05:08 -07001187 bool clear_unused_threads = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001188 const StateType state = GetPrivateState();
1189 if (StateIsStoppedState(state, true)) {
1190 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Jim Ingham18930652020-03-18 12:05:08 -07001191 m_thread_list.SetStopID(stop_id);
1192
Adrian Prantl05097242018-04-30 16:49:04 +00001193 // m_thread_list does have its own mutex, but we need to hold onto the
1194 // mutex between the call to UpdateThreadList(...) and the
1195 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001196 ThreadList &old_thread_list = m_thread_list;
1197 ThreadList real_thread_list(this);
1198 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001199 // Always update the thread list with the protocol specific thread list,
1200 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1202 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001203 // are shutting down, since that may call back into the SBAPI's,
1204 // requiring the API lock which is already held by whoever is shutting
1205 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 OperatingSystem *os = GetOperatingSystem();
1207 if (os && !m_destroy_in_process) {
1208 // Clear any old backing threads where memory threads might have been
1209 // backed by actual threads from the lldb_private::Process subclass
1210 size_t num_old_threads = old_thread_list.GetSize(false);
1211 for (size_t i = 0; i < num_old_threads; ++i)
1212 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Jim Ingham18930652020-03-18 12:05:08 -07001213 // See if the OS plugin reports all threads. If it does, then
1214 // it is safe to clear unseen thread's plans here. Otherwise we
1215 // should preserve them in case they show up again:
1216 clear_unused_threads = GetTarget().GetOSPluginReportsAllThreads();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217
1218 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001219 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001220 // dynamic type or not and we need to avoid this. OperatingSystem
1221 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001222
1223 Target &target = GetTarget();
1224 const lldb::DynamicValueType saved_prefer_dynamic =
1225 target.GetPreferDynamicValue();
1226 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1227 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1228
1229 // Now let the OperatingSystem plug-in update the thread list
1230
1231 os->UpdateThreadList(
1232 old_thread_list, // Old list full of threads created by OS plug-in
1233 real_thread_list, // The actual thread list full of threads
1234 // created by each lldb_private::Process
1235 // subclass
1236 new_thread_list); // The new thread list that we will show to the
1237 // user that gets filled in
1238
1239 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1240 target.SetPreferDynamicValue(saved_prefer_dynamic);
1241 } else {
1242 // No OS plug-in, the new thread list is the same as the real thread
Jim Ingham18930652020-03-18 12:05:08 -07001243 // list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001244 new_thread_list = real_thread_list;
1245 }
1246
1247 m_thread_list_real.Update(real_thread_list);
1248 m_thread_list.Update(new_thread_list);
1249 m_thread_list.SetStopID(stop_id);
1250
1251 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1252 // Clear any extended threads that we may have accumulated previously
1253 m_extended_thread_list.Clear();
1254 m_extended_thread_stop_id = GetLastNaturalStopID();
1255
1256 m_queue_list.Clear();
1257 m_queue_list_stop_id = GetLastNaturalStopID();
1258 }
1259 }
Jim Ingham18930652020-03-18 12:05:08 -07001260 // Now update the plan stack map.
1261 // If we do have an OS plugin, any absent real threads in the
1262 // m_thread_list have already been removed from the ThreadPlanStackMap.
1263 // So any remaining threads are OS Plugin threads, and those we want to
1264 // preserve in case they show up again.
1265 m_thread_plans.Update(m_thread_list, clear_unused_threads);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 }
1267 }
1268}
1269
Jim Ingham61e8e682020-03-10 16:18:11 -07001270ThreadPlanStack *Process::FindThreadPlans(lldb::tid_t tid) {
1271 return m_thread_plans.Find(tid);
1272}
1273
Jim Ingham18930652020-03-18 12:05:08 -07001274bool Process::PruneThreadPlansForTID(lldb::tid_t tid) {
1275 return m_thread_plans.PrunePlansForTID(tid);
Jim Ingham61e8e682020-03-10 16:18:11 -07001276}
1277
Jim Ingham18930652020-03-18 12:05:08 -07001278void Process::PruneThreadPlans() {
1279 m_thread_plans.Update(GetThreadList(), true, false);
1280}
1281
1282bool Process::DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid,
1283 lldb::DescriptionLevel desc_level,
1284 bool internal, bool condense_trivial,
1285 bool skip_unreported_plans) {
1286 return m_thread_plans.DumpPlansForTID(
1287 strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
1288}
1289void Process::DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,
1290 bool internal, bool condense_trivial,
1291 bool skip_unreported_plans) {
1292 m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
1293 skip_unreported_plans);
Jim Ingham61e8e682020-03-10 16:18:11 -07001294}
1295
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296void Process::UpdateQueueListIfNeeded() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001297 if (m_system_runtime_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298 if (m_queue_list.GetSize() == 0 ||
1299 m_queue_list_stop_id != GetLastNaturalStopID()) {
1300 const StateType state = GetPrivateState();
1301 if (StateIsStoppedState(state, true)) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001302 m_system_runtime_up->PopulateQueueList(m_queue_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 m_queue_list_stop_id = GetLastNaturalStopID();
1304 }
1305 }
1306 }
1307}
1308
1309ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1310 OperatingSystem *os = GetOperatingSystem();
1311 if (os)
1312 return os->CreateThread(tid, context);
1313 return ThreadSP();
1314}
1315
1316uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1317 return AssignIndexIDToThread(thread_id);
1318}
1319
1320bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1321 return (m_thread_id_to_index_id_map.find(thread_id) !=
1322 m_thread_id_to_index_id_map.end());
1323}
1324
1325uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1326 uint32_t result = 0;
1327 std::map<uint64_t, uint32_t>::iterator iterator =
1328 m_thread_id_to_index_id_map.find(thread_id);
1329 if (iterator == m_thread_id_to_index_id_map.end()) {
1330 result = ++m_thread_index_id;
1331 m_thread_id_to_index_id_map[thread_id] = result;
1332 } else {
1333 result = iterator->second;
1334 }
1335
1336 return result;
1337}
1338
1339StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001340 return m_public_state.GetValue();
1341}
1342
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343void Process::SetPublicState(StateType new_state, bool restarted) {
1344 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1345 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001346 LLDB_LOGF(log, "Process::SetPublicState (state = %s, restarted = %i)",
1347 StateAsCString(new_state), restarted);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001348 const StateType old_state = m_public_state.GetValue();
1349 m_public_state.SetValue(new_state);
1350
Adrian Prantl05097242018-04-30 16:49:04 +00001351 // On the transition from Run to Stopped, we unlock the writer end of the run
1352 // lock. The lock gets locked in Resume, which is the public API to tell the
1353 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001354 if (!StateChangedIsExternallyHijacked()) {
1355 if (new_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001356 LLDB_LOGF(log,
1357 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1358 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001359 m_public_run_lock.SetStopped();
1360 } else {
1361 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1362 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1363 if ((old_state_is_stopped != new_state_is_stopped)) {
1364 if (new_state_is_stopped && !restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001365 LLDB_LOGF(log, "Process::SetPublicState (%s) -- unlocking run lock",
1366 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001367 m_public_run_lock.SetStopped();
1368 }
1369 }
1370 }
1371 }
1372}
1373
Zachary Turner97206d52017-05-12 04:51:55 +00001374Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001375 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1376 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001377 LLDB_LOGF(log, "Process::Resume -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001378 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001379 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001380 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001381 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001383 Status error = PrivateResume();
1384 if (!error.Success()) {
1385 // Undo running state change
1386 m_public_run_lock.SetStopped();
1387 }
1388 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001389}
1390
Jim Ingham3139fc92019-03-01 18:13:38 +00001391static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1392
Zachary Turner97206d52017-05-12 04:51:55 +00001393Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001394 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1395 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001396 LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001398 Status error("Resume request failed - process still running.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001399 LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001400 return error;
1401 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001402
Kate Stoneb9c1b512016-09-06 20:57:50 +00001403 ListenerSP listener_sp(
Jim Ingham3139fc92019-03-01 18:13:38 +00001404 Listener::MakeListener(g_resume_sync_name));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001405 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001406
Zachary Turner97206d52017-05-12 04:51:55 +00001407 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001408 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001409 StateType state =
Konrad Kleine248a1302019-05-23 11:14:47 +00001410 WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001411 const bool must_be_alive =
1412 false; // eStateExited is ok, so this must be false
1413 if (!StateIsStoppedState(state, must_be_alive))
1414 error.SetErrorStringWithFormat(
1415 "process not in stopped state after synchronous resume: %s",
1416 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001417 } else {
1418 // Undo running state change
1419 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001420 }
Ed Mastec29693f2013-07-02 16:35:47 +00001421
Kate Stoneb9c1b512016-09-06 20:57:50 +00001422 // Undo the hijacking of process events...
1423 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001424
Kate Stoneb9c1b512016-09-06 20:57:50 +00001425 return error;
1426}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001427
Jim Ingham3139fc92019-03-01 18:13:38 +00001428bool Process::StateChangedIsExternallyHijacked() {
1429 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1430 const char *hijacking_name = GetHijackingListenerName();
1431 if (hijacking_name &&
1432 strcmp(hijacking_name, g_resume_sync_name))
1433 return true;
1434 }
1435 return false;
1436}
1437
1438bool Process::StateChangedIsHijackedForSynchronousResume() {
1439 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1440 const char *hijacking_name = GetHijackingListenerName();
1441 if (hijacking_name &&
1442 strcmp(hijacking_name, g_resume_sync_name) == 0)
1443 return true;
1444 }
1445 return false;
1446}
1447
Kate Stoneb9c1b512016-09-06 20:57:50 +00001448StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001449
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450void Process::SetPrivateState(StateType new_state) {
1451 if (m_finalize_called)
1452 return;
1453
1454 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1455 LIBLLDB_LOG_PROCESS));
1456 bool state_changed = false;
1457
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001458 LLDB_LOGF(log, "Process::SetPrivateState (%s)", StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001459
1460 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1461 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1462
1463 const StateType old_state = m_private_state.GetValueNoLock();
1464 state_changed = old_state != new_state;
1465
1466 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1467 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1468 if (old_state_is_stopped != new_state_is_stopped) {
1469 if (new_state_is_stopped)
1470 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001471 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001472 m_private_run_lock.SetRunning();
1473 }
1474
1475 if (state_changed) {
1476 m_private_state.SetValueNoLock(new_state);
1477 EventSP event_sp(
1478 new Event(eBroadcastBitStateChanged,
1479 new ProcessEventData(shared_from_this(), new_state)));
1480 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001481 // Note, this currently assumes that all threads in the list stop when
1482 // the process stops. In the future we will want to support a debugging
1483 // model where some threads continue to run while others are stopped.
1484 // When that happens we will either need a way for the thread list to
1485 // identify which threads are stopping or create a special thread list
1486 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001487 //
Adrian Prantl05097242018-04-30 16:49:04 +00001488 // The process plugin is responsible for managing the actual behavior of
1489 // the threads and should have stopped any threads that are going to stop
1490 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001491 m_thread_list.DidStop();
1492
1493 m_mod_id.BumpStopID();
1494 if (!m_mod_id.IsLastResumeForUserExpression())
1495 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1496 m_memory_cache.Clear();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001497 LLDB_LOGF(log, "Process::SetPrivateState (%s) stop_id = %u",
1498 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001499 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001500
Kate Stoneb9c1b512016-09-06 20:57:50 +00001501 // Use our target to get a shared pointer to ourselves...
1502 if (m_finalize_called && !PrivateStateThreadIsValid())
1503 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001504 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001505 m_private_state_broadcaster.BroadcastEvent(event_sp);
1506 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001507 LLDB_LOGF(log,
1508 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1509 StateAsCString(new_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001510 }
Jim Ingham22777012010-09-23 02:01:19 +00001511}
1512
Kate Stoneb9c1b512016-09-06 20:57:50 +00001513void Process::SetRunningUserExpression(bool on) {
1514 m_mod_id.SetRunningUserExpression(on);
1515}
1516
Raphael Isemannc01783a2018-08-29 22:50:54 +00001517void Process::SetRunningUtilityFunction(bool on) {
1518 m_mod_id.SetRunningUtilityFunction(on);
1519}
1520
Kate Stoneb9c1b512016-09-06 20:57:50 +00001521addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1522
1523const lldb::ABISP &Process::GetABI() {
1524 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001525 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001526 return m_abi_sp;
1527}
1528
Davide Italianocec82632019-12-03 16:54:04 -08001529std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
Alex Langford03e1a822019-05-29 18:08:22 +00001530 std::vector<LanguageRuntime *> language_runtimes;
1531
1532 if (m_finalizing)
1533 return language_runtimes;
1534
1535 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1536 // Before we pass off a copy of the language runtimes, we must make sure that
1537 // our collection is properly populated. It's possible that some of the
1538 // language runtimes were not loaded yet, either because nobody requested it
1539 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1540 // hadn't been loaded).
1541 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
Davide Italianocec82632019-12-03 16:54:04 -08001542 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
Alex Langford03e1a822019-05-29 18:08:22 +00001543 language_runtimes.emplace_back(runtime);
1544 }
1545
1546 return language_runtimes;
1547}
1548
Davide Italianocec82632019-12-03 16:54:04 -08001549LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001550 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001551 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001552
Alex Langford7d3e97f2019-05-29 21:07:53 +00001553 LanguageRuntime *runtime = nullptr;
1554
Alex Langford74eb76f2019-05-22 23:01:18 +00001555 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001556 LanguageRuntimeCollection::iterator pos;
1557 pos = m_language_runtimes.find(language);
Davide Italianocec82632019-12-03 16:54:04 -08001558 if (pos == m_language_runtimes.end() || !pos->second) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001559 lldb::LanguageRuntimeSP runtime_sp(
1560 LanguageRuntime::FindPlugin(this, language));
1561
1562 m_language_runtimes[language] = runtime_sp;
Alex Langford7d3e97f2019-05-29 21:07:53 +00001563 runtime = runtime_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001564 } else
Alex Langford7d3e97f2019-05-29 21:07:53 +00001565 runtime = pos->second.get();
1566
1567 if (runtime)
1568 // It's possible that a language runtime can support multiple LanguageTypes,
1569 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1570 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1571 // primary language type and make sure that our runtime supports it.
1572 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1573
1574 return runtime;
Jim Ingham22777012010-09-23 02:01:19 +00001575}
1576
Kate Stoneb9c1b512016-09-06 20:57:50 +00001577bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1578 if (m_finalizing)
1579 return false;
1580
1581 if (in_value.IsDynamic())
1582 return false;
1583 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1584
1585 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1586 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1587 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1588 }
1589
Alex Langford41dc5522019-05-30 21:03:53 +00001590 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1591 if (runtime->CouldHaveDynamicValue(in_value))
1592 return true;
1593 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001594
Alex Langford41dc5522019-05-30 21:03:53 +00001595 return false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001596}
1597
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001599 m_dynamic_checkers_up.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001600}
1601
Kate Stoneb9c1b512016-09-06 20:57:50 +00001602BreakpointSiteList &Process::GetBreakpointSiteList() {
1603 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001604}
1605
Kate Stoneb9c1b512016-09-06 20:57:50 +00001606const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1607 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001608}
1609
Kate Stoneb9c1b512016-09-06 20:57:50 +00001610void Process::DisableAllBreakpointSites() {
1611 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1612 // bp_site->SetEnabled(true);
1613 DisableBreakpointSite(bp_site);
1614 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001615}
1616
Zachary Turner97206d52017-05-12 04:51:55 +00001617Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1618 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001619
Kate Stoneb9c1b512016-09-06 20:57:50 +00001620 if (error.Success())
1621 m_breakpoint_site_list.Remove(break_id);
1622
1623 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001624}
1625
Zachary Turner97206d52017-05-12 04:51:55 +00001626Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1627 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001628 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1629 if (bp_site_sp) {
1630 if (bp_site_sp->IsEnabled())
1631 error = DisableBreakpointSite(bp_site_sp.get());
1632 } else {
1633 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1634 break_id);
1635 }
1636
1637 return error;
1638}
1639
Zachary Turner97206d52017-05-12 04:51:55 +00001640Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1641 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001642 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1643 if (bp_site_sp) {
1644 if (!bp_site_sp->IsEnabled())
1645 error = EnableBreakpointSite(bp_site_sp.get());
1646 } else {
1647 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1648 break_id);
1649 }
1650 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001651}
1652
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001653lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001654Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1655 bool use_hardware) {
1656 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001657
Kate Stoneb9c1b512016-09-06 20:57:50 +00001658 bool show_error = true;
1659 switch (GetState()) {
1660 case eStateInvalid:
1661 case eStateUnloaded:
1662 case eStateConnected:
1663 case eStateAttaching:
1664 case eStateLaunching:
1665 case eStateDetached:
1666 case eStateExited:
1667 show_error = false;
1668 break;
1669
1670 case eStateStopped:
1671 case eStateRunning:
1672 case eStateStepping:
1673 case eStateCrashed:
1674 case eStateSuspended:
1675 show_error = IsAlive();
1676 break;
1677 }
1678
Adrian Prantl05097242018-04-30 16:49:04 +00001679 // Reset the IsIndirect flag here, in case the location changes from pointing
1680 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001681 owner->SetIsIndirect(false);
1682
1683 if (owner->ShouldResolveIndirectFunctions()) {
1684 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1685 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001686 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001687 Address symbol_address = symbol->GetAddress();
1688 load_addr = ResolveIndirectFunction(&symbol_address, error);
1689 if (!error.Success() && show_error) {
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001690 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001691 "warning: failed to resolve indirect function at 0x%" PRIx64
1692 " for breakpoint %i.%i: %s\n",
1693 symbol->GetLoadAddress(&GetTarget()),
1694 owner->GetBreakpoint().GetID(), owner->GetID(),
1695 error.AsCString() ? error.AsCString() : "unknown error");
1696 return LLDB_INVALID_BREAK_ID;
1697 }
1698 Address resolved_address(load_addr);
1699 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1700 owner->SetIsIndirect(true);
1701 } else
1702 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1703 } else
1704 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1705
1706 if (load_addr != LLDB_INVALID_ADDRESS) {
1707 BreakpointSiteSP bp_site_sp;
1708
1709 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001710 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001711
1712 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1713
1714 if (bp_site_sp) {
1715 bp_site_sp->AddOwner(owner);
1716 owner->SetBreakpointSite(bp_site_sp);
1717 return bp_site_sp->GetID();
1718 } else {
1719 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1720 load_addr, use_hardware));
1721 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001722 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001723 if (error.Success()) {
1724 owner->SetBreakpointSite(bp_site_sp);
1725 return m_breakpoint_site_list.Add(bp_site_sp);
1726 } else {
Jonas Devliegheree103ae92018-11-15 01:18:15 +00001727 if (show_error || use_hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001728 // Report error for setting breakpoint...
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00001729 GetTarget().GetDebugger().GetErrorStream().Printf(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730 "warning: failed to set breakpoint site at 0x%" PRIx64
1731 " for breakpoint %i.%i: %s\n",
1732 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1733 error.AsCString() ? error.AsCString() : "unknown error");
1734 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001735 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001736 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001737 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001738 }
1739 // We failed to enable the breakpoint
1740 return LLDB_INVALID_BREAK_ID;
1741}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001742
Kate Stoneb9c1b512016-09-06 20:57:50 +00001743void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1744 lldb::user_id_t owner_loc_id,
1745 BreakpointSiteSP &bp_site_sp) {
1746 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1747 if (num_owners == 0) {
1748 // Don't try to disable the site if we don't have a live process anymore.
1749 if (IsAlive())
1750 DisableBreakpointSite(bp_site_sp.get());
1751 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1752 }
1753}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001754
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1756 uint8_t *buf) const {
1757 size_t bytes_removed = 0;
1758 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001759
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1761 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001762 bp_sites_in_range.ForEach([bp_addr, size,
1763 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001764 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1765 addr_t intersect_addr;
1766 size_t intersect_size;
1767 size_t opcode_offset;
1768 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1769 &intersect_size, &opcode_offset)) {
1770 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1771 assert(bp_addr < intersect_addr + intersect_size &&
1772 intersect_addr + intersect_size <= bp_addr + size);
1773 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1774 size_t buf_offset = intersect_addr - bp_addr;
1775 ::memcpy(buf + buf_offset,
1776 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1777 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001778 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001779 }
1780 });
1781 }
1782 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001783}
1784
Kate Stoneb9c1b512016-09-06 20:57:50 +00001785size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1786 PlatformSP platform_sp(GetTarget().GetPlatform());
1787 if (platform_sp)
1788 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1789 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001790}
1791
Zachary Turner97206d52017-05-12 04:51:55 +00001792Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1793 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001794 assert(bp_site != nullptr);
1795 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1796 const addr_t bp_addr = bp_site->GetLoadAddress();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001797 LLDB_LOGF(
1798 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1799 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001800 if (bp_site->IsEnabled()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001801 LLDB_LOGF(
1802 log,
1803 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1804 " -- already enabled",
1805 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001806 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001807 }
1808
1809 if (bp_addr == LLDB_INVALID_ADDRESS) {
1810 error.SetErrorString("BreakpointSite contains an invalid load address.");
1811 return error;
1812 }
1813 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1814 // trap for the breakpoint site
1815 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1816
1817 if (bp_opcode_size == 0) {
1818 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1819 "returned zero, unable to get breakpoint "
1820 "trap for address 0x%" PRIx64,
1821 bp_addr);
1822 } else {
1823 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1824
1825 if (bp_opcode_bytes == nullptr) {
1826 error.SetErrorString(
1827 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1828 return error;
1829 }
1830
1831 // Save the original opcode by reading it
1832 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1833 error) == bp_opcode_size) {
1834 // Write a software breakpoint in place of the original opcode
1835 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1836 bp_opcode_size) {
1837 uint8_t verify_bp_opcode_bytes[64];
1838 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1839 error) == bp_opcode_size) {
1840 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1841 bp_opcode_size) == 0) {
1842 bp_site->SetEnabled(true);
1843 bp_site->SetType(BreakpointSite::eSoftware);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001844 LLDB_LOGF(log,
1845 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1846 "addr = 0x%" PRIx64 " -- SUCCESS",
1847 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001848 } else
1849 error.SetErrorString(
1850 "failed to verify the breakpoint trap in memory.");
1851 } else
1852 error.SetErrorString(
1853 "Unable to read memory to verify breakpoint trap.");
1854 } else
1855 error.SetErrorString("Unable to write breakpoint trap to memory.");
1856 } else
1857 error.SetErrorString("Unable to read memory at breakpoint address.");
1858 }
1859 if (log && error.Fail())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001860 LLDB_LOGF(
1861 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1863 " -- FAILED: %s",
1864 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1865 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001866}
1867
Zachary Turner97206d52017-05-12 04:51:55 +00001868Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1869 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001870 assert(bp_site != nullptr);
1871 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1872 addr_t bp_addr = bp_site->GetLoadAddress();
1873 lldb::user_id_t breakID = bp_site->GetID();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001874 LLDB_LOGF(log,
1875 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1876 ") addr = 0x%" PRIx64,
1877 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001878
Kate Stoneb9c1b512016-09-06 20:57:50 +00001879 if (bp_site->IsHardware()) {
1880 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1881 } else if (bp_site->IsEnabled()) {
1882 const size_t break_op_size = bp_site->GetByteSize();
1883 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1884 if (break_op_size > 0) {
1885 // Clear a software breakpoint instruction
1886 uint8_t curr_break_op[8];
1887 assert(break_op_size <= sizeof(curr_break_op));
1888 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001889
Kate Stoneb9c1b512016-09-06 20:57:50 +00001890 // Read the breakpoint opcode
1891 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1892 break_op_size) {
1893 bool verify = false;
1894 // Make sure the breakpoint opcode exists at this address
1895 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1896 break_op_found = true;
1897 // We found a valid breakpoint opcode at this address, now restore
1898 // the saved opcode.
1899 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1900 break_op_size, error) == break_op_size) {
1901 verify = true;
1902 } else
1903 error.SetErrorString(
1904 "Memory write failed when restoring original opcode.");
1905 } else {
1906 error.SetErrorString(
1907 "Original breakpoint trap is no longer in memory.");
1908 // Set verify to true and so we can check if the original opcode has
1909 // already been restored
1910 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001911 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001912
Kate Stoneb9c1b512016-09-06 20:57:50 +00001913 if (verify) {
1914 uint8_t verify_opcode[8];
1915 assert(break_op_size < sizeof(verify_opcode));
1916 // Verify that our original opcode made it back to the inferior
1917 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1918 break_op_size) {
1919 // compare the memory we just read with the original opcode
1920 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1921 break_op_size) == 0) {
1922 // SUCCESS
1923 bp_site->SetEnabled(false);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001924 LLDB_LOGF(log,
1925 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1926 "addr = 0x%" PRIx64 " -- SUCCESS",
1927 bp_site->GetID(), (uint64_t)bp_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001928 return error;
1929 } else {
1930 if (break_op_found)
1931 error.SetErrorString("Failed to restore original opcode.");
1932 }
1933 } else
1934 error.SetErrorString("Failed to read memory to verify that "
1935 "breakpoint trap was restored.");
1936 }
1937 } else
1938 error.SetErrorString(
1939 "Unable to read memory that should contain the breakpoint trap.");
1940 }
1941 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001942 LLDB_LOGF(
1943 log,
1944 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1945 " -- already disabled",
1946 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001947 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001948 }
1949
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001950 LLDB_LOGF(
1951 log,
1952 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1953 " -- FAILED: %s",
1954 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001956}
1957
Adrian Prantl05097242018-04-30 16:49:04 +00001958// Uncomment to verify memory caching works after making changes to caching
1959// code
Greg Clayton58be07b2011-01-07 06:08:19 +00001960//#define VERIFY_MEMORY_READS
1961
Zachary Turner97206d52017-05-12 04:51:55 +00001962size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001963 error.Clear();
1964 if (!GetDisableMemoryCache()) {
1965#if defined(VERIFY_MEMORY_READS)
1966 // Memory caching is enabled, with debug verification
1967
1968 if (buf && size) {
1969 // Uncomment the line below to make sure memory caching is working.
1970 // I ran this through the test suite and got no assertions, so I am
1971 // pretty confident this is working well. If any changes are made to
1972 // memory caching, uncomment the line below and test your changes!
1973
1974 // Verify all memory reads by using the cache first, then redundantly
1975 // reading the same memory from the inferior and comparing to make sure
1976 // everything is exactly the same.
1977 std::string verify_buf(size, '\0');
1978 assert(verify_buf.size() == size);
1979 const size_t cache_bytes_read =
1980 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00001981 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001982 const size_t verify_bytes_read =
1983 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1984 verify_buf.size(), verify_error);
1985 assert(cache_bytes_read == verify_bytes_read);
1986 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1987 assert(verify_error.Success() == error.Success());
1988 return cache_bytes_read;
1989 }
1990 return 0;
1991#else // !defined(VERIFY_MEMORY_READS)
1992 // Memory caching is enabled, without debug verification
1993
1994 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00001995#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001996 } else {
1997 // Memory caching is disabled
1998
1999 return ReadMemoryFromInferior(addr, buf, size, error);
2000 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002001}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002002
2003size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00002004 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002005 char buf[256];
2006 out_str.clear();
2007 addr_t curr_addr = addr;
2008 while (true) {
2009 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2010 if (length == 0)
2011 break;
2012 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00002013 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2014 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00002015 if (length == sizeof(buf) - 1)
2016 curr_addr += length;
2017 else
2018 break;
2019 }
2020 return out_str.size();
2021}
2022
2023size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00002024 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002025 size_t total_bytes_read = 0;
2026 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00002027 // Ensure a null terminator independent of the number of bytes that is
2028 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002029 memset(dst, 0, max_bytes);
2030 size_t bytes_left = max_bytes - type_width;
2031
2032 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2033 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2034 "string with more than 4 bytes "
2035 "per character!");
2036
Greg Clayton4c82d422012-05-18 23:20:01 +00002037 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002038 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2039 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002040
Kate Stoneb9c1b512016-09-06 20:57:50 +00002041 error.Clear();
2042 while (bytes_left > 0 && error.Success()) {
2043 addr_t cache_line_bytes_left =
2044 cache_line_size - (curr_addr % cache_line_size);
2045 addr_t bytes_to_read =
2046 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2047 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002048
Kate Stoneb9c1b512016-09-06 20:57:50 +00002049 if (bytes_read == 0)
2050 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002051
Kate Stoneb9c1b512016-09-06 20:57:50 +00002052 // Search for a null terminator of correct size and alignment in
2053 // bytes_read
2054 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2055 for (size_t i = aligned_start;
2056 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2057 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2058 error.Clear();
2059 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002060 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002061
2062 total_bytes_read += bytes_read;
2063 curr_dst += bytes_read;
2064 curr_addr += bytes_read;
2065 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002066 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002067 } else {
2068 if (max_bytes)
2069 error.SetErrorString("invalid arguments");
2070 }
2071 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002072}
2073
Kate Stoneb9c1b512016-09-06 20:57:50 +00002074// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002075// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002076size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002077 size_t dst_max_len,
2078 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002079 size_t total_cstr_len = 0;
2080 if (dst && dst_max_len) {
2081 result_error.Clear();
2082 // NULL out everything just to be safe
2083 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002084 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002085 addr_t curr_addr = addr;
2086 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2087 size_t bytes_left = dst_max_len - 1;
2088 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002089
Kate Stoneb9c1b512016-09-06 20:57:50 +00002090 while (bytes_left > 0) {
2091 addr_t cache_line_bytes_left =
2092 cache_line_size - (curr_addr % cache_line_size);
2093 addr_t bytes_to_read =
2094 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2095 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002096
Kate Stoneb9c1b512016-09-06 20:57:50 +00002097 if (bytes_read == 0) {
2098 result_error = error;
2099 dst[total_cstr_len] = '\0';
2100 break;
2101 }
2102 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002103
Kate Stoneb9c1b512016-09-06 20:57:50 +00002104 total_cstr_len += len;
2105
2106 if (len < bytes_to_read)
2107 break;
2108
2109 curr_dst += bytes_read;
2110 curr_addr += bytes_read;
2111 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002112 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002113 } else {
2114 if (dst == nullptr)
2115 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002116 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002117 result_error.Clear();
2118 }
2119 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002120}
2121
Kate Stoneb9c1b512016-09-06 20:57:50 +00002122size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002123 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002124 if (buf == nullptr || size == 0)
2125 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126
Kate Stoneb9c1b512016-09-06 20:57:50 +00002127 size_t bytes_read = 0;
2128 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002129
Kate Stoneb9c1b512016-09-06 20:57:50 +00002130 while (bytes_read < size) {
2131 const size_t curr_size = size - bytes_read;
2132 const size_t curr_bytes_read =
2133 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2134 bytes_read += curr_bytes_read;
2135 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2136 break;
2137 }
2138
2139 // Replace any software breakpoint opcodes that fall into this range back
2140 // into "buf" before we return
2141 if (bytes_read > 0)
2142 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2143 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144}
2145
Kate Stoneb9c1b512016-09-06 20:57:50 +00002146uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2147 size_t integer_byte_size,
2148 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002149 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002150 Scalar scalar;
2151 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2152 error))
2153 return scalar.ULongLong(fail_value);
2154 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002155}
2156
Kate Stoneb9c1b512016-09-06 20:57:50 +00002157int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2158 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002159 int64_t fail_value,
2160 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002161 Scalar scalar;
2162 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2163 error))
2164 return scalar.SLongLong(fail_value);
2165 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002166}
2167
Zachary Turner97206d52017-05-12 04:51:55 +00002168addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 Scalar scalar;
2170 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2171 error))
2172 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2173 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002174}
2175
Kate Stoneb9c1b512016-09-06 20:57:50 +00002176bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002177 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002178 Scalar scalar;
2179 const uint32_t addr_byte_size = GetAddressByteSize();
2180 if (addr_byte_size <= 4)
2181 scalar = (uint32_t)ptr_value;
2182 else
2183 scalar = ptr_value;
2184 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2185 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002186}
2187
Kate Stoneb9c1b512016-09-06 20:57:50 +00002188size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002189 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002190 size_t bytes_written = 0;
2191 const uint8_t *bytes = (const uint8_t *)buf;
2192
2193 while (bytes_written < size) {
2194 const size_t curr_size = size - bytes_written;
2195 const size_t curr_bytes_written = DoWriteMemory(
2196 addr + bytes_written, bytes + bytes_written, curr_size, error);
2197 bytes_written += curr_bytes_written;
2198 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2199 break;
2200 }
2201 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002202}
2203
Kate Stoneb9c1b512016-09-06 20:57:50 +00002204size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002205 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002206#if defined(ENABLE_MEMORY_CACHING)
2207 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002208#endif
2209
Kate Stoneb9c1b512016-09-06 20:57:50 +00002210 if (buf == nullptr || size == 0)
2211 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002212
Kate Stoneb9c1b512016-09-06 20:57:50 +00002213 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002214
Kate Stoneb9c1b512016-09-06 20:57:50 +00002215 // We need to write any data that would go where any current software traps
2216 // (enabled software breakpoints) any software traps (breakpoints) that we
2217 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002218
Kate Stoneb9c1b512016-09-06 20:57:50 +00002219 BreakpointSiteList bp_sites_in_range;
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002220 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002221 return WriteMemoryPrivate(addr, buf, size, error);
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002222
2223 // No breakpoint sites overlap
2224 if (bp_sites_in_range.IsEmpty())
2225 return WriteMemoryPrivate(addr, buf, size, error);
2226
2227 const uint8_t *ubuf = (const uint8_t *)buf;
2228 uint64_t bytes_written = 0;
2229
2230 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2231 &error](BreakpointSite *bp) -> void {
2232 if (error.Fail())
2233 return;
2234
2235 addr_t intersect_addr;
2236 size_t intersect_size;
2237 size_t opcode_offset;
2238 const bool intersects = bp->IntersectsRange(
2239 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2240 UNUSED_IF_ASSERT_DISABLED(intersects);
2241 assert(intersects);
2242 assert(addr <= intersect_addr && intersect_addr < addr + size);
2243 assert(addr < intersect_addr + intersect_size &&
2244 intersect_addr + intersect_size <= addr + size);
2245 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2246
2247 // Check for bytes before this breakpoint
2248 const addr_t curr_addr = addr + bytes_written;
2249 if (intersect_addr > curr_addr) {
2250 // There are some bytes before this breakpoint that we need to just
2251 // write to memory
2252 size_t curr_size = intersect_addr - curr_addr;
2253 size_t curr_bytes_written =
2254 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2255 bytes_written += curr_bytes_written;
2256 if (curr_bytes_written != curr_size) {
2257 // We weren't able to write all of the requested bytes, we are
2258 // done looping and will return the number of bytes that we have
2259 // written so far.
2260 if (error.Success())
2261 error.SetErrorToGenericError();
2262 }
2263 }
2264 // Now write any bytes that would cover up any software breakpoints
2265 // directly into the breakpoint opcode buffer
2266 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2267 intersect_size);
2268 bytes_written += intersect_size;
2269 });
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270
2271 // Write any remaining bytes after the last breakpoint if we have any left
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002272 if (bytes_written < size)
2273 bytes_written +=
2274 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2275 size - bytes_written, error);
2276
2277 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002278}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002279
Kate Stoneb9c1b512016-09-06 20:57:50 +00002280size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002281 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002282 if (byte_size == UINT32_MAX)
2283 byte_size = scalar.GetByteSize();
2284 if (byte_size > 0) {
2285 uint8_t buf[32];
2286 const size_t mem_size =
2287 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2288 if (mem_size > 0)
2289 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002290 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002291 error.SetErrorString("failed to get scalar as memory data");
2292 } else {
2293 error.SetErrorString("invalid scalar value");
2294 }
2295 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002296}
2297
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2299 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002300 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002301 uint64_t uval = 0;
2302 if (byte_size == 0) {
2303 error.SetErrorString("byte size is zero");
2304 } else if (byte_size & (byte_size - 1)) {
2305 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2306 byte_size);
2307 } else if (byte_size <= sizeof(uval)) {
2308 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2309 if (bytes_read == byte_size) {
2310 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2311 GetAddressByteSize());
2312 lldb::offset_t offset = 0;
2313 if (byte_size <= 4)
2314 scalar = data.GetMaxU32(&offset, byte_size);
2315 else
2316 scalar = data.GetMaxU64(&offset, byte_size);
2317 if (is_signed)
2318 scalar.SignExtend(byte_size * 8);
2319 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002320 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002321 } else {
2322 error.SetErrorStringWithFormat(
2323 "byte size of %u is too large for integer scalar type", byte_size);
2324 }
2325 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002326}
2327
Pavel Labath16064d32018-03-20 11:56:24 +00002328Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2329 Status error;
2330 for (const auto &Entry : entries) {
2331 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2332 error);
2333 if (!error.Success())
2334 break;
2335 }
2336 return error;
2337}
2338
Greg Claytond495c532011-05-17 03:37:42 +00002339#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002340addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002341 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002342 if (GetPrivateState() != eStateStopped) {
2343 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002344 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002345 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002346
2347#if defined(USE_ALLOCATE_MEMORY_CACHE)
2348 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002349#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002350 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2351 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002352 LLDB_LOGF(log,
2353 "Process::AllocateMemory(size=%" PRIu64
2354 ", permissions=%s) => 0x%16.16" PRIx64
2355 " (m_stop_id = %u m_memory_id = %u)",
2356 (uint64_t)size, GetPermissionsAsCString(permissions),
2357 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2358 m_mod_id.GetMemoryID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002360#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002361}
2362
Kate Stoneb9c1b512016-09-06 20:57:50 +00002363addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002364 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002365 addr_t return_addr = AllocateMemory(size, permissions, error);
2366 if (error.Success()) {
2367 std::string buffer(size, 0);
2368 WriteMemory(return_addr, buffer.c_str(), size, error);
2369 }
2370 return return_addr;
2371}
2372
2373bool Process::CanJIT() {
2374 if (m_can_jit == eCanJITDontKnow) {
2375 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002376 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002377
2378 uint64_t allocated_memory = AllocateMemory(
2379 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2380 err);
2381
2382 if (err.Success()) {
2383 m_can_jit = eCanJITYes;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002384 LLDB_LOGF(log,
2385 "Process::%s pid %" PRIu64
2386 " allocation test passed, CanJIT () is true",
2387 __FUNCTION__, GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002388 } else {
2389 m_can_jit = eCanJITNo;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002390 LLDB_LOGF(log,
2391 "Process::%s pid %" PRIu64
2392 " allocation test failed, CanJIT () is false: %s",
2393 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002394 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002395
2396 DeallocateMemory(allocated_memory);
2397 }
2398
2399 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002400}
2401
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402void Process::SetCanJIT(bool can_jit) {
2403 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002404}
2405
Kate Stoneb9c1b512016-09-06 20:57:50 +00002406void Process::SetCanRunCode(bool can_run_code) {
2407 SetCanJIT(can_run_code);
2408 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002409}
2410
Zachary Turner97206d52017-05-12 04:51:55 +00002411Status Process::DeallocateMemory(addr_t ptr) {
2412 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002413#if defined(USE_ALLOCATE_MEMORY_CACHE)
2414 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2415 error.SetErrorStringWithFormat(
2416 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2417 }
Greg Claytond495c532011-05-17 03:37:42 +00002418#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002419 error = DoDeallocateMemory(ptr);
2420
2421 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002422 LLDB_LOGF(log,
2423 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2424 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2425 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2426 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002427#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002428 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429}
2430
Kate Stoneb9c1b512016-09-06 20:57:50 +00002431ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2432 lldb::addr_t header_addr,
2433 size_t size_to_read) {
2434 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2435 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002436 LLDB_LOGF(log,
2437 "Process::ReadModuleFromMemory reading %s binary from memory",
2438 file_spec.GetPath().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002439 }
2440 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2441 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002442 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002443 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2444 shared_from_this(), header_addr, error, size_to_read);
2445 if (objfile)
2446 return module_sp;
2447 }
2448 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002449}
2450
Kate Stoneb9c1b512016-09-06 20:57:50 +00002451bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2452 uint32_t &permissions) {
2453 MemoryRegionInfo range_info;
2454 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002455 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002456 if (!error.Success())
2457 return false;
2458 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2459 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2460 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2461 return false;
2462 }
2463
2464 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2465 permissions |= lldb::ePermissionsReadable;
2466
2467 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2468 permissions |= lldb::ePermissionsWritable;
2469
2470 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2471 permissions |= lldb::ePermissionsExecutable;
2472
2473 return true;
2474}
2475
Zachary Turner97206d52017-05-12 04:51:55 +00002476Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2477 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002478 error.SetErrorString("watchpoints are not supported");
2479 return error;
2480}
2481
Zachary Turner97206d52017-05-12 04:51:55 +00002482Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2483 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002484 error.SetErrorString("watchpoints are not supported");
2485 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002486}
2487
2488StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002489Process::WaitForProcessStopPrivate(EventSP &event_sp,
2490 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002491 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002492
Kate Stoneb9c1b512016-09-06 20:57:50 +00002493 while (true) {
2494 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002495 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002496
Kate Stoneb9c1b512016-09-06 20:57:50 +00002497 if (StateIsStoppedState(state, false))
2498 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002499
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 // If state is invalid, then we timed out
2501 if (state == eStateInvalid)
2502 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002503
Kate Stoneb9c1b512016-09-06 20:57:50 +00002504 if (event_sp)
2505 HandlePrivateEvent(event_sp);
2506 }
2507 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002508}
2509
Kate Stoneb9c1b512016-09-06 20:57:50 +00002510void Process::LoadOperatingSystemPlugin(bool flush) {
2511 if (flush)
2512 m_thread_list.Clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002513 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514 if (flush)
2515 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002516}
2517
Zachary Turner97206d52017-05-12 04:51:55 +00002518Status Process::Launch(ProcessLaunchInfo &launch_info) {
2519 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002520 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002521 m_dyld_up.reset();
2522 m_jit_loaders_up.reset();
2523 m_system_runtime_up.reset();
2524 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002525 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002526
Kate Stoneb9c1b512016-09-06 20:57:50 +00002527 Module *exe_module = GetTarget().GetExecutableModulePointer();
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002528 if (!exe_module) {
2529 error.SetErrorString("executable module does not exist");
2530 return error;
2531 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002532
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002533 char local_exec_file_path[PATH_MAX];
2534 char platform_exec_file_path[PATH_MAX];
2535 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2536 sizeof(local_exec_file_path));
2537 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2538 sizeof(platform_exec_file_path));
2539 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2540 // Install anything that might need to be installed prior to launching.
2541 // For host systems, this will do nothing, but if we are connected to a
2542 // remote platform it will install any needed binaries
2543 error = GetTarget().Install(&launch_info);
2544 if (error.Fail())
2545 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002546
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002547 if (PrivateStateThreadIsValid())
2548 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002549
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002550 error = WillLaunch(exe_module);
2551 if (error.Success()) {
2552 const bool restarted = false;
2553 SetPublicState(eStateLaunching, restarted);
2554 m_should_detach = false;
2555
2556 if (m_public_run_lock.TrySetRunning()) {
2557 // Now launch using these arguments.
2558 error = DoLaunch(exe_module, launch_info);
2559 } else {
2560 // This shouldn't happen
2561 error.SetErrorString("failed to acquire process run lock");
2562 }
2563
2564 if (error.Fail()) {
2565 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2566 SetID(LLDB_INVALID_PROCESS_ID);
2567 const char *error_string = error.AsCString();
2568 if (error_string == nullptr)
2569 error_string = "launch failed";
2570 SetExitStatus(-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002571 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002572 } else {
2573 EventSP event_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002574
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002575 // Now wait for the process to launch and return control to us, and then
2576 // call DidLaunch:
2577 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Stella Stamenova36d457c2018-06-01 19:14:53 +00002578
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002579 if (state == eStateInvalid || !event_sp) {
2580 // We were able to launch the process, but we failed to catch the
2581 // initial stop.
2582 error.SetErrorString("failed to catch stop after launch");
2583 SetExitStatus(0, "failed to catch stop after launch");
2584 Destroy(false);
2585 } else if (state == eStateStopped || state == eStateCrashed) {
2586 DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002587
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002588 DynamicLoader *dyld = GetDynamicLoader();
2589 if (dyld)
2590 dyld->DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002591
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002592 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002593
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002594 SystemRuntime *system_runtime = GetSystemRuntime();
2595 if (system_runtime)
2596 system_runtime->DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002597
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002598 if (!m_os_up)
2599 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002600
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002601 // We successfully launched the process and stopped, now it the
2602 // right time to set up signal filters before resuming.
2603 UpdateAutomaticSignalFiltering();
Greg Clayton35824e32015-02-20 20:59:47 +00002604
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002605 // Note, the stop event was consumed above, but not handled. This
2606 // was done to give DidLaunch a chance to run. The target is either
2607 // stopped or crashed. Directly set the state. This is done to
2608 // prevent a stop message with a bunch of spurious output on thread
2609 // status, as well as not pop a ProcessIOHandler.
2610 SetPublicState(state, false);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002611
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002612 if (PrivateStateThreadIsValid())
2613 ResumePrivateStateThread();
2614 else
2615 StartPrivateStateThread();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002616
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002617 // Target was stopped at entry as was intended. Need to notify the
2618 // listeners about it.
2619 if (state == eStateStopped &&
2620 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002621 HandlePrivateEvent(event_sp);
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002622 } else if (state == eStateExited) {
2623 // We exited while trying to launch somehow. Don't call DidLaunch
2624 // as that's not likely to work, and return an invalid pid.
2625 HandlePrivateEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002626 }
2627 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002628 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002629 } else {
2630 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2631 local_exec_file_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002632 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002633
Kate Stoneb9c1b512016-09-06 20:57:50 +00002634 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002635}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002636
Zachary Turner97206d52017-05-12 04:51:55 +00002637Status Process::LoadCore() {
2638 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002639 if (error.Success()) {
2640 ListenerSP listener_sp(
2641 Listener::MakeListener("lldb.process.load_core_listener"));
2642 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002643
Kate Stoneb9c1b512016-09-06 20:57:50 +00002644 if (PrivateStateThreadIsValid())
2645 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002646 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002647 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002648
Kate Stoneb9c1b512016-09-06 20:57:50 +00002649 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002650 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002651 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002652
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002653 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002654
Kate Stoneb9c1b512016-09-06 20:57:50 +00002655 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002656 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002657 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002658
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002659 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00002660 LoadOperatingSystemPlugin(false);
2661
Kate Stoneb9c1b512016-09-06 20:57:50 +00002662 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002663 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002664 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002665
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002666 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002667 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002668 StateType state =
Pavel Labath7ada1c52019-06-25 07:14:29 +00002669 WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002670
2671 if (!StateIsStoppedState(state, false)) {
2672 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002673 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2674 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002675 error.SetErrorString(
2676 "Did not get stopped event after loading the core file.");
2677 }
2678 RestoreProcessEvents();
2679 }
2680 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002681}
2682
Kate Stoneb9c1b512016-09-06 20:57:50 +00002683DynamicLoader *Process::GetDynamicLoader() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002684 if (!m_dyld_up)
2685 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2686 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002687}
2688
Antonio Afonso943faef2019-06-11 20:16:13 +00002689DataExtractor Process::GetAuxvData() { return DataExtractor(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002690
2691JITLoaderList &Process::GetJITLoaders() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002692 if (!m_jit_loaders_up) {
2693 m_jit_loaders_up.reset(new JITLoaderList());
2694 JITLoader::LoadPlugins(this, *m_jit_loaders_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002695 }
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002696 return *m_jit_loaders_up;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002697}
2698
2699SystemRuntime *Process::GetSystemRuntime() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002700 if (!m_system_runtime_up)
2701 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2702 return m_system_runtime_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002703}
2704
2705Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2706 uint32_t exec_count)
2707 : NextEventAction(process), m_exec_count(exec_count) {
2708 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002709 LLDB_LOGF(
2710 log,
2711 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2712 __FUNCTION__, static_cast<void *>(process), exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713}
2714
2715Process::NextEventAction::EventActionResult
2716Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2717 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2718
2719 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002720 LLDB_LOGF(log,
2721 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2722 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723
2724 switch (state) {
2725 case eStateAttaching:
2726 return eEventActionSuccess;
2727
2728 case eStateRunning:
2729 case eStateConnected:
2730 return eEventActionRetry;
2731
2732 case eStateStopped:
2733 case eStateCrashed:
2734 // During attach, prior to sending the eStateStopped event,
2735 // lldb_private::Process subclasses must set the new process ID.
2736 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002737 // We don't want these events to be reported, so go set the
2738 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002739 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2740
2741 if (m_exec_count > 0) {
2742 --m_exec_count;
2743
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002744 LLDB_LOGF(log,
2745 "Process::AttachCompletionHandler::%s state %s: reduced "
2746 "remaining exec count to %" PRIu32 ", requesting resume",
2747 __FUNCTION__, StateAsCString(state), m_exec_count);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748
2749 RequestResume();
2750 return eEventActionRetry;
2751 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002752 LLDB_LOGF(log,
2753 "Process::AttachCompletionHandler::%s state %s: no more "
2754 "execs expected to start, continuing with attach",
2755 __FUNCTION__, StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002756
2757 m_process->CompleteAttach();
2758 return eEventActionSuccess;
2759 }
2760 break;
2761
2762 default:
2763 case eStateExited:
2764 case eStateInvalid:
2765 break;
2766 }
2767
2768 m_exit_string.assign("No valid Process");
2769 return eEventActionExit;
2770}
2771
2772Process::NextEventAction::EventActionResult
2773Process::AttachCompletionHandler::HandleBeingInterrupted() {
2774 return eEventActionSuccess;
2775}
2776
2777const char *Process::AttachCompletionHandler::GetExitString() {
2778 return m_exit_string.c_str();
2779}
2780
2781ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2782 if (m_listener_sp)
2783 return m_listener_sp;
2784 else
2785 return debugger.GetListener();
2786}
2787
Zachary Turner97206d52017-05-12 04:51:55 +00002788Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002789 m_abi_sp.reset();
2790 m_process_input_reader.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002791 m_dyld_up.reset();
2792 m_jit_loaders_up.reset();
2793 m_system_runtime_up.reset();
2794 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795
2796 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002797 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002798 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2799 char process_name[PATH_MAX];
2800
2801 if (attach_info.GetExecutableFile().GetPath(process_name,
2802 sizeof(process_name))) {
2803 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2804
2805 if (wait_for_launch) {
2806 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2807 if (error.Success()) {
2808 if (m_public_run_lock.TrySetRunning()) {
2809 m_should_detach = true;
2810 const bool restarted = false;
2811 SetPublicState(eStateAttaching, restarted);
2812 // Now attach using these arguments.
2813 error = DoAttachToProcessWithName(process_name, attach_info);
2814 } else {
2815 // This shouldn't happen
2816 error.SetErrorString("failed to acquire process run lock");
2817 }
2818
2819 if (error.Fail()) {
2820 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2821 SetID(LLDB_INVALID_PROCESS_ID);
2822 if (error.AsCString() == nullptr)
2823 error.SetErrorString("attach failed");
2824
2825 SetExitStatus(-1, error.AsCString());
2826 }
2827 } else {
2828 SetNextEventAction(new Process::AttachCompletionHandler(
2829 this, attach_info.GetResumeCount()));
2830 StartPrivateStateThread();
2831 }
2832 return error;
2833 }
2834 } else {
2835 ProcessInstanceInfoList process_infos;
2836 PlatformSP platform_sp(GetTarget().GetPlatform());
2837
2838 if (platform_sp) {
2839 ProcessInstanceInfoMatch match_info;
2840 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00002841 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002842 platform_sp->FindProcesses(match_info, process_infos);
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002843 const uint32_t num_matches = process_infos.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002844 if (num_matches == 1) {
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002845 attach_pid = process_infos[0].GetProcessID();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002846 // Fall through and attach using the above process ID
2847 } else {
2848 match_info.GetProcessInfo().GetExecutableFile().GetPath(
2849 process_name, sizeof(process_name));
2850 if (num_matches > 1) {
2851 StreamString s;
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002852 ProcessInstanceInfo::DumpTableHeader(s, true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002853 for (size_t i = 0; i < num_matches; i++) {
Jonas Devlieghere638b06c2020-03-12 14:10:25 -07002854 process_infos[i].DumpAsTableRow(
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002855 s, platform_sp->GetUserIDResolver(), true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002856 }
2857 error.SetErrorStringWithFormat(
2858 "more than one process named %s:\n%s", process_name,
2859 s.GetData());
2860 } else
2861 error.SetErrorStringWithFormat(
2862 "could not find a process named %s", process_name);
2863 }
2864 } else {
2865 error.SetErrorString(
2866 "invalid platform, can't find processes by name");
2867 return error;
2868 }
2869 }
2870 } else {
2871 error.SetErrorString("invalid process name");
2872 }
2873 }
2874
2875 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2876 error = WillAttachToProcessWithID(attach_pid);
2877 if (error.Success()) {
2878
2879 if (m_public_run_lock.TrySetRunning()) {
2880 // Now attach using these arguments.
2881 m_should_detach = true;
2882 const bool restarted = false;
2883 SetPublicState(eStateAttaching, restarted);
2884 error = DoAttachToProcessWithID(attach_pid, attach_info);
2885 } else {
2886 // This shouldn't happen
2887 error.SetErrorString("failed to acquire process run lock");
2888 }
2889
2890 if (error.Success()) {
2891 SetNextEventAction(new Process::AttachCompletionHandler(
2892 this, attach_info.GetResumeCount()));
2893 StartPrivateStateThread();
2894 } else {
Greg Clayton71337622011-02-24 22:24:29 +00002895 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002896 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002897
Kate Stoneb9c1b512016-09-06 20:57:50 +00002898 const char *error_string = error.AsCString();
2899 if (error_string == nullptr)
2900 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00002901
Kate Stoneb9c1b512016-09-06 20:57:50 +00002902 SetExitStatus(-1, error_string);
2903 }
Greg Claytonb766a732011-02-04 01:58:07 +00002904 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002905 }
2906 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00002907}
2908
Kate Stoneb9c1b512016-09-06 20:57:50 +00002909void Process::CompleteAttach() {
2910 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2911 LIBLLDB_LOG_TARGET));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002912 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913
2914 // Let the process subclass figure out at much as it can about the process
2915 // before we go looking for a dynamic loader plug-in.
2916 ArchSpec process_arch;
2917 DidAttach(process_arch);
2918
2919 if (process_arch.IsValid()) {
2920 GetTarget().SetArchitecture(process_arch);
2921 if (log) {
2922 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002923 LLDB_LOGF(log,
2924 "Process::%s replacing process architecture with DidAttach() "
2925 "architecture: %s",
2926 __FUNCTION__, triple_str ? triple_str : "<null>");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002927 }
2928 }
2929
2930 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00002931 // architecture, and if it isn't the same as the one we've already set,
2932 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002933 PlatformSP platform_sp(GetTarget().GetPlatform());
2934 assert(platform_sp);
2935 if (platform_sp) {
2936 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2937 if (target_arch.IsValid() &&
2938 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2939 ArchSpec platform_arch;
2940 platform_sp =
2941 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2942 if (platform_sp) {
2943 GetTarget().SetPlatform(platform_sp);
2944 GetTarget().SetArchitecture(platform_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002945 LLDB_LOGF(log,
2946 "Process::%s switching platform to %s and architecture "
2947 "to %s based on info from attach",
2948 __FUNCTION__, platform_sp->GetName().AsCString(""),
2949 platform_arch.GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002950 }
2951 } else if (!process_arch.IsValid()) {
2952 ProcessInstanceInfo process_info;
2953 GetProcessInfo(process_info);
2954 const ArchSpec &process_arch = process_info.GetArchitecture();
2955 if (process_arch.IsValid() &&
2956 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
2957 GetTarget().SetArchitecture(process_arch);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002958 LLDB_LOGF(log,
2959 "Process::%s switching architecture to %s based on info "
2960 "the platform retrieved for pid %" PRIu64,
2961 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
2962 GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002963 }
2964 }
2965 }
2966
2967 // We have completed the attach, now it is time to find the dynamic loader
2968 // plug-in
2969 DynamicLoader *dyld = GetDynamicLoader();
2970 if (dyld) {
2971 dyld->DidAttach();
2972 if (log) {
2973 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002974 LLDB_LOGF(log,
2975 "Process::%s after DynamicLoader::DidAttach(), target "
2976 "executable is %s (using %s plugin)",
2977 __FUNCTION__,
2978 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2979 : "<none>",
2980 dyld->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002981 }
2982 }
2983
2984 GetJITLoaders().DidAttach();
2985
2986 SystemRuntime *system_runtime = GetSystemRuntime();
2987 if (system_runtime) {
2988 system_runtime->DidAttach();
2989 if (log) {
2990 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00002991 LLDB_LOGF(log,
2992 "Process::%s after SystemRuntime::DidAttach(), target "
2993 "executable is %s (using %s plugin)",
2994 __FUNCTION__,
2995 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2996 : "<none>",
2997 system_runtime->GetPluginName().AsCString("<unnamed>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002998 }
2999 }
3000
Jim Ingham8864b432019-06-28 17:57:19 +00003001 if (!m_os_up) {
Greg Clayton29eeea02017-02-09 18:55:41 +00003002 LoadOperatingSystemPlugin(false);
Jim Ingham8864b432019-06-28 17:57:19 +00003003 if (m_os_up) {
3004 // Somebody might have gotten threads before now, but we need to force the
3005 // update after we've loaded the OperatingSystem plugin or it won't get a
3006 // chance to process the threads.
3007 m_thread_list.Clear();
3008 UpdateThreadListIfNeeded();
3009 }
3010 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003011 // Figure out which one is the executable, and set that in our target:
3012 const ModuleList &target_modules = GetTarget().GetImages();
3013 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3014 size_t num_modules = target_modules.GetSize();
3015 ModuleSP new_executable_module_sp;
3016
3017 for (size_t i = 0; i < num_modules; i++) {
3018 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3019 if (module_sp && module_sp->IsExecutable()) {
3020 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3021 new_executable_module_sp = module_sp;
3022 break;
3023 }
3024 }
3025 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00003026 GetTarget().SetExecutableModule(new_executable_module_sp,
3027 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003028 if (log) {
3029 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003030 LLDB_LOGF(
3031 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003032 "Process::%s after looping through modules, target executable is %s",
3033 __FUNCTION__,
3034 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3035 : "<none>");
3036 }
3037 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003038}
3039
Zachary Turner97206d52017-05-12 04:51:55 +00003040Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003041 m_abi_sp.reset();
3042 m_process_input_reader.reset();
3043
3044 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003045 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046
Zachary Turner97206d52017-05-12 04:51:55 +00003047 Status error(DoConnectRemote(strm, remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003048 if (error.Success()) {
3049 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3050 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003051 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003052
3053 if (state == eStateStopped || state == eStateCrashed) {
3054 // If we attached and actually have a process on the other end, then
3055 // this ended up being the equivalent of an attach.
3056 CompleteAttach();
3057
3058 // This delays passing the stopped event to listeners till
3059 // CompleteAttach gets a chance to complete...
3060 HandlePrivateEvent(event_sp);
3061 }
3062 }
3063
3064 if (PrivateStateThreadIsValid())
3065 ResumePrivateStateThread();
3066 else
3067 StartPrivateStateThread();
3068 }
3069 return error;
3070}
3071
Zachary Turner97206d52017-05-12 04:51:55 +00003072Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003073 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3074 LIBLLDB_LOG_STEP));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003075 LLDB_LOGF(log,
3076 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3077 "private state: %s",
3078 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3079 StateAsCString(m_private_state.GetValue()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003080
Adrian Prantl05097242018-04-30 16:49:04 +00003081 // If signals handing status changed we might want to update our signal
3082 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003083 UpdateAutomaticSignalFiltering();
3084
Zachary Turner97206d52017-05-12 04:51:55 +00003085 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086 // Tell the process it is about to resume before the thread list
3087 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003088 // Now let the thread list know we are about to resume so it can let all of
3089 // our threads know that they are about to be resumed. Threads will each be
3090 // called with Thread::WillResume(StateType) where StateType contains the
3091 // state that they are supposed to have when the process is resumed
3092 // (suspended/running/stepping). Threads should also check their resume
3093 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3094 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003095 if (m_thread_list.WillResume()) {
3096 // Last thing, do the PreResumeActions.
3097 if (!RunPreResumeActions()) {
3098 error.SetErrorStringWithFormat(
3099 "Process::PrivateResume PreResumeActions failed, not resuming.");
3100 } else {
3101 m_mod_id.BumpResumeID();
3102 error = DoResume();
3103 if (error.Success()) {
3104 DidResume();
3105 m_thread_list.DidResume();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003106 LLDB_LOGF(log, "Process thinks the process has resumed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003107 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003108 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003109 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110 }
3111 }
3112 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003113 // Somebody wanted to run without running (e.g. we were faking a step
3114 // from one frame of a set of inlined frames that share the same PC to
3115 // another.) So generate a continue & a stopped event, and let the world
3116 // handle them.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003117 LLDB_LOGF(log,
3118 "Process::PrivateResume() asked to simulate a start & stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003119
3120 SetPrivateState(eStateRunning);
3121 SetPrivateState(eStateStopped);
3122 }
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003123 } else
3124 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3125 error.AsCString("<unknown error>"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003126 return error;
3127}
3128
Zachary Turner97206d52017-05-12 04:51:55 +00003129Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003130 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003131 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003132
Adrian Prantl05097242018-04-30 16:49:04 +00003133 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3134 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003135 m_clear_thread_plans_on_stop |= clear_thread_plans;
3136
3137 ListenerSP halt_listener_sp(
3138 Listener::MakeListener("lldb.process.halt_listener"));
3139 HijackProcessEvents(halt_listener_sp);
3140
3141 EventSP event_sp;
3142
3143 SendAsyncInterrupt();
3144
3145 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003146 // Don't hijack and eat the eStateExited as the code that was doing the
3147 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003148 RestoreProcessEvents();
3149 SetExitStatus(SIGKILL, "Cancelled async attach.");
3150 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003151 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003152 }
3153
3154 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003155 StateType state = WaitForProcessToStop(
3156 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003157 RestoreProcessEvents();
3158
3159 if (state == eStateInvalid || !event_sp) {
3160 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003161 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003162 }
3163
3164 BroadcastEvent(event_sp);
3165
Zachary Turner97206d52017-05-12 04:51:55 +00003166 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003167}
3168
Zachary Turner97206d52017-05-12 04:51:55 +00003169Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3170 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003171
3172 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003173 // expression, for instance, then the public state will be stopped, but we
3174 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003175 if (m_public_state.GetValue() == eStateRunning ||
3176 m_private_state.GetValue() == eStateRunning) {
3177 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003178 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003179
Kate Stoneb9c1b512016-09-06 20:57:50 +00003180 ListenerSP listener_sp(
3181 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3182 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003183
Pavel Labath19da1f12015-12-07 12:36:52 +00003184 SendAsyncInterrupt();
3185
Kate Stoneb9c1b512016-09-06 20:57:50 +00003186 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003187 StateType state =
3188 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003189
Pavel Labath19da1f12015-12-07 12:36:52 +00003190 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003191
Kate Stoneb9c1b512016-09-06 20:57:50 +00003192 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003193 // exited event into the shared pointer passed in and return. Our caller
3194 // doesn't need to do anything else, since they don't have a process
3195 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003196
3197 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003198 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3199 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003200 return error;
3201 } else
3202 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3203
3204 if (state != eStateStopped) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003205 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3206 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003207 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003208 // here, but if the lower levels just bobbled sending the event and we
3209 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003210 StateType private_state = m_private_state.GetValue();
3211 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003212 return Status(
3213 "Attempt to stop the target in order to detach timed out. "
3214 "State = %s",
3215 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003216 }
3217 }
3218 }
3219 return error;
3220}
3221
Zachary Turner97206d52017-05-12 04:51:55 +00003222Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003223 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003224 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003225 m_destroy_in_process = true;
3226
3227 error = WillDetach();
3228
3229 if (error.Success()) {
3230 if (DetachRequiresHalt()) {
3231 error = StopForDestroyOrDetach(exit_event_sp);
3232 if (!error.Success()) {
3233 m_destroy_in_process = false;
3234 return error;
3235 } else if (exit_event_sp) {
3236 // We shouldn't need to do anything else here. There's no process left
3237 // to detach from...
3238 StopPrivateStateThread();
3239 m_destroy_in_process = false;
3240 return error;
3241 }
3242 }
3243
3244 m_thread_list.DiscardThreadPlans();
3245 DisableAllBreakpointSites();
3246
3247 error = DoDetach(keep_stopped);
3248 if (error.Success()) {
3249 DidDetach();
3250 StopPrivateStateThread();
3251 } else {
3252 return error;
3253 }
3254 }
3255 m_destroy_in_process = false;
3256
Adrian Prantl05097242018-04-30 16:49:04 +00003257 // If we exited when we were waiting for a process to stop, then forward the
3258 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003259 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003260 // Directly broadcast our exited event because we shut down our private
3261 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003262 BroadcastEvent(exit_event_sp);
3263 }
3264
3265 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003266 // not end up propagating the last events through the event system, in which
3267 // case we might strand the write lock. Unlock it here so when we do to tear
3268 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003269
3270 m_public_run_lock.SetStopped();
3271 return error;
3272}
3273
Zachary Turner97206d52017-05-12 04:51:55 +00003274Status Process::Destroy(bool force_kill) {
Jim Ingham61e8e682020-03-10 16:18:11 -07003275 // If we've already called Process::Finalize then there's nothing useful to
3276 // be done here. Finalize has actually called Destroy already.
3277 if (m_finalize_called)
3278 return {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003279
3280 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003281 // don't do any unnecessary work that might hinder the destruction. Remember
3282 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003283 // failed and the process stays around for some reason it won't be in a
3284 // confused state.
3285
3286 if (force_kill)
3287 m_should_detach = false;
3288
3289 if (GetShouldDetach()) {
3290 // FIXME: This will have to be a process setting:
3291 bool keep_stopped = false;
3292 Detach(keep_stopped);
3293 }
3294
3295 m_destroy_in_process = true;
3296
Zachary Turner97206d52017-05-12 04:51:55 +00003297 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003298 if (error.Success()) {
3299 EventSP exit_event_sp;
3300 if (DestroyRequiresHalt()) {
3301 error = StopForDestroyOrDetach(exit_event_sp);
3302 }
3303
3304 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003305 // Ditch all thread plans, and remove all our breakpoints: in case we
3306 // have to restart the target to kill it, we don't want it hitting a
3307 // breakpoint... Only do this if we've stopped, however, since if we
3308 // didn't manage to halt it above, then we're not going to have much luck
3309 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003310 m_thread_list.DiscardThreadPlans();
3311 DisableAllBreakpointSites();
3312 }
3313
3314 error = DoDestroy();
3315 if (error.Success()) {
3316 DidDestroy();
3317 StopPrivateStateThread();
3318 }
3319 m_stdio_communication.Disconnect();
3320 m_stdio_communication.StopReadThread();
3321 m_stdin_forward = false;
3322
3323 if (m_process_input_reader) {
3324 m_process_input_reader->SetIsDone(true);
3325 m_process_input_reader->Cancel();
3326 m_process_input_reader.reset();
3327 }
3328
Adrian Prantl05097242018-04-30 16:49:04 +00003329 // If we exited when we were waiting for a process to stop, then forward
3330 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003331 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003332 // Directly broadcast our exited event because we shut down our private
3333 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003334 BroadcastEvent(exit_event_sp);
3335 }
3336
Adrian Prantl05097242018-04-30 16:49:04 +00003337 // If we have been interrupted (to kill us) in the middle of running, we
3338 // may not end up propagating the last events through the event system, in
3339 // which case we might strand the write lock. Unlock it here so when we do
3340 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003341 m_public_run_lock.SetStopped();
3342 }
3343
3344 m_destroy_in_process = false;
3345
3346 return error;
3347}
3348
Zachary Turner97206d52017-05-12 04:51:55 +00003349Status Process::Signal(int signal) {
3350 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003351 if (error.Success()) {
3352 error = DoSignal(signal);
3353 if (error.Success())
3354 DidSignal();
3355 }
3356 return error;
3357}
3358
3359void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3360 assert(signals_sp && "null signals_sp");
3361 m_unix_signals_sp = signals_sp;
3362}
3363
3364const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3365 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3366 return m_unix_signals_sp;
3367}
3368
3369lldb::ByteOrder Process::GetByteOrder() const {
3370 return GetTarget().GetArchitecture().GetByteOrder();
3371}
3372
3373uint32_t Process::GetAddressByteSize() const {
3374 return GetTarget().GetArchitecture().GetAddressByteSize();
3375}
3376
3377bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3378 const StateType state =
3379 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3380 bool return_value = true;
3381 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3382 LIBLLDB_LOG_PROCESS));
3383
3384 switch (state) {
3385 case eStateDetached:
3386 case eStateExited:
3387 case eStateUnloaded:
3388 m_stdio_communication.SynchronizeWithReadThread();
3389 m_stdio_communication.Disconnect();
3390 m_stdio_communication.StopReadThread();
3391 m_stdin_forward = false;
3392
3393 LLVM_FALLTHROUGH;
3394 case eStateConnected:
3395 case eStateAttaching:
3396 case eStateLaunching:
3397 // These events indicate changes in the state of the debugging session,
3398 // always report them.
3399 return_value = true;
3400 break;
3401 case eStateInvalid:
3402 // We stopped for no apparent reason, don't report it.
3403 return_value = false;
3404 break;
3405 case eStateRunning:
3406 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003407 // If we've started the target running, we handle the cases where we are
3408 // already running and where there is a transition from stopped to running
3409 // differently. running -> running: Automatically suppress extra running
3410 // events stopped -> running: Report except when there is one or more no
3411 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003412 // and no yes votes.
3413 SynchronouslyNotifyStateChanged(state);
3414 if (m_force_next_event_delivery)
3415 return_value = true;
3416 else {
3417 switch (m_last_broadcast_state) {
3418 case eStateRunning:
3419 case eStateStepping:
3420 // We always suppress multiple runnings with no PUBLIC stop in between.
3421 return_value = false;
3422 break;
3423 default:
3424 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003425 // run if we aren't running so we don't miss any running events. If I
3426 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3427 // and hit the breakpoints on multiple threads, then somehow during the
3428 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003429
3430 // This is a transition from stop to run.
3431 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3432 case eVoteYes:
3433 case eVoteNoOpinion:
3434 return_value = true;
3435 break;
3436 case eVoteNo:
3437 return_value = false;
3438 break;
3439 }
3440 break;
3441 }
3442 }
3443 break;
3444 case eStateStopped:
3445 case eStateCrashed:
3446 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003447 // We've stopped. First see if we're going to restart the target. If we
3448 // are going to stop, then we always broadcast the event. If we aren't
3449 // going to stop, let the thread plans decide if we're going to report this
3450 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003451
3452 m_stdio_communication.SynchronizeWithReadThread();
3453 RefreshStateAfterStop();
3454 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003455 LLDB_LOGF(log,
3456 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3457 "interrupt, state: %s",
3458 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003459 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003460 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003461 m_thread_list.ShouldStop(event_ptr);
3462 return_value = true;
3463 } else {
3464 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3465 bool should_resume = false;
3466
3467 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003468 // restarted... Asking the thread list is also not likely to go well,
3469 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003470
3471 if (!was_restarted)
3472 should_resume = !m_thread_list.ShouldStop(event_ptr);
3473
3474 if (was_restarted || should_resume || m_resume_requested) {
3475 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003476 LLDB_LOGF(log,
3477 "Process::ShouldBroadcastEvent: should_resume: %i state: "
3478 "%s was_restarted: %i stop_vote: %d.",
3479 should_resume, StateAsCString(state), was_restarted,
3480 stop_vote);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003481
3482 switch (stop_vote) {
3483 case eVoteYes:
3484 return_value = true;
3485 break;
3486 case eVoteNoOpinion:
3487 case eVoteNo:
3488 return_value = false;
3489 break;
3490 }
3491
3492 if (!was_restarted) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003493 LLDB_LOGF(log,
3494 "Process::ShouldBroadcastEvent (%p) Restarting process "
3495 "from state: %s",
3496 static_cast<void *>(event_ptr), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003497 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3498 PrivateResume();
3499 }
3500 } else {
3501 return_value = true;
3502 SynchronouslyNotifyStateChanged(state);
3503 }
3504 }
3505 break;
3506 }
3507
3508 // Forcing the next event delivery is a one shot deal. So reset it here.
3509 m_force_next_event_delivery = false;
3510
3511 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003512 // events get coalesced.) But we only coalesce against events we actually
3513 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3514 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3515 // done, because the PublicState reflects the last event pulled off the
3516 // queue, and there may be several events stacked up on the queue unserviced.
3517 // So the PublicState may not reflect the last broadcasted event yet.
3518 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003519
3520 if (return_value)
3521 m_last_broadcast_state = state;
3522
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003523 LLDB_LOGF(log,
3524 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3525 "broadcast state: %s - %s",
3526 static_cast<void *>(event_ptr), StateAsCString(state),
3527 StateAsCString(m_last_broadcast_state),
3528 return_value ? "YES" : "NO");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003529 return return_value;
3530}
3531
3532bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3533 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3534
3535 bool already_running = PrivateStateThreadIsValid();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003536 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
3537 already_running ? " already running"
3538 : " starting private state thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003539
3540 if (!is_secondary_thread && already_running)
3541 return true;
3542
Adrian Prantl05097242018-04-30 16:49:04 +00003543 // Create a thread that watches our internal state and controls which events
3544 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003545 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003546 uint32_t max_len = llvm::get_max_thread_name_length();
3547 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003548 // On platforms with abbreviated thread name lengths, choose thread names
3549 // that fit within the limit.
3550 if (already_running)
3551 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3552 else
3553 snprintf(thread_name, sizeof(thread_name), "intern-state");
3554 } else {
3555 if (already_running)
3556 snprintf(thread_name, sizeof(thread_name),
3557 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3558 GetID());
3559 else
3560 snprintf(thread_name, sizeof(thread_name),
3561 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3562 }
3563
3564 // Create the private state thread, and start it running.
3565 PrivateStateThreadArgs *args_ptr =
3566 new PrivateStateThreadArgs(this, is_secondary_thread);
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003567 llvm::Expected<HostThread> private_state_thread =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003568 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003569 (void *)args_ptr, 8 * 1024 * 1024);
3570 if (!private_state_thread) {
3571 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3572 "failed to launch host thread: {}",
3573 llvm::toString(private_state_thread.takeError()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003574 return false;
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003575 }
3576
3577 assert(private_state_thread->IsJoinable());
3578 m_private_state_thread = *private_state_thread;
3579 ResumePrivateStateThread();
3580 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003581}
3582
3583void Process::PausePrivateStateThread() {
3584 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3585}
3586
3587void Process::ResumePrivateStateThread() {
3588 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3589}
3590
3591void Process::StopPrivateStateThread() {
3592 if (m_private_state_thread.IsJoinable())
3593 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3594 else {
3595 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003596 LLDB_LOGF(
3597 log,
3598 "Went to stop the private state thread, but it was already invalid.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003599 }
3600}
3601
3602void Process::ControlPrivateStateThread(uint32_t signal) {
3603 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3604
3605 assert(signal == eBroadcastInternalStateControlStop ||
3606 signal == eBroadcastInternalStateControlPause ||
3607 signal == eBroadcastInternalStateControlResume);
3608
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003609 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003610
3611 // Signal the private state thread
3612 if (m_private_state_thread.IsJoinable()) {
3613 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003614 // It is important to do this outside of the if below, because it's
3615 // possible that the thread state is invalid but that the thread is waiting
3616 // on a control event instead of simply being on its way out (this should
3617 // not happen, but it apparently can).
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003618 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003619 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3620 m_private_state_control_broadcaster.BroadcastEvent(signal,
3621 event_receipt_sp);
3622
3623 // Wait for the event receipt or for the private state thread to exit
3624 bool receipt_received = false;
3625 if (PrivateStateThreadIsValid()) {
3626 while (!receipt_received) {
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003627 // Check for a receipt for n seconds and then check if the private
Adrian Prantl05097242018-04-30 16:49:04 +00003628 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003629 receipt_received =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003630 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003631 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003632 // Check if the private state thread is still around. If it isn't
3633 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003634 if (!PrivateStateThreadIsValid())
3635 break; // Private state thread exited or is exiting, we are done
3636 }
3637 }
3638 }
3639
3640 if (signal == eBroadcastInternalStateControlStop) {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003641 thread_result_t result = {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003642 m_private_state_thread.Join(&result);
3643 m_private_state_thread.Reset();
3644 }
3645 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003646 LLDB_LOGF(
3647 log,
3648 "Private state thread already dead, no need to signal it to stop.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003649 }
3650}
3651
3652void Process::SendAsyncInterrupt() {
3653 if (PrivateStateThreadIsValid())
3654 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3655 nullptr);
3656 else
3657 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3658}
3659
3660void Process::HandlePrivateEvent(EventSP &event_sp) {
3661 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3662 m_resume_requested = false;
3663
3664 const StateType new_state =
3665 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3666
3667 // First check to see if anybody wants a shot at this event:
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003668 if (m_next_event_action_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003669 NextEventAction::EventActionResult action_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003670 m_next_event_action_up->PerformAction(event_sp);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003671 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003672
3673 switch (action_result) {
3674 case NextEventAction::eEventActionSuccess:
3675 SetNextEventAction(nullptr);
3676 break;
3677
3678 case NextEventAction::eEventActionRetry:
3679 break;
3680
3681 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003682 // Handle Exiting Here. If we already got an exited event, we should
3683 // just propagate it. Otherwise, swallow this event, and set our state
3684 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003685 if (new_state != eStateExited) {
3686 // FIXME: should cons up an exited event, and discard this one.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003687 SetExitStatus(0, m_next_event_action_up->GetExitString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003688 SetNextEventAction(nullptr);
3689 return;
3690 }
3691 SetNextEventAction(nullptr);
3692 break;
3693 }
3694 }
3695
3696 // See if we should broadcast this state to external clients?
3697 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3698
3699 if (should_broadcast) {
3700 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3701 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003702 LLDB_LOGF(log,
3703 "Process::%s (pid = %" PRIu64
3704 ") broadcasting new state %s (old state %s) to %s",
3705 __FUNCTION__, GetID(), StateAsCString(new_state),
3706 StateAsCString(GetState()),
3707 is_hijacked ? "hijacked" : "public");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003708 }
3709 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3710 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003711 // Only push the input handler if we aren't fowarding events, as this
3712 // means the curses GUI is in use... Or don't push it if we are launching
3713 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003714 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3715 new_state != eStateLaunching && new_state != eStateAttaching) {
3716 PushProcessIOHandler();
3717 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3718 eBroadcastAlways);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003719 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
3720 __FUNCTION__, m_iohandler_sync.GetValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003721 }
3722 } else if (StateIsStoppedState(new_state, false)) {
3723 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003724 // If the lldb_private::Debugger is handling the events, we don't want
3725 // to pop the process IOHandler here, we want to do it when we receive
3726 // the stopped event so we can carefully control when the process
3727 // IOHandler is popped because when we stop we want to display some
3728 // text stating how and why we stopped, then maybe some
3729 // process/thread/frame info, and then we want the "(lldb) " prompt to
3730 // show up. If we pop the process IOHandler here, then we will cause
3731 // the command interpreter to become the top IOHandler after the
3732 // process pops off and it will update its prompt right away... See the
3733 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003734 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3735 // Otherwise we end up getting overlapping "(lldb) " prompts and
3736 // garbled output.
3737 //
3738 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003739 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3740 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003741 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003742 // thread plans, or when commands want to run in synchronous mode and
3743 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003744 // that will hijack the events is a simple expression:
3745 //
3746 // (lldb) expr (int)puts("hello")
3747 //
3748 // This will cause the internal process state thread to resume and halt
3749 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3750 // events) and we do need the IO handler to be pushed and popped
3751 // correctly.
3752
3753 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3754 PopProcessIOHandler();
3755 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003756 }
3757
3758 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003759 } else {
3760 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003761 LLDB_LOGF(
3762 log,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003763 "Process::%s (pid = %" PRIu64
3764 ") suppressing state %s (old state %s): should_broadcast == false",
3765 __FUNCTION__, GetID(), StateAsCString(new_state),
3766 StateAsCString(GetState()));
3767 }
3768 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003769}
3770
Zachary Turner97206d52017-05-12 04:51:55 +00003771Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003772 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003773 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003774 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003775 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003776
3777 // Ask the process subclass to actually halt our process
3778 bool caused_stop;
3779 error = DoHalt(caused_stop);
3780
3781 DidHalt();
3782 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003783}
3784
Kate Stoneb9c1b512016-09-06 20:57:50 +00003785thread_result_t Process::PrivateStateThread(void *arg) {
3786 std::unique_ptr<PrivateStateThreadArgs> args_up(
3787 static_cast<PrivateStateThreadArgs *>(arg));
3788 thread_result_t result =
3789 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3790 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003791}
3792
Kate Stoneb9c1b512016-09-06 20:57:50 +00003793thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3794 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003795
Kate Stoneb9c1b512016-09-06 20:57:50 +00003796 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003797 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3798 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003799
Kate Stoneb9c1b512016-09-06 20:57:50 +00003800 bool exit_now = false;
3801 bool interrupt_requested = false;
3802 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003803 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003804 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003805 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003806 LLDB_LOGF(log,
3807 "Process::%s (arg = %p, pid = %" PRIu64
3808 ") got a control event: %d",
3809 __FUNCTION__, static_cast<void *>(this), GetID(),
3810 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003811
Kate Stoneb9c1b512016-09-06 20:57:50 +00003812 switch (event_sp->GetType()) {
3813 case eBroadcastInternalStateControlStop:
3814 exit_now = true;
3815 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003816
Kate Stoneb9c1b512016-09-06 20:57:50 +00003817 case eBroadcastInternalStateControlPause:
3818 control_only = true;
3819 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003820
Kate Stoneb9c1b512016-09-06 20:57:50 +00003821 case eBroadcastInternalStateControlResume:
3822 control_only = false;
3823 break;
3824 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003825
Kate Stoneb9c1b512016-09-06 20:57:50 +00003826 continue;
3827 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3828 if (m_public_state.GetValue() == eStateAttaching) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003829 LLDB_LOGF(log,
3830 "Process::%s (arg = %p, pid = %" PRIu64
3831 ") woke up with an interrupt while attaching - "
3832 "forwarding interrupt.",
3833 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003834 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3835 } else if (StateIsRunningState(m_last_broadcast_state)) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003836 LLDB_LOGF(log,
3837 "Process::%s (arg = %p, pid = %" PRIu64
3838 ") woke up with an interrupt - Halting.",
3839 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00003840 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003841 if (error.Fail() && log)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003842 LLDB_LOGF(log,
3843 "Process::%s (arg = %p, pid = %" PRIu64
3844 ") failed to halt the process: %s",
3845 __FUNCTION__, static_cast<void *>(this), GetID(),
3846 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00003847 // Halt should generate a stopped event. Make a note of the fact that
3848 // we were doing the interrupt, so we can set the interrupted flag
3849 // after we receive the event. We deliberately set this to true even if
3850 // HaltPrivate failed, so that we can interrupt on the next natural
3851 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003852 interrupt_requested = true;
3853 } else {
3854 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00003855 // running and sends an interrupt request, but the process actually
3856 // stops before we receive it. In that case, we can just ignore the
3857 // request. We use m_last_broadcast_state, because the Stopped event
3858 // may not have been popped of the event queue yet, which is when the
3859 // public state gets updated.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003860 LLDB_LOGF(log,
3861 "Process::%s ignoring interrupt as we have already stopped.",
3862 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003863 }
3864 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003865 }
3866
Kate Stoneb9c1b512016-09-06 20:57:50 +00003867 const StateType internal_state =
3868 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003869
Kate Stoneb9c1b512016-09-06 20:57:50 +00003870 if (internal_state != eStateInvalid) {
3871 if (m_clear_thread_plans_on_stop &&
3872 StateIsStoppedState(internal_state, true)) {
3873 m_clear_thread_plans_on_stop = false;
3874 m_thread_list.DiscardThreadPlans();
3875 }
3876
3877 if (interrupt_requested) {
3878 if (StateIsStoppedState(internal_state, true)) {
3879 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00003880 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00003881 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3882 interrupt_requested = false;
3883 } else if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003884 LLDB_LOGF(log,
3885 "Process::%s interrupt_requested, but a non-stopped "
3886 "state '%s' received.",
3887 __FUNCTION__, StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003888 }
3889 }
3890
3891 HandlePrivateEvent(event_sp);
3892 }
3893
3894 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3895 internal_state == eStateDetached) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003896 LLDB_LOGF(log,
3897 "Process::%s (arg = %p, pid = %" PRIu64
3898 ") about to exit with internal state %s...",
3899 __FUNCTION__, static_cast<void *>(this), GetID(),
3900 StateAsCString(internal_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003901
3902 break;
3903 }
3904 }
3905
3906 // Verify log is still enabled before attempting to write to it...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00003907 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3908 __FUNCTION__, static_cast<void *>(this), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003909
3910 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00003911 // will have already acquired the public_run_lock, and isn't done with what
3912 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003913 if (!is_secondary_thread)
3914 m_public_run_lock.SetStopped();
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003915 return {};
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003916}
3917
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003918// Process Event Data
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003919
Kate Stoneb9c1b512016-09-06 20:57:50 +00003920Process::ProcessEventData::ProcessEventData()
3921 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3922 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003923
Kate Stoneb9c1b512016-09-06 20:57:50 +00003924Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3925 StateType state)
3926 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3927 m_update_state(0), m_interrupted(false) {
3928 if (process_sp)
3929 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003930}
3931
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003932Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003933
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003934ConstString Process::ProcessEventData::GetFlavorString() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003935 static ConstString g_flavor("Process::ProcessEventData");
3936 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003937}
3938
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003939ConstString Process::ProcessEventData::GetFlavor() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003940 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003941}
3942
Kate Stoneb9c1b512016-09-06 20:57:50 +00003943void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
3944 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00003945
Kate Stoneb9c1b512016-09-06 20:57:50 +00003946 if (!process_sp)
3947 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003948
Kate Stoneb9c1b512016-09-06 20:57:50 +00003949 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00003950 // pulled off of the private process event queue, and then any number of
3951 // times, first when it gets pulled off of the public event queue, then other
3952 // times when we're pretending that this is where we stopped at the end of
3953 // expression evaluation. m_update_state is used to distinguish these three
3954 // cases; it is 0 when we're just pulling it off for private handling, and >
3955 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00003956 // command handling then.
3957 if (m_update_state != 1)
3958 return;
3959
3960 process_sp->SetPublicState(
3961 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
3962
Jason Molendab3a3cd12016-12-08 06:27:29 +00003963 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00003964 // Let process subclasses know we are about to do a public stop and do
3965 // anything they might need to in order to speed up register and memory
3966 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00003967 process_sp->WillPublicStop();
3968 }
3969
Kate Stoneb9c1b512016-09-06 20:57:50 +00003970 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00003971 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
3972 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00003973 // end up restarting the process.
3974 if (m_interrupted)
3975 return;
3976
3977 // If we're stopped and haven't restarted, then do the StopInfo actions here:
3978 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003979 ThreadList &curr_thread_list = process_sp->GetThreadList();
3980 uint32_t num_threads = curr_thread_list.GetSize();
3981 uint32_t idx;
3982
3983 // The actions might change one of the thread's stop_info's opinions about
Adrian Prantl05097242018-04-30 16:49:04 +00003984 // whether we should stop the process, so we need to query that as we go.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003985
3986 // One other complication here, is that we try to catch any case where the
Adrian Prantl05097242018-04-30 16:49:04 +00003987 // target has run (except for expressions) and immediately exit, but if we
3988 // get that wrong (which is possible) then the thread list might have
3989 // changed, and that would cause our iteration here to crash. We could
3990 // make a copy of the thread list, but we'd really like to also know if it
3991 // has changed at all, so we make up a vector of the thread ID's and check
3992 // what we get back against this list & bag out if anything differs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003993 std::vector<uint32_t> thread_index_array(num_threads);
3994 for (idx = 0; idx < num_threads; ++idx)
3995 thread_index_array[idx] =
3996 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3997
3998 // Use this to track whether we should continue from here. We will only
Adrian Prantl05097242018-04-30 16:49:04 +00003999 // continue the target running if no thread says we should stop. Of course
4000 // if some thread's PerformAction actually sets the target running, then it
4001 // doesn't matter what the other threads say...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004002
4003 bool still_should_stop = false;
4004
4005 // Sometimes - for instance if we have a bug in the stub we are talking to,
Adrian Prantl05097242018-04-30 16:49:04 +00004006 // we stop but no thread has a valid stop reason. In that case we should
4007 // just stop, because we have no way of telling what the right thing to do
4008 // is, and it's better to let the user decide than continue behind their
4009 // backs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004010
4011 bool does_anybody_have_an_opinion = false;
4012
4013 for (idx = 0; idx < num_threads; ++idx) {
4014 curr_thread_list = process_sp->GetThreadList();
4015 if (curr_thread_list.GetSize() != num_threads) {
4016 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4017 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004018 LLDB_LOGF(
4019 log,
4020 "Number of threads changed from %u to %u while processing event.",
4021 num_threads, curr_thread_list.GetSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004022 break;
4023 }
4024
4025 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4026
4027 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4028 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4029 LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004030 LLDB_LOGF(log,
4031 "The thread at position %u changed from %u to %u while "
4032 "processing event.",
4033 idx, thread_index_array[idx], thread_sp->GetIndexID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004034 break;
4035 }
4036
4037 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4038 if (stop_info_sp && stop_info_sp->IsValid()) {
4039 does_anybody_have_an_opinion = true;
4040 bool this_thread_wants_to_stop;
4041 if (stop_info_sp->GetOverrideShouldStop()) {
4042 this_thread_wants_to_stop =
4043 stop_info_sp->GetOverriddenShouldStopValue();
4044 } else {
4045 stop_info_sp->PerformAction(event_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +00004046 // The stop action might restart the target. If it does, then we
4047 // want to mark that in the event so that whoever is receiving it
4048 // will know to wait for the running event and reflect that state
4049 // appropriately. We also need to stop processing actions, since they
4050 // aren't expecting the target to be running.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004051
4052 // FIXME: we might have run.
4053 if (stop_info_sp->HasTargetRunSinceMe()) {
4054 SetRestarted(true);
4055 break;
4056 }
4057
4058 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004059 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004060
4061 if (!still_should_stop)
4062 still_should_stop = this_thread_wants_to_stop;
4063 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004064 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004065
4066 if (!GetRestarted()) {
4067 if (!still_should_stop && does_anybody_have_an_opinion) {
4068 // We've been asked to continue, so do that here.
4069 SetRestarted(true);
Adrian Prantl05097242018-04-30 16:49:04 +00004070 // Use the public resume method here, since this is just extending a
4071 // public resume.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004072 process_sp->PrivateResume();
4073 } else {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004074 bool hijacked =
4075 process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4076 !process_sp->StateChangedIsHijackedForSynchronousResume();
Jim Ingham3139fc92019-03-01 18:13:38 +00004077
4078 if (!hijacked) {
4079 // If we didn't restart, run the Stop Hooks here.
4080 // Don't do that if state changed events aren't hooked up to the
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004081 // public (or SyncResume) broadcasters. StopHooks are just for
4082 // real public stops. They might also restart the target,
Jim Ingham3139fc92019-03-01 18:13:38 +00004083 // so watch for that.
4084 process_sp->GetTarget().RunStopHooks();
4085 if (process_sp->GetPrivateState() == eStateRunning)
4086 SetRestarted(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004087 }
4088 }
4089 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004090}
Zachary Turner805e7102019-03-04 21:51:03 +00004091}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004092
Kate Stoneb9c1b512016-09-06 20:57:50 +00004093void Process::ProcessEventData::Dump(Stream *s) const {
4094 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004095
Kate Stoneb9c1b512016-09-06 20:57:50 +00004096 if (process_sp)
4097 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4098 static_cast<void *>(process_sp.get()), process_sp->GetID());
4099 else
4100 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004101
Kate Stoneb9c1b512016-09-06 20:57:50 +00004102 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004103}
4104
4105const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004106Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4107 if (event_ptr) {
4108 const EventData *event_data = event_ptr->GetData();
4109 if (event_data &&
4110 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4111 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4112 }
4113 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004114}
4115
4116ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004117Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4118 ProcessSP process_sp;
4119 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4120 if (data)
4121 process_sp = data->GetProcessSP();
4122 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004123}
4124
Kate Stoneb9c1b512016-09-06 20:57:50 +00004125StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4126 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4127 if (data == nullptr)
4128 return eStateInvalid;
4129 else
4130 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004131}
4132
Kate Stoneb9c1b512016-09-06 20:57:50 +00004133bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4134 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4135 if (data == nullptr)
4136 return false;
4137 else
4138 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004139}
4140
Kate Stoneb9c1b512016-09-06 20:57:50 +00004141void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4142 bool new_value) {
4143 ProcessEventData *data =
4144 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4145 if (data != nullptr)
4146 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004147}
4148
Jim Ingham0161b492013-02-09 01:29:05 +00004149size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004150Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4151 ProcessEventData *data =
4152 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4153 if (data != nullptr)
4154 return data->GetNumRestartedReasons();
4155 else
4156 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004157}
4158
4159const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004160Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4161 size_t idx) {
4162 ProcessEventData *data =
4163 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4164 if (data != nullptr)
4165 return data->GetRestartedReasonAtIndex(idx);
4166 else
4167 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004168}
4169
Kate Stoneb9c1b512016-09-06 20:57:50 +00004170void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4171 const char *reason) {
4172 ProcessEventData *data =
4173 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4174 if (data != nullptr)
4175 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004176}
4177
Kate Stoneb9c1b512016-09-06 20:57:50 +00004178bool Process::ProcessEventData::GetInterruptedFromEvent(
4179 const Event *event_ptr) {
4180 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4181 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004182 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004183 else
4184 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004185}
4186
Kate Stoneb9c1b512016-09-06 20:57:50 +00004187void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4188 bool new_value) {
4189 ProcessEventData *data =
4190 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4191 if (data != nullptr)
4192 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004193}
4194
Kate Stoneb9c1b512016-09-06 20:57:50 +00004195bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4196 ProcessEventData *data =
4197 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4198 if (data) {
4199 data->SetUpdateStateOnRemoval();
4200 return true;
4201 }
4202 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004203}
4204
Jim Inghamb87b9e62018-06-26 23:38:58 +00004205lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004206
4207void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4208 exe_ctx.SetTargetPtr(&GetTarget());
4209 exe_ctx.SetProcessPtr(this);
4210 exe_ctx.SetThreadPtr(nullptr);
4211 exe_ctx.SetFramePtr(nullptr);
4212}
4213
4214// uint32_t
4215// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4216// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004217//{
4218// return 0;
4219//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004220//
4221// ArchSpec
4222// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004223//{
4224// return Host::GetArchSpecForExistingProcess (pid);
4225//}
4226//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004227// ArchSpec
4228// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004229//{
4230// return Host::GetArchSpecForExistingProcess (process_name);
4231//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004232
Kate Stoneb9c1b512016-09-06 20:57:50 +00004233void Process::AppendSTDOUT(const char *s, size_t len) {
4234 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4235 m_stdout_data.append(s, len);
4236 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4237 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004238}
4239
Kate Stoneb9c1b512016-09-06 20:57:50 +00004240void Process::AppendSTDERR(const char *s, size_t len) {
4241 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4242 m_stderr_data.append(s, len);
4243 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4244 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004245}
4246
Kate Stoneb9c1b512016-09-06 20:57:50 +00004247void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4248 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4249 m_profile_data.push_back(one_profile_data);
4250 BroadcastEventIfUnique(eBroadcastBitProfileData,
4251 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004252}
4253
Kate Stoneb9c1b512016-09-06 20:57:50 +00004254void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4255 const StructuredDataPluginSP &plugin_sp) {
4256 BroadcastEvent(
4257 eBroadcastBitStructuredData,
4258 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004259}
4260
4261StructuredDataPluginSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004262Process::GetStructuredDataPlugin(ConstString type_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004263 auto find_it = m_structured_data_plugin_map.find(type_name);
4264 if (find_it != m_structured_data_plugin_map.end())
4265 return find_it->second;
4266 else
4267 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004268}
4269
Zachary Turner97206d52017-05-12 04:51:55 +00004270size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004271 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4272 if (m_profile_data.empty())
4273 return 0;
4274
4275 std::string &one_profile_data = m_profile_data.front();
4276 size_t bytes_available = one_profile_data.size();
4277 if (bytes_available > 0) {
4278 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004279 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4280 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004281 if (bytes_available > buf_size) {
4282 memcpy(buf, one_profile_data.c_str(), buf_size);
4283 one_profile_data.erase(0, buf_size);
4284 bytes_available = buf_size;
4285 } else {
4286 memcpy(buf, one_profile_data.c_str(), bytes_available);
4287 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004288 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004289 }
4290 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004291}
4292
Greg Clayton93e86192011-11-13 04:45:22 +00004293// Process STDIO
Greg Clayton93e86192011-11-13 04:45:22 +00004294
Zachary Turner97206d52017-05-12 04:51:55 +00004295size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004296 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4297 size_t bytes_available = m_stdout_data.size();
4298 if (bytes_available > 0) {
4299 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004300 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4301 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004302 if (bytes_available > buf_size) {
4303 memcpy(buf, m_stdout_data.c_str(), buf_size);
4304 m_stdout_data.erase(0, buf_size);
4305 bytes_available = buf_size;
4306 } else {
4307 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4308 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004309 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004310 }
4311 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004312}
4313
Zachary Turner97206d52017-05-12 04:51:55 +00004314size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004315 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4316 size_t bytes_available = m_stderr_data.size();
4317 if (bytes_available > 0) {
4318 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004319 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4320 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004321 if (bytes_available > buf_size) {
4322 memcpy(buf, m_stderr_data.c_str(), buf_size);
4323 m_stderr_data.erase(0, buf_size);
4324 bytes_available = buf_size;
4325 } else {
4326 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4327 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004328 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004329 }
4330 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004331}
4332
Kate Stoneb9c1b512016-09-06 20:57:50 +00004333void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4334 size_t src_len) {
4335 Process *process = (Process *)baton;
4336 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004337}
4338
Kate Stoneb9c1b512016-09-06 20:57:50 +00004339class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004340public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004341 IOHandlerProcessSTDIO(Process *process, int write_fd)
4342 : IOHandler(process->GetTarget().GetDebugger(),
4343 IOHandler::Type::ProcessIO),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004344 m_process(process),
Lawrence D'Anna7ca15ba2019-09-27 14:33:35 +00004345 m_read_file(GetInputFD(), File::eOpenOptionRead, false),
Jonas Devlieghere948786c2019-09-23 20:36:46 +00004346 m_write_file(write_fd, File::eOpenOptionWrite, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004347 m_pipe.CreateNew(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004348 }
4349
4350 ~IOHandlerProcessSTDIO() override = default;
4351
Adrian Prantl05097242018-04-30 16:49:04 +00004352 // Each IOHandler gets to run until it is done. It should read data from the
4353 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004354 void Run() override {
4355 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4356 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4357 SetIsDone(true);
4358 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004359 }
4360
Kate Stoneb9c1b512016-09-06 20:57:50 +00004361 SetIsDone(false);
4362 const int read_fd = m_read_file.GetDescriptor();
4363 TerminalState terminal_state;
4364 terminal_state.Save(read_fd, false);
4365 Terminal terminal(read_fd);
4366 terminal.SetCanonical(false);
4367 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004368// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004369#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004370 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4371 m_is_running = true;
4372 while (!GetIsDone()) {
4373 SelectHelper select_helper;
4374 select_helper.FDSetRead(read_fd);
4375 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004376 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004377
Kate Stoneb9c1b512016-09-06 20:57:50 +00004378 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004379 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004380 } else {
4381 char ch = 0;
4382 size_t n;
4383 if (select_helper.FDIsSetRead(read_fd)) {
4384 n = 1;
4385 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4386 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4387 SetIsDone(true);
4388 } else
4389 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004390 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004391 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4392 size_t bytes_read;
4393 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004394 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004395 if (error.Success()) {
4396 switch (ch) {
4397 case 'q':
4398 SetIsDone(true);
4399 break;
4400 case 'i':
4401 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004402 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004403 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004404 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004405 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004406 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004407 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004408 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004409 m_is_running = false;
4410#endif
4411 terminal_state.Restore();
4412 }
4413
4414 void Cancel() override {
4415 SetIsDone(true);
4416 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004417 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4418 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004419 //
4420 // (lldb) step_process_thousands_of_times
4421 //
4422 // In this case the command interpreter will be in the middle of handling
4423 // the command and if the process pushes and pops the IOHandler thousands
4424 // of times, we can end up writing to m_pipe without ever consuming the
4425 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4426 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4427 if (m_is_running) {
4428 char ch = 'q'; // Send 'q' for quit
4429 size_t bytes_written = 0;
4430 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004431 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004432 }
4433
4434 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004435 // Do only things that are safe to do in an interrupt context (like in a
4436 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004437 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4438 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004439 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004440 if (m_active) {
4441 char ch = 'i'; // Send 'i' for interrupt
4442 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004443 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004444 return result.Success();
4445 } else {
4446 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004447 // currently so do the right thing if we aren't actively watching for
4448 // STDIN by sending the interrupt to the process. Otherwise the write to
4449 // the pipe above would do nothing. This can happen when the command
4450 // interpreter is running and gets a "expression ...". It will be on the
4451 // IOHandler thread and sending the input is complete to the delegate
4452 // which will cause the expression to run, which will push the process IO
4453 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004454
4455 if (StateIsRunningState(m_process->GetState())) {
4456 m_process->SendAsyncInterrupt();
4457 return true;
4458 }
4459 }
4460 return false;
4461 }
4462
4463 void GotEOF() override {}
4464
Greg Clayton44d93782014-01-27 23:43:24 +00004465protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004466 Process *m_process;
Lawrence D'Annaf913fd62019-10-03 04:31:46 +00004467 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
4468 NativeFile m_write_file; // Write to this file (usually the master pty for
4469 // getting io to debuggee)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004470 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004471 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004472};
4473
Kate Stoneb9c1b512016-09-06 20:57:50 +00004474void Process::SetSTDIOFileDescriptor(int fd) {
4475 // First set up the Read Thread for reading/handling process I/O
Pavel Labath451741a2020-04-02 14:40:59 +02004476 m_stdio_communication.SetConnection(
4477 std::make_unique<ConnectionFileDescriptor>(fd, true));
4478 if (m_stdio_communication.IsConnected()) {
4479 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4480 STDIOReadThreadBytesReceived, this);
4481 m_stdio_communication.StartReadThread();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004482
Pavel Labath451741a2020-04-02 14:40:59 +02004483 // Now read thread is set up, set up input reader.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004484
Pavel Labath451741a2020-04-02 14:40:59 +02004485 if (!m_process_input_reader)
4486 m_process_input_reader =
4487 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004488 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004489}
4490
Kate Stoneb9c1b512016-09-06 20:57:50 +00004491bool Process::ProcessIOHandlerIsActive() {
4492 IOHandlerSP io_handler_sp(m_process_input_reader);
4493 if (io_handler_sp)
4494 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4495 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004496}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004497bool Process::PushProcessIOHandler() {
4498 IOHandlerSP io_handler_sp(m_process_input_reader);
4499 if (io_handler_sp) {
4500 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004501 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004502
Kate Stoneb9c1b512016-09-06 20:57:50 +00004503 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004504 // If we evaluate an utility function, then we don't cancel the current
4505 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4506 // existing IOHandler that potentially provides the user interface (e.g.
4507 // the IOHandler for Editline).
4508 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004509 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
4510 cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004511 return true;
4512 }
4513 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004514}
4515
Kate Stoneb9c1b512016-09-06 20:57:50 +00004516bool Process::PopProcessIOHandler() {
4517 IOHandlerSP io_handler_sp(m_process_input_reader);
4518 if (io_handler_sp)
Jonas Devlieghere7ce2de22020-01-15 14:56:28 -08004519 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004520 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004521}
4522
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004523// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004524void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004525
Kate Stoneb9c1b512016-09-06 20:57:50 +00004526void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004527
Kate Stoneb9c1b512016-09-06 20:57:50 +00004528namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004529// RestorePlanState is used to record the "is private", "is master" and "okay
4530// to discard" fields of the plan we are running, and reset it on Clean or on
4531// destruction. It will only reset the state once, so you can call Clean and
4532// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004533
Kate Stoneb9c1b512016-09-06 20:57:50 +00004534class RestorePlanState {
4535public:
4536 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4537 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4538 if (m_thread_plan_sp) {
4539 m_private = m_thread_plan_sp->GetPrivate();
4540 m_is_master = m_thread_plan_sp->IsMasterPlan();
4541 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4542 }
4543 }
4544
4545 ~RestorePlanState() { Clean(); }
4546
4547 void Clean() {
4548 if (!m_already_reset && m_thread_plan_sp) {
4549 m_already_reset = true;
4550 m_thread_plan_sp->SetPrivate(m_private);
4551 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4552 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4553 }
4554 }
4555
4556private:
4557 lldb::ThreadPlanSP m_thread_plan_sp;
4558 bool m_already_reset;
4559 bool m_private;
4560 bool m_is_master;
4561 bool m_okay_to_discard;
4562};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004563} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004564
Pavel Labath2ce22162016-12-01 10:57:30 +00004565static microseconds
4566GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4567 const milliseconds default_one_thread_timeout(250);
4568
4569 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004570 if (!options.GetTimeout()) {
4571 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4572 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004573 }
4574
4575 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004576 if (options.GetOneThreadTimeout())
4577 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004578
4579 // Otherwise use half the total timeout, bounded by the
4580 // default_one_thread_timeout.
4581 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004582 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004583}
4584
4585static Timeout<std::micro>
4586GetExpressionTimeout(const EvaluateExpressionOptions &options,
4587 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004588 // If we are going to run all threads the whole time, or if we are only going
4589 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004590 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004591 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004592
4593 if (before_first_timeout)
4594 return GetOneThreadExpressionTimeout(options);
4595
Pavel Labath43d35412016-12-06 11:24:51 +00004596 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004597 return llvm::None;
4598 else
Pavel Labath43d35412016-12-06 11:24:51 +00004599 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004600}
4601
Pavel Labath45dde232017-05-25 10:50:06 +00004602static llvm::Optional<ExpressionResults>
4603HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4604 RestorePlanState &restorer, const EventSP &event_sp,
4605 EventSP &event_to_broadcast_sp,
4606 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4607 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4608
4609 ThreadPlanSP plan = thread.GetCompletedPlan();
4610 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4611 LLDB_LOG(log, "execution completed successfully");
4612
4613 // Restore the plan state so it will get reported as intended when we are
4614 // done.
4615 restorer.Clean();
4616 return eExpressionCompleted;
4617 }
4618
4619 StopInfoSP stop_info_sp = thread.GetStopInfo();
4620 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4621 stop_info_sp->ShouldNotify(event_sp.get())) {
4622 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4623 if (!options.DoesIgnoreBreakpoints()) {
4624 // Restore the plan state and then force Private to false. We are going
4625 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004626 // it won't report correctly when we continue to its termination later
4627 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004628 restorer.Clean();
4629 thread_plan_sp->SetPrivate(false);
4630 event_to_broadcast_sp = event_sp;
4631 }
4632 return eExpressionHitBreakpoint;
4633 }
4634
4635 if (!handle_interrupts &&
4636 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4637 return llvm::None;
4638
4639 LLDB_LOG(log, "thread plan did not successfully complete");
4640 if (!options.DoesUnwindOnError())
4641 event_to_broadcast_sp = event_sp;
4642 return eExpressionInterrupted;
4643}
4644
Jim Ingham1624a2d2014-05-05 02:26:40 +00004645ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004646Process::RunThreadPlan(ExecutionContext &exe_ctx,
4647 lldb::ThreadPlanSP &thread_plan_sp,
4648 const EvaluateExpressionOptions &options,
4649 DiagnosticManager &diagnostic_manager) {
4650 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004651
Kate Stoneb9c1b512016-09-06 20:57:50 +00004652 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4653
4654 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004655 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004656 eDiagnosticSeverityError,
4657 "RunThreadPlan called with empty thread plan.");
4658 return eExpressionSetupError;
4659 }
4660
4661 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004662 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004663 eDiagnosticSeverityError,
4664 "RunThreadPlan called with an invalid thread plan.");
4665 return eExpressionSetupError;
4666 }
4667
4668 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004669 diagnostic_manager.PutString(eDiagnosticSeverityError,
4670 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004671 return eExpressionSetupError;
4672 }
4673
4674 Thread *thread = exe_ctx.GetThreadPtr();
4675 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004676 diagnostic_manager.PutString(eDiagnosticSeverityError,
4677 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004678 return eExpressionSetupError;
4679 }
4680
4681 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004682 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004683
4684 RestorePlanState thread_plan_restorer(thread_plan_sp);
4685
Adrian Prantl05097242018-04-30 16:49:04 +00004686 // We rely on the thread plan we are running returning "PlanCompleted" if
4687 // when it successfully completes. For that to be true the plan can't be
4688 // private - since private plans suppress themselves in the GetCompletedPlan
4689 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004690
4691 thread_plan_sp->SetPrivate(false);
4692
4693 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004694 // when they are done we will end up asking the plan above us whether we
4695 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004696
4697 thread_plan_sp->SetIsMasterPlan(true);
4698 thread_plan_sp->SetOkayToDiscard(false);
4699
Raphael Isemannc01783a2018-08-29 22:50:54 +00004700 // If we are running some utility expression for LLDB, we now have to mark
4701 // this in the ProcesModID of this process. This RAII takes care of marking
4702 // and reverting the mark it once we are done running the expression.
4703 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4704
Kate Stoneb9c1b512016-09-06 20:57:50 +00004705 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004706 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004707 eDiagnosticSeverityError,
4708 "RunThreadPlan called while the private state was not stopped.");
4709 return eExpressionSetupError;
4710 }
4711
4712 // Save the thread & frame from the exe_ctx for restoration after we run
4713 const uint32_t thread_idx_id = thread->GetIndexID();
4714 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4715 if (!selected_frame_sp) {
4716 thread->SetSelectedFrame(nullptr);
4717 selected_frame_sp = thread->GetSelectedFrame();
4718 if (!selected_frame_sp) {
4719 diagnostic_manager.Printf(
4720 eDiagnosticSeverityError,
4721 "RunThreadPlan called without a selected frame on thread %d",
4722 thread_idx_id);
4723 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004724 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004725 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004726
Adrian Prantl05097242018-04-30 16:49:04 +00004727 // Make sure the timeout values make sense. The one thread timeout needs to
4728 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004729 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4730 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004731 diagnostic_manager.PutString(eDiagnosticSeverityError,
4732 "RunThreadPlan called with one thread "
4733 "timeout greater than total timeout");
4734 return eExpressionSetupError;
4735 }
4736
Kate Stoneb9c1b512016-09-06 20:57:50 +00004737 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004738
Kate Stoneb9c1b512016-09-06 20:57:50 +00004739 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004740 // We don't want to do that either, so we should arrange to reset them as
4741 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004742
Kate Stoneb9c1b512016-09-06 20:57:50 +00004743 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004744
Kate Stoneb9c1b512016-09-06 20:57:50 +00004745 uint32_t selected_tid;
4746 StackID selected_stack_id;
4747 if (selected_thread_sp) {
4748 selected_tid = selected_thread_sp->GetIndexID();
4749 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4750 } else {
4751 selected_tid = LLDB_INVALID_THREAD_ID;
4752 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004753
Kate Stoneb9c1b512016-09-06 20:57:50 +00004754 HostThread backup_private_state_thread;
4755 lldb::StateType old_state = eStateInvalid;
4756 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004757
Kate Stoneb9c1b512016-09-06 20:57:50 +00004758 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4759 LIBLLDB_LOG_PROCESS));
4760 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4761 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004762 // public events on this thread, since we are the thread that is generating
4763 // public events. The simplest thing to do is to spin up a temporary thread
4764 // to handle private state thread events while we are fielding public
4765 // events here.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004766 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4767 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004768
Kate Stoneb9c1b512016-09-06 20:57:50 +00004769 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004770
Kate Stoneb9c1b512016-09-06 20:57:50 +00004771 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004772 // anything it pushes, and then stop, returning control here. But in the
4773 // normal course of things, the plan above us on the stack would be given a
4774 // shot at the stop event before deciding to stop, and we don't want that.
4775 // So we insert a "stopper" base plan on the stack before the plan we want
4776 // to run. Since base plans always stop and return control to the user,
4777 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004778 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4779 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4780 // Have to make sure our public state is stopped, since otherwise the
4781 // reporting logic below doesn't work correctly.
4782 old_state = m_public_state.GetValue();
4783 m_public_state.SetValueNoLock(eStateStopped);
4784
4785 // Now spin up the private state thread:
4786 StartPrivateStateThread(true);
4787 }
4788
4789 thread->QueueThreadPlan(
4790 thread_plan_sp, false); // This used to pass "true" does that make sense?
4791
4792 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004793 // In this case, we aren't actually going to run, we just want to stop
4794 // right away. Flush this thread so we will refetch the stacks and show the
4795 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004796 // FIXME: To make this prettier we should invent some stop reason for this,
4797 // but that
4798 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004799 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004800 thread->Flush();
4801 return eExpressionStoppedForDebug;
4802 }
4803
4804 ListenerSP listener_sp(
4805 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4806
4807 lldb::EventSP event_to_broadcast_sp;
4808
4809 {
4810 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004811 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004812 //
4813 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004814 // exits during execution), then the event is put into
4815 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004816
4817 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4818
4819 if (log) {
4820 StreamString s;
4821 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004822 LLDB_LOGF(log,
4823 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4824 " to run thread plan \"%s\".",
4825 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004826 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004827
4828 bool got_event;
4829 lldb::EventSP event_sp;
4830 lldb::StateType stop_state = lldb::eStateInvalid;
4831
4832 bool before_first_timeout = true; // This is set to false the first time
4833 // that we have to halt the target.
4834 bool do_resume = true;
4835 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004836
4837 // This is just for accounting:
4838 uint32_t num_resumes = 0;
4839
Kate Stoneb9c1b512016-09-06 20:57:50 +00004840 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00004841 // going to run one thread, then we don't need the first timeout. So we
4842 // pretend we are after the first timeout already.
4843 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004844 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00004845
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004846 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4847 options.GetStopOthers(), options.GetTryAllThreads(),
4848 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004849
Adrian Prantl05097242018-04-30 16:49:04 +00004850 // This isn't going to work if there are unfetched events on the queue. Are
4851 // there cases where we might want to run the remaining events here, and
4852 // then try to call the function? That's probably being too tricky for our
4853 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004854
4855 Event *other_events = listener_sp->PeekAtNextEvent();
4856 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004857 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004858 eDiagnosticSeverityError,
4859 "RunThreadPlan called with pending events on the queue.");
4860 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00004861 }
4862
Kate Stoneb9c1b512016-09-06 20:57:50 +00004863 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00004864 // calling a function as part of a thread plan, in which case the last
4865 // delivered event could be the running event, and we don't want event
4866 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004867 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00004868
Kate Stoneb9c1b512016-09-06 20:57:50 +00004869// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00004870// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00004871
Kate Stoneb9c1b512016-09-06 20:57:50 +00004872#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00004873 // It's pretty much impossible to write test cases for things like: One
4874 // thread timeout expires, I go to halt, but the process already stopped on
4875 // the function call stop breakpoint. Turning on this define will make us
4876 // not fetch the first event till after the halt. So if you run a quick
4877 // function, it will have completed, and the completion event will be
4878 // waiting, when you interrupt for halt. The expression evaluation should
4879 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004880 bool miss_first_event = true;
4881#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00004882 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00004883 // We usually want to resume the process if we get to the top of the
4884 // loop. The only exception is if we get two running events with no
4885 // intervening stop, which can happen, we will just wait for then next
4886 // stop event.
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004887 LLDB_LOGF(log,
4888 "Top of while loop: do_resume: %i handle_running_event: %i "
4889 "before_first_timeout: %i.",
4890 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00004891
Kate Stoneb9c1b512016-09-06 20:57:50 +00004892 if (do_resume || handle_running_event) {
4893 // Do the initial resume and wait for the running event before going
4894 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00004895
Kate Stoneb9c1b512016-09-06 20:57:50 +00004896 if (do_resume) {
4897 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00004898 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004899 if (!resume_error.Success()) {
4900 diagnostic_manager.Printf(
4901 eDiagnosticSeverityError,
4902 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4903 resume_error.AsCString());
4904 return_value = eExpressionSetupError;
4905 break;
4906 }
Jason Molendaef7d6412015-08-06 03:27:10 +00004907 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004908
Pavel Labathd35031e12016-11-30 10:41:42 +00004909 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00004910 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004911 if (!got_event) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004912 LLDB_LOGF(log,
4913 "Process::RunThreadPlan(): didn't get any event after "
4914 "resume %" PRIu32 ", exiting.",
4915 num_resumes);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004916
4917 diagnostic_manager.Printf(eDiagnosticSeverityError,
4918 "didn't get any event after resume %" PRIu32
4919 ", exiting.",
4920 num_resumes);
4921 return_value = eExpressionSetupError;
4922 break;
4923 }
4924
4925 stop_state =
4926 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4927
4928 if (stop_state != eStateRunning) {
4929 bool restarted = false;
4930
4931 if (stop_state == eStateStopped) {
4932 restarted = Process::ProcessEventData::GetRestartedFromEvent(
4933 event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004934 LLDB_LOGF(
4935 log,
4936 "Process::RunThreadPlan(): didn't get running event after "
4937 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4938 "handle_running_event: %i).",
4939 num_resumes, StateAsCString(stop_state), restarted, do_resume,
4940 handle_running_event);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004941 }
4942
4943 if (restarted) {
4944 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00004945 // should ever get a stopped & restarted event here. But if I do,
4946 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004947 const bool clear_thread_plans = false;
4948 const bool use_run_lock = false;
4949 Halt(clear_thread_plans, use_run_lock);
4950 }
4951
4952 diagnostic_manager.Printf(
4953 eDiagnosticSeverityError,
4954 "didn't get running event after initial resume, got %s instead.",
4955 StateAsCString(stop_state));
4956 return_value = eExpressionSetupError;
4957 break;
4958 }
4959
4960 if (log)
4961 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00004962 // We need to call the function synchronously, so spin waiting for it
4963 // to return. If we get interrupted while executing, we're going to
4964 // lose our context, and won't be able to gather the result at this
4965 // point. We set the timeout AFTER the resume, since the resume takes
4966 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004967 } else {
4968 if (log)
4969 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
4970 }
4971
Kate Stoneb9c1b512016-09-06 20:57:50 +00004972 do_resume = true;
4973 handle_running_event = true;
4974
4975 // Now wait for the process to stop again:
4976 event_sp.reset();
4977
Pavel Labath2ce22162016-12-01 10:57:30 +00004978 Timeout<std::micro> timeout =
4979 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004980 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004981 if (timeout) {
4982 auto now = system_clock::now();
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004983 LLDB_LOGF(log,
4984 "Process::RunThreadPlan(): about to wait - now is %s - "
4985 "endpoint is %s",
4986 llvm::to_string(now).c_str(),
4987 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004988 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00004989 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00004990 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004991 }
4992
4993#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4994 // See comment above...
4995 if (miss_first_event) {
Pavel Labath3d4f7652019-08-05 08:23:25 +00004996 std::this_thread::sleep_for(std::chrono::milliseconds(1));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004997 miss_first_event = false;
4998 got_event = false;
4999 } else
5000#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005001 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005002
5003 if (got_event) {
5004 if (event_sp) {
5005 bool keep_going = false;
5006 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5007 const bool clear_thread_plans = false;
5008 const bool use_run_lock = false;
5009 Halt(clear_thread_plans, use_run_lock);
5010 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005011 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5012 "execution halted by user interrupt.");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005013 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
5014 "eBroadcastBitInterrupted, exiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005015 break;
5016 } else {
5017 stop_state =
5018 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005019 LLDB_LOGF(log,
5020 "Process::RunThreadPlan(): in while loop, got event: %s.",
5021 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005022
5023 switch (stop_state) {
5024 case lldb::eStateStopped: {
5025 // We stopped, figure out what we are going to do now.
5026 ThreadSP thread_sp =
5027 GetThreadList().FindThreadByIndexID(thread_idx_id);
5028 if (!thread_sp) {
5029 // Ooh, our thread has vanished. Unlikely that this was
5030 // successful execution...
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005031 LLDB_LOGF(log,
5032 "Process::RunThreadPlan(): execution completed "
5033 "but our thread (index-id=%u) has vanished.",
5034 thread_idx_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005035 return_value = eExpressionInterrupted;
Pavel Labath45dde232017-05-25 10:50:06 +00005036 } else if (Process::ProcessEventData::GetRestartedFromEvent(
5037 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005038 // If we were restarted, we just need to go back up to fetch
5039 // another event.
Pavel Labath45dde232017-05-25 10:50:06 +00005040 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005041 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5042 "restart, so we'll continue waiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005043 }
Pavel Labath45dde232017-05-25 10:50:06 +00005044 keep_going = true;
5045 do_resume = false;
5046 handle_running_event = true;
5047 } else {
5048 const bool handle_interrupts = true;
5049 return_value = *HandleStoppedEvent(
5050 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5051 event_to_broadcast_sp, options, handle_interrupts);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005052 }
5053 } break;
5054
5055 case lldb::eStateRunning:
5056 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005057 // running events without an intervening stop, and in that case
5058 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005059 do_resume = false;
5060 keep_going = true;
5061 handle_running_event = false;
5062 break;
5063
5064 default:
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005065 LLDB_LOGF(log,
5066 "Process::RunThreadPlan(): execution stopped with "
5067 "unexpected state: %s.",
5068 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005069
5070 if (stop_state == eStateExited)
5071 event_to_broadcast_sp = event_sp;
5072
Zachary Turnere2411fa2016-11-12 19:12:56 +00005073 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005074 eDiagnosticSeverityError,
5075 "execution stopped with unexpected state.");
5076 return_value = eExpressionInterrupted;
5077 break;
5078 }
5079 }
5080
5081 if (keep_going)
5082 continue;
5083 else
5084 break;
5085 } else {
5086 if (log)
5087 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5088 "the event pointer was null. How odd...");
5089 return_value = eExpressionInterrupted;
5090 break;
5091 }
5092 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005093 // If we didn't get an event that means we've timed out... We will
5094 // interrupt the process here. Depending on what we were asked to do
5095 // we will either exit, or try with all threads running for the same
5096 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005097
5098 if (log) {
5099 if (options.GetTryAllThreads()) {
5100 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005101 LLDB_LOG(log,
5102 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005103 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005104 LLDB_LOG(log, "Restarting function with all threads enabled and "
5105 "timeout: {0} timed out, abandoning execution.",
5106 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005107 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005108 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5109 "abandoning execution.",
5110 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005111 }
5112
5113 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005114 // around to calling Halt the target could have stopped. That's fine,
5115 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005116 // BUT it is also possible that we stopped & restarted (e.g. hit a
5117 // signal with "stop" set to false.) In
5118 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005119 // back to waiting for the Halt's stopped event. That's what this
5120 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005121
5122 bool back_to_top = true;
5123 uint32_t try_halt_again = 0;
5124 bool do_halt = true;
5125 const uint32_t num_retries = 5;
5126 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005127 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005128 if (do_halt) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005129 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005130 const bool clear_thread_plans = false;
5131 const bool use_run_lock = false;
5132 Halt(clear_thread_plans, use_run_lock);
5133 }
5134 if (halt_error.Success()) {
5135 if (log)
5136 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5137
Pavel Labathd35031e12016-11-30 10:41:42 +00005138 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00005139 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005140
5141 if (got_event) {
5142 stop_state =
5143 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5144 if (log) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005145 LLDB_LOGF(log,
5146 "Process::RunThreadPlan(): Stopped with event: %s",
5147 StateAsCString(stop_state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005148 if (stop_state == lldb::eStateStopped &&
5149 Process::ProcessEventData::GetInterruptedFromEvent(
5150 event_sp.get()))
5151 log->PutCString(" Event was the Halt interruption event.");
5152 }
5153
5154 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005155 if (Process::ProcessEventData::GetRestartedFromEvent(
5156 event_sp.get())) {
5157 if (log)
5158 log->PutCString("Process::RunThreadPlan(): Went to halt "
5159 "but got a restarted event, there must be "
5160 "an un-restarted stopped event so try "
5161 "again... "
5162 "Exiting wait loop.");
5163 try_halt_again++;
5164 do_halt = false;
5165 continue;
5166 }
5167
Pavel Labath45dde232017-05-25 10:50:06 +00005168 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005169 // delivered it, the process could have already finished its
5170 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005171 const bool handle_interrupts = false;
5172 if (auto result = HandleStoppedEvent(
5173 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5174 event_to_broadcast_sp, options, handle_interrupts)) {
5175 return_value = *result;
5176 back_to_top = false;
5177 break;
5178 }
5179
Kate Stoneb9c1b512016-09-06 20:57:50 +00005180 if (!options.GetTryAllThreads()) {
5181 if (log)
5182 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5183 "was false, we stopped so now we're "
5184 "quitting.");
5185 return_value = eExpressionInterrupted;
5186 back_to_top = false;
5187 break;
5188 }
5189
5190 if (before_first_timeout) {
5191 // Set all the other threads to run, and return to the top of
5192 // the loop, which will continue;
5193 before_first_timeout = false;
5194 thread_plan_sp->SetStopOthers(false);
5195 if (log)
5196 log->PutCString(
5197 "Process::RunThreadPlan(): about to resume.");
5198
5199 back_to_top = true;
5200 break;
5201 } else {
5202 // Running all threads failed, so return Interrupted.
5203 if (log)
5204 log->PutCString("Process::RunThreadPlan(): running all "
5205 "threads timed out.");
5206 return_value = eExpressionInterrupted;
5207 back_to_top = false;
5208 break;
5209 }
5210 }
5211 } else {
5212 if (log)
5213 log->PutCString("Process::RunThreadPlan(): halt said it "
5214 "succeeded, but I got no event. "
5215 "I'm getting out of here passing Interrupted.");
5216 return_value = eExpressionInterrupted;
5217 back_to_top = false;
5218 break;
5219 }
5220 } else {
5221 try_halt_again++;
5222 continue;
5223 }
5224 }
5225
5226 if (!back_to_top || try_halt_again > num_retries)
5227 break;
5228 else
5229 continue;
5230 }
5231 } // END WAIT LOOP
5232
Adrian Prantl05097242018-04-30 16:49:04 +00005233 // If we had to start up a temporary private state thread to run this
5234 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005235 if (backup_private_state_thread.IsJoinable()) {
5236 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005237 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005238 m_private_state_thread = backup_private_state_thread;
5239 if (stopper_base_plan_sp) {
5240 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5241 }
5242 if (old_state != eStateInvalid)
5243 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005244 }
5245
Kate Stoneb9c1b512016-09-06 20:57:50 +00005246 if (return_value != eExpressionCompleted && log) {
5247 // Print a backtrace into the log so we can figure out where we are:
5248 StreamString s;
5249 s.PutCString("Thread state after unsuccessful completion: \n");
5250 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005251 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005252 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005253 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005254 // There are three cases where this could happen: 1) The execution
5255 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5256 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005257 bool should_unwind = (return_value == eExpressionInterrupted &&
5258 options.DoesUnwindOnError()) ||
5259 (return_value == eExpressionHitBreakpoint &&
5260 options.DoesIgnoreBreakpoints());
5261
5262 if (return_value == eExpressionCompleted || should_unwind) {
5263 thread_plan_sp->RestoreThreadState();
5264 }
5265
5266 // Now do some processing on the results of the run:
5267 if (return_value == eExpressionInterrupted ||
5268 return_value == eExpressionHitBreakpoint) {
5269 if (log) {
5270 StreamString s;
5271 if (event_sp)
5272 event_sp->Dump(&s);
5273 else {
5274 log->PutCString("Process::RunThreadPlan(): Stop event that "
5275 "interrupted us is NULL.");
5276 }
5277
5278 StreamString ts;
5279
5280 const char *event_explanation = nullptr;
5281
5282 do {
5283 if (!event_sp) {
5284 event_explanation = "<no event>";
5285 break;
5286 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5287 event_explanation = "<user interrupt>";
5288 break;
5289 } else {
5290 const Process::ProcessEventData *event_data =
5291 Process::ProcessEventData::GetEventDataFromEvent(
5292 event_sp.get());
5293
5294 if (!event_data) {
5295 event_explanation = "<no event data>";
5296 break;
5297 }
5298
5299 Process *process = event_data->GetProcessSP().get();
5300
5301 if (!process) {
5302 event_explanation = "<no process>";
5303 break;
5304 }
5305
5306 ThreadList &thread_list = process->GetThreadList();
5307
5308 uint32_t num_threads = thread_list.GetSize();
5309 uint32_t thread_index;
5310
5311 ts.Printf("<%u threads> ", num_threads);
5312
5313 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5314 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5315
5316 if (!thread) {
5317 ts.Printf("<?> ");
5318 continue;
5319 }
5320
5321 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5322 RegisterContext *register_context =
5323 thread->GetRegisterContext().get();
5324
5325 if (register_context)
5326 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5327 else
5328 ts.Printf("[ip unknown] ");
5329
5330 // Show the private stop info here, the public stop info will be
5331 // from the last natural stop.
5332 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5333 if (stop_info_sp) {
5334 const char *stop_desc = stop_info_sp->GetDescription();
5335 if (stop_desc)
5336 ts.PutCString(stop_desc);
5337 }
5338 ts.Printf(">");
5339 }
5340
5341 event_explanation = ts.GetData();
5342 }
Jonas Devlieghere09ad8c82019-05-24 00:44:33 +00005343 } while (false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005344
5345 if (event_explanation)
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005346 LLDB_LOGF(log,
5347 "Process::RunThreadPlan(): execution interrupted: %s %s",
5348 s.GetData(), event_explanation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005349 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005350 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
5351 s.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005352 }
5353
5354 if (should_unwind) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005355 LLDB_LOGF(log,
5356 "Process::RunThreadPlan: ExecutionInterrupted - "
5357 "discarding thread plans up to %p.",
5358 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005359 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5360 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005361 LLDB_LOGF(log,
5362 "Process::RunThreadPlan: ExecutionInterrupted - for "
5363 "plan: %p not discarding.",
5364 static_cast<void *>(thread_plan_sp.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005365 }
5366 } else if (return_value == eExpressionSetupError) {
5367 if (log)
5368 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5369
5370 if (options.DoesUnwindOnError()) {
5371 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5372 }
5373 } else {
5374 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5375 if (log)
5376 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5377 return_value = eExpressionCompleted;
5378 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5379 if (log)
5380 log->PutCString(
5381 "Process::RunThreadPlan(): thread plan was discarded");
5382 return_value = eExpressionDiscarded;
5383 } else {
5384 if (log)
5385 log->PutCString(
5386 "Process::RunThreadPlan(): thread plan stopped in mid course");
5387 if (options.DoesUnwindOnError() && thread_plan_sp) {
5388 if (log)
5389 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5390 "'cause unwind_on_error is set.");
5391 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5392 }
5393 }
5394 }
5395
5396 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005397 // target Check that it's still there, and if it is put it back in the
5398 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005399 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5400 if (thread) {
5401 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5402 }
5403
5404 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005405 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005406
5407 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5408 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5409 selected_stack_id.IsValid()) {
5410 // We were able to restore the selected thread, now restore the frame:
5411 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5412 StackFrameSP old_frame_sp =
5413 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5414 selected_stack_id);
5415 if (old_frame_sp)
5416 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5417 old_frame_sp.get());
5418 }
5419 }
5420 }
5421
5422 // If the process exited during the run of the thread plan, notify everyone.
5423
5424 if (event_to_broadcast_sp) {
5425 if (log)
5426 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5427 BroadcastEvent(event_to_broadcast_sp);
5428 }
5429
5430 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005431}
5432
Kate Stoneb9c1b512016-09-06 20:57:50 +00005433const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5434 const char *result_name;
5435
5436 switch (result) {
5437 case eExpressionCompleted:
5438 result_name = "eExpressionCompleted";
5439 break;
5440 case eExpressionDiscarded:
5441 result_name = "eExpressionDiscarded";
5442 break;
5443 case eExpressionInterrupted:
5444 result_name = "eExpressionInterrupted";
5445 break;
5446 case eExpressionHitBreakpoint:
5447 result_name = "eExpressionHitBreakpoint";
5448 break;
5449 case eExpressionSetupError:
5450 result_name = "eExpressionSetupError";
5451 break;
5452 case eExpressionParseError:
5453 result_name = "eExpressionParseError";
5454 break;
5455 case eExpressionResultUnavailable:
5456 result_name = "eExpressionResultUnavailable";
5457 break;
5458 case eExpressionTimedOut:
5459 result_name = "eExpressionTimedOut";
5460 break;
5461 case eExpressionStoppedForDebug:
5462 result_name = "eExpressionStoppedForDebug";
5463 break;
5464 }
5465 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005466}
5467
Kate Stoneb9c1b512016-09-06 20:57:50 +00005468void Process::GetStatus(Stream &strm) {
5469 const StateType state = GetState();
5470 if (StateIsStoppedState(state, false)) {
5471 if (state == eStateExited) {
5472 int exit_status = GetExitStatus();
5473 const char *exit_description = GetExitDescription();
5474 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5475 GetID(), exit_status, exit_status,
5476 exit_description ? exit_description : "");
5477 } else {
5478 if (state == eStateConnected)
5479 strm.Printf("Connected to remote target.\n");
5480 else
5481 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5482 }
5483 } else {
5484 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5485 }
Pavel Labatha933d512016-04-05 13:07:16 +00005486}
5487
Kate Stoneb9c1b512016-09-06 20:57:50 +00005488size_t Process::GetThreadStatus(Stream &strm,
5489 bool only_threads_with_stop_reason,
5490 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005491 uint32_t num_frames_with_source,
5492 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005493 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005494
Kate Stoneb9c1b512016-09-06 20:57:50 +00005495 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005496 // very well might run code (e.g. if we need it to get return values or
5497 // arguments.) For that to work the process has to be able to acquire it.
5498 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005499
5500 uint32_t num_threads;
5501 std::vector<lldb::tid_t> thread_id_array;
5502 // Scope for thread list locker;
5503 {
5504 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5505 ThreadList &curr_thread_list = GetThreadList();
5506 num_threads = curr_thread_list.GetSize();
5507 uint32_t idx;
5508 thread_id_array.resize(num_threads);
5509 for (idx = 0; idx < num_threads; ++idx)
5510 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5511 }
5512
5513 for (uint32_t i = 0; i < num_threads; i++) {
5514 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5515 if (thread_sp) {
5516 if (only_threads_with_stop_reason) {
5517 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5518 if (!stop_info_sp || !stop_info_sp->IsValid())
5519 continue;
5520 }
5521 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005522 num_frames_with_source,
5523 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005524 ++num_thread_infos_dumped;
5525 } else {
5526 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005527 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
5528 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005529 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005530 }
5531 return num_thread_infos_dumped;
5532}
5533
5534void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5535 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5536}
5537
5538bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5539 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5540 region.GetByteSize());
5541}
5542
5543void Process::AddPreResumeAction(PreResumeActionCallback callback,
5544 void *baton) {
5545 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5546}
5547
5548bool Process::RunPreResumeActions() {
5549 bool result = true;
5550 while (!m_pre_resume_actions.empty()) {
5551 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5552 m_pre_resume_actions.pop_back();
5553 bool this_result = action.callback(action.baton);
5554 if (result)
5555 result = this_result;
5556 }
5557 return result;
5558}
5559
5560void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5561
Jim Inghamffd91752016-10-20 22:50:00 +00005562void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5563{
5564 PreResumeCallbackAndBaton element(callback, baton);
5565 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5566 if (found_iter != m_pre_resume_actions.end())
5567 {
5568 m_pre_resume_actions.erase(found_iter);
5569 }
5570}
5571
Kate Stoneb9c1b512016-09-06 20:57:50 +00005572ProcessRunLock &Process::GetRunLock() {
5573 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5574 return m_private_run_lock;
5575 else
5576 return m_public_run_lock;
5577}
5578
Jim Ingham58c3235e2019-10-01 00:47:25 +00005579bool Process::CurrentThreadIsPrivateStateThread()
5580{
5581 return m_private_state_thread.EqualsThread(Host::GetCurrentThread());
5582}
5583
5584
Kate Stoneb9c1b512016-09-06 20:57:50 +00005585void Process::Flush() {
5586 m_thread_list.Flush();
5587 m_extended_thread_list.Flush();
5588 m_extended_thread_stop_id = 0;
5589 m_queue_list.Clear();
5590 m_queue_list_stop_id = 0;
5591}
5592
5593void Process::DidExec() {
5594 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005595 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005596
5597 Target &target = GetTarget();
5598 target.CleanupProcess();
5599 target.ClearModules(false);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005600 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005601 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005602 m_system_runtime_up.reset();
5603 m_os_up.reset();
5604 m_dyld_up.reset();
5605 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005606 m_image_tokens.clear();
5607 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +00005608 {
5609 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5610 m_language_runtimes.clear();
5611 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005612 m_instrumentation_runtimes.clear();
5613 m_thread_list.DiscardThreadPlans();
5614 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005615 DoDidExec();
5616 CompleteAttach();
5617 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005618 // CompleteAttach() in case the dynamic loader loaded things in new
5619 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005620 Flush();
5621
Adrian Prantl05097242018-04-30 16:49:04 +00005622 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5623 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005624 target.DidExec();
5625}
5626
Zachary Turner97206d52017-05-12 04:51:55 +00005627addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005628 if (address == nullptr) {
5629 error.SetErrorString("Invalid address argument");
5630 return LLDB_INVALID_ADDRESS;
5631 }
5632
5633 addr_t function_addr = LLDB_INVALID_ADDRESS;
5634
5635 addr_t addr = address->GetLoadAddress(&GetTarget());
5636 std::map<addr_t, addr_t>::const_iterator iter =
5637 m_resolved_indirect_addresses.find(addr);
5638 if (iter != m_resolved_indirect_addresses.end()) {
5639 function_addr = (*iter).second;
5640 } else {
Alex Langford5b2b38e2019-09-13 00:02:05 +00005641 if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005642 Symbol *symbol = address->CalculateSymbolContextSymbol();
5643 error.SetErrorStringWithFormat(
5644 "Unable to call resolver for indirect function %s",
5645 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5646 function_addr = LLDB_INVALID_ADDRESS;
5647 } else {
5648 m_resolved_indirect_addresses.insert(
5649 std::pair<addr_t, addr_t>(addr, function_addr));
5650 }
5651 }
5652 return function_addr;
5653}
5654
5655void Process::ModulesDidLoad(ModuleList &module_list) {
5656 SystemRuntime *sys_runtime = GetSystemRuntime();
5657 if (sys_runtime) {
5658 sys_runtime->ModulesDidLoad(module_list);
5659 }
5660
5661 GetJITLoaders().ModulesDidLoad(module_list);
5662
5663 // Give runtimes a chance to be created.
5664 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5665 m_instrumentation_runtimes);
5666
5667 // Tell runtimes about new modules.
5668 for (auto pos = m_instrumentation_runtimes.begin();
5669 pos != m_instrumentation_runtimes.end(); ++pos) {
5670 InstrumentationRuntimeSP runtime = pos->second;
5671 runtime->ModulesDidLoad(module_list);
5672 }
5673
Adrian Prantl05097242018-04-30 16:49:04 +00005674 // Let any language runtimes we have already created know about the modules
5675 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005676
Adrian Prantl05097242018-04-30 16:49:04 +00005677 // Iterate over a copy of this language runtime list in case the language
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005678 // runtime ModulesDidLoad somehow causes the language runtime to be
Adrian Prantl05097242018-04-30 16:49:04 +00005679 // unloaded.
Alex Langford74eb76f2019-05-22 23:01:18 +00005680 {
5681 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5682 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5683 for (const auto &pair : language_runtimes) {
5684 // We must check language_runtime_sp to make sure it is not nullptr as we
5685 // might cache the fact that we didn't have a language runtime for a
5686 // language.
5687 LanguageRuntimeSP language_runtime_sp = pair.second;
5688 if (language_runtime_sp)
5689 language_runtime_sp->ModulesDidLoad(module_list);
5690 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005691 }
5692
5693 // If we don't have an operating system plug-in, try to load one since
5694 // loading shared libraries might cause a new one to try and load
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005695 if (!m_os_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005696 LoadOperatingSystemPlugin(false);
5697
5698 // Give structured-data plugins a chance to see the modified modules.
5699 for (auto pair : m_structured_data_plugin_map) {
5700 if (pair.second)
5701 pair.second->ModulesDidLoad(*this, module_list);
5702 }
5703}
5704
5705void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5706 const char *fmt, ...) {
5707 bool print_warning = true;
5708
5709 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5710 if (!stream_sp)
5711 return;
5712 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5713 return;
5714 }
5715
5716 if (repeat_key != nullptr) {
5717 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5718 if (it == m_warnings_issued.end()) {
5719 m_warnings_issued[warning_type] = WarningsPointerSet();
5720 m_warnings_issued[warning_type].insert(repeat_key);
5721 } else {
5722 if (it->second.find(repeat_key) != it->second.end()) {
5723 print_warning = false;
5724 } else {
5725 it->second.insert(repeat_key);
5726 }
5727 }
5728 }
5729
5730 if (print_warning) {
5731 va_list args;
5732 va_start(args, fmt);
5733 stream_sp->PrintfVarArg(fmt, args);
5734 va_end(args);
5735 }
5736}
5737
5738void Process::PrintWarningOptimization(const SymbolContext &sc) {
5739 if (GetWarningsOptimization() && sc.module_sp &&
5740 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5741 sc.function->GetIsOptimized()) {
5742 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5743 "%s was compiled with optimization - stepping may behave "
5744 "oddly; variables may not be available.\n",
5745 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5746 }
5747}
5748
5749bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5750 info.Clear();
5751
5752 PlatformSP platform_sp = GetTarget().GetPlatform();
5753 if (!platform_sp)
5754 return false;
5755
5756 return platform_sp->GetProcessInfo(GetID(), info);
5757}
5758
5759ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5760 ThreadCollectionSP threads;
5761
5762 const MemoryHistorySP &memory_history =
5763 MemoryHistory::FindPlugin(shared_from_this());
5764
5765 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005766 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005767 }
5768
Jonas Devlieghere796ac802019-02-11 23:13:08 +00005769 threads = std::make_shared<ThreadCollection>(
5770 memory_history->GetHistoryThreads(addr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005771
5772 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005773}
Kuba Brecka63927542014-10-11 01:59:32 +00005774
5775InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005776Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5777 InstrumentationRuntimeCollection::iterator pos;
5778 pos = m_instrumentation_runtimes.find(type);
5779 if (pos == m_instrumentation_runtimes.end()) {
5780 return InstrumentationRuntimeSP();
5781 } else
5782 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005783}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005784
Kate Stoneb9c1b512016-09-06 20:57:50 +00005785bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5786 const ArchSpec &arch, ModuleSpec &module_spec) {
5787 module_spec.Clear();
5788 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005789}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005790
Kate Stoneb9c1b512016-09-06 20:57:50 +00005791size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5792 m_image_tokens.push_back(image_ptr);
5793 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005794}
5795
Kate Stoneb9c1b512016-09-06 20:57:50 +00005796lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5797 if (token < m_image_tokens.size())
5798 return m_image_tokens[token];
Saleem Abdulrasool3775be22020-04-06 17:33:38 -07005799 return LLDB_INVALID_ADDRESS;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005800}
5801
Kate Stoneb9c1b512016-09-06 20:57:50 +00005802void Process::ResetImageToken(size_t token) {
5803 if (token < m_image_tokens.size())
Saleem Abdulrasool3775be22020-04-06 17:33:38 -07005804 m_image_tokens[token] = LLDB_INVALID_ADDRESS;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005805}
Jason Molendafd4cea52016-01-08 21:40:11 +00005806
5807Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005808Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5809 AddressRange range_bounds) {
5810 Target &target = GetTarget();
5811 DisassemblerSP disassembler_sp;
5812 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005813
Kate Stoneb9c1b512016-09-06 20:57:50 +00005814 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005815
Kate Stoneb9c1b512016-09-06 20:57:50 +00005816 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005817 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005818 if (!default_stop_addr.IsValid())
5819 return retval;
5820
Kate Stoneb9c1b512016-09-06 20:57:50 +00005821 const char *plugin_name = nullptr;
5822 const char *flavor = nullptr;
5823 const bool prefer_file_cache = true;
5824 disassembler_sp = Disassembler::DisassembleRange(
Pavel Labath04592d52020-03-05 13:03:26 +01005825 target.GetArchitecture(), plugin_name, flavor, GetTarget(), range_bounds,
Kate Stoneb9c1b512016-09-06 20:57:50 +00005826 prefer_file_cache);
5827 if (disassembler_sp)
5828 insn_list = &disassembler_sp->GetInstructionList();
5829
5830 if (insn_list == nullptr) {
5831 return retval;
5832 }
5833
5834 size_t insn_offset =
5835 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5836 if (insn_offset == UINT32_MAX) {
5837 return retval;
5838 }
5839
5840 uint32_t branch_index =
Greg Claytondf225762019-05-09 20:39:34 +00005841 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target,
Jim Ingham434905b2019-12-16 17:38:13 -08005842 false /* ignore_calls*/,
5843 nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005844 if (branch_index == UINT32_MAX) {
5845 return retval;
5846 }
5847
5848 if (branch_index > insn_offset) {
5849 Address next_branch_insn_address =
5850 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5851 if (next_branch_insn_address.IsValid() &&
5852 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5853 retval = next_branch_insn_address;
5854 }
5855 }
5856
5857 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00005858}
Howard Hellyerad007562016-07-07 08:21:28 +00005859
Zachary Turner97206d52017-05-12 04:51:55 +00005860Status
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005861Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00005862
Zachary Turner97206d52017-05-12 04:51:55 +00005863 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00005864
Kate Stoneb9c1b512016-09-06 20:57:50 +00005865 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00005866
Kate Stoneb9c1b512016-09-06 20:57:50 +00005867 region_list.clear();
5868 do {
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005869 lldb_private::MemoryRegionInfo region_info;
5870 error = GetMemoryRegionInfo(range_end, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005871 // GetMemoryRegionInfo should only return an error if it is unimplemented.
5872 if (error.Fail()) {
5873 region_list.clear();
5874 break;
Todd Fiala75930012016-08-19 04:21:48 +00005875 }
5876
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005877 range_end = region_info.GetRange().GetRangeEnd();
5878 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5879 region_list.push_back(std::move(region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005880 }
5881 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00005882
Kate Stoneb9c1b512016-09-06 20:57:50 +00005883 return error;
5884}
5885
Zachary Turner97206d52017-05-12 04:51:55 +00005886Status
Adrian Prantl0e4c4822019-03-06 21:22:25 +00005887Process::ConfigureStructuredData(ConstString type_name,
Zachary Turner97206d52017-05-12 04:51:55 +00005888 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005889 // If you get this, the Process-derived class needs to implement a method to
5890 // enable an already-reported asynchronous structured data feature. See
5891 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00005892 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005893}
5894
5895void Process::MapSupportedStructuredDataPlugins(
5896 const StructuredData::Array &supported_type_names) {
5897 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5898
5899 // Bail out early if there are no type names to map.
5900 if (supported_type_names.GetSize() == 0) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005901 LLDB_LOGF(log, "Process::%s(): no structured data types supported",
5902 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005903 return;
5904 }
Todd Fiala75930012016-08-19 04:21:48 +00005905
Kate Stoneb9c1b512016-09-06 20:57:50 +00005906 // Convert StructuredData type names to ConstString instances.
5907 std::set<ConstString> const_type_names;
5908
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005909 LLDB_LOGF(log,
5910 "Process::%s(): the process supports the following async "
5911 "structured data types:",
5912 __FUNCTION__);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005913
5914 supported_type_names.ForEach(
5915 [&const_type_names, &log](StructuredData::Object *object) {
5916 if (!object) {
5917 // Invalid - shouldn't be null objects in the array.
5918 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005919 }
5920
5921 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005922 if (!type_name) {
5923 // Invalid format - all type names should be strings.
5924 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005925 }
5926
5927 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00005928 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00005929 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005930 });
Todd Fiala75930012016-08-19 04:21:48 +00005931
Adrian Prantl05097242018-04-30 16:49:04 +00005932 // For each StructuredDataPlugin, if the plugin handles any of the types in
5933 // the supported_type_names, map that type name to that plugin. Stop when
5934 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005935 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00005936 // supports?
5937 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
5938 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00005939 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
5940 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00005941 if (!create_instance)
5942 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005943
Kate Stoneb9c1b512016-09-06 20:57:50 +00005944 // Create the plugin.
5945 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
5946 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005947 // This plugin doesn't think it can work with the process. Move on to the
5948 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005949 continue;
Todd Fiala75930012016-08-19 04:21:48 +00005950 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005951
Adrian Prantl05097242018-04-30 16:49:04 +00005952 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005953 std::vector<ConstString> names_to_remove;
5954 for (auto &type_name : const_type_names) {
5955 if (plugin_sp->SupportsStructuredDataType(type_name)) {
5956 m_structured_data_plugin_map.insert(
5957 std::make_pair(type_name, plugin_sp));
5958 names_to_remove.push_back(type_name);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00005959 LLDB_LOGF(log,
5960 "Process::%s(): using plugin %s for type name "
5961 "%s",
5962 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
5963 type_name.GetCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005964 }
5965 }
5966
5967 // Remove the type names that were consumed by this plugin.
5968 for (auto &type_name : names_to_remove)
5969 const_type_names.erase(type_name);
5970 }
Todd Fiala75930012016-08-19 04:21:48 +00005971}
5972
Kate Stoneb9c1b512016-09-06 20:57:50 +00005973bool Process::RouteAsyncStructuredData(
5974 const StructuredData::ObjectSP object_sp) {
5975 // Nothing to do if there's no data.
5976 if (!object_sp)
5977 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005978
Adrian Prantl05097242018-04-30 16:49:04 +00005979 // The contract is this must be a dictionary, so we can look up the routing
5980 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005981 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
5982 if (!dictionary)
5983 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005984
Kate Stoneb9c1b512016-09-06 20:57:50 +00005985 // Grab the async structured type name (i.e. the feature/plugin name).
5986 ConstString type_name;
5987 if (!dictionary->GetValueForKeyAsString("type", type_name))
5988 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005989
Kate Stoneb9c1b512016-09-06 20:57:50 +00005990 // Check if there's a plugin registered for this type name.
5991 auto find_it = m_structured_data_plugin_map.find(type_name);
5992 if (find_it == m_structured_data_plugin_map.end()) {
5993 // We don't have a mapping for this structured data type.
5994 return false;
5995 }
Todd Fiala75930012016-08-19 04:21:48 +00005996
Kate Stoneb9c1b512016-09-06 20:57:50 +00005997 // Route the structured data to the plugin.
5998 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
5999 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006000}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006001
Zachary Turner97206d52017-05-12 04:51:55 +00006002Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006003 // Default implementation does nothign.
6004 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00006005 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006006}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006007
Frederic Rissd10d3792018-05-11 18:21:11 +00006008UtilityFunction *Process::GetLoadImageUtilityFunction(
6009 Platform *platform,
6010 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006011 if (platform != GetTarget().GetPlatform().get())
6012 return nullptr;
Michal Gorny3276fff2019-09-03 12:31:24 +00006013 llvm::call_once(m_dlopen_utility_func_flag_once,
6014 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006015 return m_dlopen_utility_func_up.get();
6016}
Alex Langford5b2b38e2019-09-13 00:02:05 +00006017
6018bool Process::CallVoidArgVoidPtrReturn(const Address *address,
6019 addr_t &returned_func,
6020 bool trap_exceptions) {
6021 Thread *thread = GetThreadList().GetExpressionExecutionThread().get();
6022 if (thread == nullptr || address == nullptr)
6023 return false;
6024
6025 EvaluateExpressionOptions options;
6026 options.SetStopOthers(true);
6027 options.SetUnwindOnError(true);
6028 options.SetIgnoreBreakpoints(true);
6029 options.SetTryAllThreads(true);
6030 options.SetDebug(false);
6031 options.SetTimeout(GetUtilityExpressionTimeout());
6032 options.SetTrapExceptions(trap_exceptions);
6033
6034 auto type_system_or_err =
6035 GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC);
6036 if (!type_system_or_err) {
6037 llvm::consumeError(type_system_or_err.takeError());
6038 return false;
6039 }
6040 CompilerType void_ptr_type =
6041 type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
6042 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction(
6043 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
6044 if (call_plan_sp) {
6045 DiagnosticManager diagnostics;
6046
6047 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6048 if (frame) {
6049 ExecutionContext exe_ctx;
6050 frame->CalculateExecutionContext(exe_ctx);
6051 ExpressionResults result =
6052 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
6053 if (result == eExpressionCompleted) {
6054 returned_func =
6055 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6056 LLDB_INVALID_ADDRESS);
6057
6058 if (GetAddressByteSize() == 4) {
6059 if (returned_func == UINT32_MAX)
6060 return false;
6061 } else if (GetAddressByteSize() == 8) {
6062 if (returned_func == UINT64_MAX)
6063 return false;
6064 }
6065 return true;
6066 }
6067 }
6068 }
6069
6070 return false;
6071}