blob: 996782b53786d6f3c0130efd636628c9422ef03c [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Eugene Zelenko8f30a652015-10-23 18:39:37 +000010// C Includes
11// C++ Includes
Greg Clayton5cc45e02016-02-26 19:41:49 +000012#include <atomic>
Greg Clayton04df8ee2016-02-26 19:38:18 +000013#include <mutex>
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +000014
Eugene Zelenko8f30a652015-10-23 18:39:37 +000015// Other libraries and framework includes
Pavel Labath2ce22162016-12-01 10:57:30 +000016#include "llvm/Support/ScopedPrinter.h"
Zachary Turner777de772017-03-04 16:42:25 +000017#include "llvm/Support/Threading.h"
18
Eugene Zelenko8f30a652015-10-23 18:39:37 +000019// Project includes
Sean Callanan579e70c2016-03-19 00:03:59 +000020#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include "lldb/Breakpoint/BreakpointLocation.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000022#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include "lldb/Core/Debugger.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000024#include "lldb/Core/Event.h"
Greg Clayton1f746072012-08-29 21:13:06 +000025#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000026#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027#include "lldb/Core/PluginManager.h"
28#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000029#include "lldb/Core/StreamFile.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000030#include "lldb/Expression/DiagnosticManager.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000031#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000032#include "lldb/Expression/UserExpression.h"
Jim Ingham1ecb34f2018-04-17 20:44:47 +000033#include "lldb/Expression/UtilityFunction.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000034#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000035#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000037#include "lldb/Host/HostInfo.h"
Zachary Turner3eb2b442017-03-22 23:33:16 +000038#include "lldb/Host/OptionParser.h"
Greg Clayton100eb932014-07-02 21:10:39 +000039#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000040#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000041#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000042#include "lldb/Interpreter/CommandInterpreter.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000043#include "lldb/Interpreter/OptionArgParser.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000044#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000045#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000046#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Target/ABI.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000048#include "lldb/Target/CPPLanguageRuntime.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000049#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000050#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000051#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000052#include "lldb/Target/JITLoaderList.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000053#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000054#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000055#include "lldb/Target/MemoryRegionInfo.h"
Jim Ingham22777012010-09-23 02:01:19 +000056#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000057#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000058#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000059#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000060#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000061#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000062#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000063#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000064#include "lldb/Target/Target.h"
65#include "lldb/Target/TargetList.h"
66#include "lldb/Target/Thread.h"
67#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000068#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000069#include "lldb/Target/UnixSignals.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000070#include "lldb/Utility/Log.h"
Zachary Turner50232572015-03-18 21:31:45 +000071#include "lldb/Utility/NameMatches.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000072#include "lldb/Utility/SelectHelper.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073
74using namespace lldb;
75using namespace lldb_private;
Pavel Labathe3e21cf2016-11-30 11:56:32 +000076using namespace std::chrono;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000077
Kate Stoneb9c1b512016-09-06 20:57:50 +000078// Comment out line below to disable memory caching, overriding the process
Pavel Labath43d35412016-12-06 11:24:51 +000079// setting target.process.disable-memory-cache
Greg Clayton67cc0632012-08-22 17:17:09 +000080#define ENABLE_MEMORY_CACHING
81
82#ifdef ENABLE_MEMORY_CACHING
83#define DISABLE_MEM_CACHE_DEFAULT false
84#else
85#define DISABLE_MEM_CACHE_DEFAULT true
86#endif
87
Kate Stoneb9c1b512016-09-06 20:57:50 +000088class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000089public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000090 ProcessOptionValueProperties(const ConstString &name)
91 : OptionValueProperties(name) {}
92
Adrian Prantl05097242018-04-30 16:49:04 +000093 // This constructor is used when creating ProcessOptionValueProperties when
94 // it is part of a new lldb_private::Process instance. It will copy all
95 // current global property values as needed
Kate Stoneb9c1b512016-09-06 20:57:50 +000096 ProcessOptionValueProperties(ProcessProperties *global_properties)
97 : OptionValueProperties(*global_properties->GetValueProperties()) {}
98
99 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
100 bool will_modify,
101 uint32_t idx) const override {
Adrian Prantl05097242018-04-30 16:49:04 +0000102 // When getting the value for a key from the process options, we will
103 // always try and grab the setting from the current process if there is
104 // one. Else we just use the one from this instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105 if (exe_ctx) {
106 Process *process = exe_ctx->GetProcessPtr();
107 if (process) {
108 ProcessOptionValueProperties *instance_properties =
109 static_cast<ProcessOptionValueProperties *>(
110 process->GetValueProperties().get());
111 if (this != instance_properties)
112 return instance_properties->ProtectedGetPropertyAtIndex(idx);
113 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000114 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115 return ProtectedGetPropertyAtIndex(idx);
116 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000117};
118
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119static PropertyDefinition g_properties[] = {
120 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
121 DISABLE_MEM_CACHE_DEFAULT, nullptr, nullptr,
122 "Disable reading and caching of memory in fixed-size units."},
123 {"extra-startup-command", OptionValue::eTypeArray, false,
124 OptionValue::eTypeString, nullptr, nullptr,
125 "A list containing extra commands understood by the particular process "
126 "plugin used. "
127 "For instance, to turn on debugserver logging set this to "
128 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
129 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
130 nullptr, nullptr,
131 "If true, breakpoints will be ignored during expression evaluation."},
132 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
133 nullptr, nullptr, "If true, errors in expression evaluation will unwind "
134 "the stack back to the state before the call."},
135 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
136 nullptr, "A path to a python OS plug-in module file that contains a "
137 "OperatingSystemPlugIn class."},
138 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
139 nullptr, nullptr,
140 "If true, stop when a shared library is loaded or unloaded."},
141 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
142 nullptr, "If true, detach will attempt to keep the process stopped."},
143 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
144 nullptr, "The memory cache line size"},
145 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
146 nullptr, "If true, warn when stopped in code that is optimized where "
147 "stepping and variable availability may not behave as expected."},
Jim Inghamba205c12017-12-05 02:50:45 +0000148 {"stop-on-exec", OptionValue::eTypeBoolean, true, true,
149 nullptr, nullptr,
150 "If true, stop when a shared library is loaded or unloaded."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000152
153enum {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154 ePropertyDisableMemCache,
155 ePropertyExtraStartCommand,
156 ePropertyIgnoreBreakpointsInExpressions,
157 ePropertyUnwindOnErrorInExpressions,
158 ePropertyPythonOSPluginPath,
159 ePropertyStopOnSharedLibraryEvents,
160 ePropertyDetachKeepsStopped,
161 ePropertyMemCacheLineSize,
Jim Inghamba205c12017-12-05 02:50:45 +0000162 ePropertyWarningOptimization,
163 ePropertyStopOnExec
Greg Clayton67cc0632012-08-22 17:17:09 +0000164};
165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166ProcessProperties::ProcessProperties(lldb_private::Process *process)
167 : Properties(),
168 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000169{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170 if (process == nullptr) {
171 // Global process properties, set them up one time
172 m_collection_sp.reset(
173 new ProcessOptionValueProperties(ConstString("process")));
174 m_collection_sp->Initialize(g_properties);
175 m_collection_sp->AppendProperty(
176 ConstString("thread"), ConstString("Settings specific to threads."),
177 true, Thread::GetGlobalProperties()->GetValueProperties());
178 } else {
179 m_collection_sp.reset(
180 new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
181 m_collection_sp->SetValueChangedCallback(
182 ePropertyPythonOSPluginPath,
183 ProcessProperties::OptionValueChangedCallback, this);
184 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000185}
186
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000187ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000188
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189void ProcessProperties::OptionValueChangedCallback(void *baton,
190 OptionValue *option_value) {
191 ProcessProperties *properties = (ProcessProperties *)baton;
192 if (properties->m_process)
193 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000194}
195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196bool ProcessProperties::GetDisableMemoryCache() const {
197 const uint32_t idx = ePropertyDisableMemCache;
198 return m_collection_sp->GetPropertyAtIndexAsBoolean(
199 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000200}
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
203 const uint32_t idx = ePropertyMemCacheLineSize;
204 return m_collection_sp->GetPropertyAtIndexAsUInt64(
205 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000206}
207
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208Args ProcessProperties::GetExtraStartupCommands() const {
209 Args args;
210 const uint32_t idx = ePropertyExtraStartCommand;
211 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
212 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000213}
214
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215void ProcessProperties::SetExtraStartupCommands(const Args &args) {
216 const uint32_t idx = ePropertyExtraStartCommand;
217 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000218}
219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220FileSpec ProcessProperties::GetPythonOSPluginPath() const {
221 const uint32_t idx = ePropertyPythonOSPluginPath;
222 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000223}
224
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
226 const uint32_t idx = ePropertyPythonOSPluginPath;
227 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000228}
229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
231 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
232 return m_collection_sp->GetPropertyAtIndexAsBoolean(
233 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000234}
235
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
237 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
238 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000239}
240
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
242 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
243 return m_collection_sp->GetPropertyAtIndexAsBoolean(
244 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000245}
246
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
248 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
249 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000250}
251
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
253 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
254 return m_collection_sp->GetPropertyAtIndexAsBoolean(
255 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000256}
257
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
259 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
260 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
261}
262
263bool ProcessProperties::GetDetachKeepsStopped() const {
264 const uint32_t idx = ePropertyDetachKeepsStopped;
265 return m_collection_sp->GetPropertyAtIndexAsBoolean(
266 nullptr, idx, g_properties[idx].default_uint_value != 0);
267}
268
269void ProcessProperties::SetDetachKeepsStopped(bool stop) {
270 const uint32_t idx = ePropertyDetachKeepsStopped;
271 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
272}
273
274bool ProcessProperties::GetWarningsOptimization() const {
275 const uint32_t idx = ePropertyWarningOptimization;
276 return m_collection_sp->GetPropertyAtIndexAsBoolean(
277 nullptr, idx, g_properties[idx].default_uint_value != 0);
278}
279
Jim Inghamba205c12017-12-05 02:50:45 +0000280bool ProcessProperties::GetStopOnExec() const {
281 const uint32_t idx = ePropertyStopOnExec;
282 return m_collection_sp->GetPropertyAtIndexAsBoolean(
283 nullptr, idx, g_properties[idx].default_uint_value != 0);
284}
285
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const {
287 const char *cstr;
288 if (m_pid != LLDB_INVALID_PROCESS_ID)
289 s.Printf(" pid = %" PRIu64 "\n", m_pid);
290
291 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
292 s.Printf(" parent = %" PRIu64 "\n", m_parent_pid);
293
294 if (m_executable) {
295 s.Printf(" name = %s\n", m_executable.GetFilename().GetCString());
296 s.PutCString(" file = ");
297 m_executable.Dump(&s);
298 s.EOL();
299 }
300 const uint32_t argc = m_arguments.GetArgumentCount();
301 if (argc > 0) {
302 for (uint32_t i = 0; i < argc; i++) {
303 const char *arg = m_arguments.GetArgumentAtIndex(i);
304 if (i < 10)
305 s.Printf(" arg[%u] = %s\n", i, arg);
306 else
307 s.Printf("arg[%u] = %s\n", i, arg);
308 }
309 }
310
Pavel Labath62930e52018-01-10 11:57:31 +0000311 s.Format("{0}", m_environment);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312
313 if (m_arch.IsValid()) {
314 s.Printf(" arch = ");
315 m_arch.DumpTriple(s);
316 s.EOL();
317 }
318
319 if (m_uid != UINT32_MAX) {
320 cstr = platform->GetUserName(m_uid);
321 s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
322 }
323 if (m_gid != UINT32_MAX) {
324 cstr = platform->GetGroupName(m_gid);
325 s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
326 }
327 if (m_euid != UINT32_MAX) {
328 cstr = platform->GetUserName(m_euid);
329 s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
330 }
331 if (m_egid != UINT32_MAX) {
332 cstr = platform->GetGroupName(m_egid);
333 s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
334 }
335}
336
337void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform,
338 bool show_args, bool verbose) {
339 const char *label;
340 if (show_args || verbose)
341 label = "ARGUMENTS";
342 else
343 label = "NAME";
344
345 if (verbose) {
346 s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE "
347 " %s\n",
348 label);
349 s.PutCString("====== ====== ========== ========== ========== ========== "
350 "======================== ============================\n");
351 } else {
352 s.Printf("PID PARENT USER TRIPLE %s\n", label);
353 s.PutCString("====== ====== ========== ======================== "
354 "============================\n");
355 }
356}
357
358void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform,
359 bool show_args, bool verbose) const {
360 if (m_pid != LLDB_INVALID_PROCESS_ID) {
Greg Clayton32e0a752011-03-30 18:16:51 +0000361 const char *cstr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000363
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 StreamString arch_strm;
Todd Fiala7df337f2015-10-13 23:41:19 +0000365 if (m_arch.IsValid())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 m_arch.DumpTriple(arch_strm);
367
368 if (verbose) {
369 cstr = platform->GetUserName(m_uid);
370 if (cstr &&
371 cstr[0]) // Watch for empty string that indicates lookup failed
372 s.Printf("%-10s ", cstr);
373 else
374 s.Printf("%-10u ", m_uid);
375
376 cstr = platform->GetGroupName(m_gid);
377 if (cstr &&
378 cstr[0]) // Watch for empty string that indicates lookup failed
379 s.Printf("%-10s ", cstr);
380 else
381 s.Printf("%-10u ", m_gid);
382
383 cstr = platform->GetUserName(m_euid);
384 if (cstr &&
385 cstr[0]) // Watch for empty string that indicates lookup failed
386 s.Printf("%-10s ", cstr);
387 else
388 s.Printf("%-10u ", m_euid);
389
390 cstr = platform->GetGroupName(m_egid);
391 if (cstr &&
392 cstr[0]) // Watch for empty string that indicates lookup failed
393 s.Printf("%-10s ", cstr);
394 else
395 s.Printf("%-10u ", m_egid);
396
Zachary Turnerc1564272016-11-16 21:15:24 +0000397 s.Printf("%-24s ", arch_strm.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 } else {
399 s.Printf("%-10s %-24s ", platform->GetUserName(m_euid),
Zachary Turnerc1564272016-11-16 21:15:24 +0000400 arch_strm.GetData());
Todd Fiala7df337f2015-10-13 23:41:19 +0000401 }
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000402
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 if (verbose || show_args) {
404 const uint32_t argc = m_arguments.GetArgumentCount();
405 if (argc > 0) {
406 for (uint32_t i = 0; i < argc; i++) {
407 if (i > 0)
408 s.PutChar(' ');
409 s.PutCString(m_arguments.GetArgumentAtIndex(i));
410 }
411 }
412 } else {
413 s.PutCString(GetName());
Greg Clayton32e0a752011-03-30 18:16:51 +0000414 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415
416 s.EOL();
417 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000418}
419
Zachary Turner97206d52017-05-12 04:51:55 +0000420Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000421 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000423 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424 const int short_option = m_getopt_table[option_idx].val;
425
426 switch (short_option) {
427 case 's': // Stop at program entry point
428 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
429 break;
430
431 case 'i': // STDIN for read only
432 {
433 FileAction action;
434 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
435 launch_info.AppendFileAction(action);
436 break;
437 }
438
439 case 'o': // Open STDOUT for write only
440 {
441 FileAction action;
442 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
443 launch_info.AppendFileAction(action);
444 break;
445 }
446
447 case 'e': // STDERR for write only
448 {
449 FileAction action;
450 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
451 launch_info.AppendFileAction(action);
452 break;
453 }
454
455 case 'p': // Process plug-in name
456 launch_info.SetProcessPluginName(option_arg);
457 break;
458
459 case 'n': // Disable STDIO
460 {
461 FileAction action;
462 const FileSpec dev_null{FileSystem::DEV_NULL, false};
463 if (action.Open(STDIN_FILENO, dev_null, true, false))
464 launch_info.AppendFileAction(action);
465 if (action.Open(STDOUT_FILENO, dev_null, false, true))
466 launch_info.AppendFileAction(action);
467 if (action.Open(STDERR_FILENO, dev_null, false, true))
468 launch_info.AppendFileAction(action);
469 break;
470 }
471
472 case 'w':
473 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
474 break;
475
476 case 't': // Open process in new terminal window
477 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
478 break;
479
480 case 'a': {
481 TargetSP target_sp =
482 execution_context ? execution_context->GetTargetSP() : TargetSP();
483 PlatformSP platform_sp =
484 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000485 launch_info.GetArchitecture() =
486 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487 } break;
488
489 case 'A': // Disable ASLR.
490 {
491 bool success;
492 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000493 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 if (success)
495 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000496 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 error.SetErrorStringWithFormat(
498 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000499 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500 break;
501 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000502
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 case 'X': // shell expand args.
504 {
505 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000506 const bool expand_args =
507 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 if (success)
509 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000510 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511 error.SetErrorStringWithFormat(
512 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000513 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514 break;
515 }
516
517 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000518 if (!option_arg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 launch_info.SetShell(FileSpec(option_arg, false));
520 else
521 launch_info.SetShell(HostInfo::GetDefaultShell());
522 break;
523
524 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000525 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 break;
527
528 default:
529 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
530 short_option);
531 break;
532 }
533 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000534}
535
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000536static OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
538 nullptr, nullptr, 0, eArgTypeNone,
539 "Stop at the entry point of the program when launching a process."},
540 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
541 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
542 "Set whether to disable address space layout randomization when launching "
543 "a process."},
544 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
545 nullptr, nullptr, 0, eArgTypePlugin,
546 "Name of the process plugin you want to use."},
547 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
548 OptionParser::eRequiredArgument, nullptr, nullptr, 0,
549 eArgTypeDirectoryName,
550 "Set the current working directory to <path> when running the inferior."},
551 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
552 nullptr, nullptr, 0, eArgTypeArchitecture,
553 "Set the architecture for the process to launch when ambiguous."},
554 {LLDB_OPT_SET_ALL, false, "environment", 'v',
555 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone,
556 "Specify an environment variable name/value string (--environment "
557 "NAME=VALUE). Can be specified multiple times for subsequent environment "
558 "entries."},
559 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
560 OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeFilename,
561 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000562
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
564 nullptr, nullptr, 0, eArgTypeFilename,
565 "Redirect stdin for the process to <filename>."},
566 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
567 nullptr, nullptr, 0, eArgTypeFilename,
568 "Redirect stdout for the process to <filename>."},
569 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
570 nullptr, nullptr, 0, eArgTypeFilename,
571 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000572
Kate Stoneb9c1b512016-09-06 20:57:50 +0000573 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
574 nullptr, 0, eArgTypeNone,
575 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000576
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
578 nullptr, 0, eArgTypeNone,
579 "Do not set up for terminal I/O to go to running process."},
580 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
581 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
582 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000583};
584
585llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000586 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000587}
Greg Clayton32e0a752011-03-30 18:16:51 +0000588
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
Pavel Labathc4a33952017-02-20 11:35:33 +0000590 if (m_name_match_type == NameMatch::Ignore || process_name == nullptr)
Greg Clayton32e0a752011-03-30 18:16:51 +0000591 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592 const char *match_name = m_match_info.GetName();
593 if (!match_name)
Greg Clayton32e0a752011-03-30 18:16:51 +0000594 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595
596 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
Greg Clayton32e0a752011-03-30 18:16:51 +0000597}
598
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599bool ProcessInstanceInfoMatch::Matches(
600 const ProcessInstanceInfo &proc_info) const {
601 if (!NameMatches(proc_info.GetName()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603
604 if (m_match_info.ProcessIDIsValid() &&
605 m_match_info.GetProcessID() != proc_info.GetProcessID())
606 return false;
607
608 if (m_match_info.ParentProcessIDIsValid() &&
609 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
610 return false;
611
612 if (m_match_info.UserIDIsValid() &&
613 m_match_info.GetUserID() != proc_info.GetUserID())
614 return false;
615
616 if (m_match_info.GroupIDIsValid() &&
617 m_match_info.GetGroupID() != proc_info.GetGroupID())
618 return false;
619
620 if (m_match_info.EffectiveUserIDIsValid() &&
621 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
622 return false;
623
624 if (m_match_info.EffectiveGroupIDIsValid() &&
625 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
626 return false;
627
628 if (m_match_info.GetArchitecture().IsValid() &&
629 !m_match_info.GetArchitecture().IsCompatibleMatch(
630 proc_info.GetArchitecture()))
631 return false;
632 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000633}
634
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
Pavel Labathc4a33952017-02-20 11:35:33 +0000636 if (m_name_match_type != NameMatch::Ignore)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637 return false;
638
639 if (m_match_info.ProcessIDIsValid())
640 return false;
641
642 if (m_match_info.ParentProcessIDIsValid())
643 return false;
644
645 if (m_match_info.UserIDIsValid())
646 return false;
647
648 if (m_match_info.GroupIDIsValid())
649 return false;
650
651 if (m_match_info.EffectiveUserIDIsValid())
652 return false;
653
654 if (m_match_info.EffectiveGroupIDIsValid())
655 return false;
656
657 if (m_match_info.GetArchitecture().IsValid())
658 return false;
659
660 if (m_match_all_users)
661 return false;
662
663 return true;
664}
665
666void ProcessInstanceInfoMatch::Clear() {
667 m_match_info.Clear();
Pavel Labathc4a33952017-02-20 11:35:33 +0000668 m_name_match_type = NameMatch::Ignore;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669 m_match_all_users = false;
670}
671
Zachary Turner31659452016-11-17 21:15:14 +0000672ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
673 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 ListenerSP listener_sp,
675 const FileSpec *crash_file_path) {
676 static uint32_t g_process_unique_id = 0;
677
678 ProcessSP process_sp;
679 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000680 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000681 ConstString const_plugin_name(plugin_name);
682 create_callback =
683 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
684 if (create_callback) {
685 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
686 if (process_sp) {
687 if (process_sp->CanDebug(target_sp, true)) {
688 process_sp->m_process_unique_id = ++g_process_unique_id;
689 } else
690 process_sp.reset();
691 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000692 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 } else {
694 for (uint32_t idx = 0;
695 (create_callback =
696 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
697 ++idx) {
698 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
699 if (process_sp) {
700 if (process_sp->CanDebug(target_sp, false)) {
701 process_sp->m_process_unique_id = ++g_process_unique_id;
702 break;
703 } else
704 process_sp.reset();
705 }
706 }
707 }
708 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000709}
710
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711ConstString &Process::GetStaticBroadcasterClass() {
712 static ConstString class_name("lldb.process");
713 return class_name;
714}
715
716Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
717 : Process(target_sp, listener_sp,
718 UnixSignals::Create(HostInfo::GetArchitecture())) {
719 // This constructor just delegates to the full Process constructor,
720 // defaulting to using the Host's UnixSignals.
721}
722
723Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
724 const UnixSignalsSP &unix_signals_sp)
725 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
726 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
727 Process::GetStaticBroadcasterClass().AsCString()),
728 m_target_sp(target_sp), m_public_state(eStateUnloaded),
729 m_private_state(eStateUnloaded),
730 m_private_state_broadcaster(nullptr,
731 "lldb.process.internal_state_broadcaster"),
732 m_private_state_control_broadcaster(
733 nullptr, "lldb.process.internal_state_control_broadcaster"),
734 m_private_state_listener_sp(
735 Listener::MakeListener("lldb.process.internal_state_listener")),
736 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
737 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
738 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
739 m_thread_list(this), m_extended_thread_list(this),
740 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
741 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
742 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
743 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
744 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
745 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
746 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
747 m_memory_cache(*this), m_allocated_memory_cache(*this),
748 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000749 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
751 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
752 m_can_interpret_function_calls(false), m_warnings_issued(),
753 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
754 CheckInWithManager();
755
756 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
757 if (log)
758 log->Printf("%p Process::Process()", static_cast<void *>(this));
759
760 if (!m_unix_signals_sp)
761 m_unix_signals_sp = std::make_shared<UnixSignals>();
762
763 SetEventName(eBroadcastBitStateChanged, "state-changed");
764 SetEventName(eBroadcastBitInterrupt, "interrupt");
765 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
766 SetEventName(eBroadcastBitSTDERR, "stderr-available");
767 SetEventName(eBroadcastBitProfileData, "profile-data-available");
768 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
769
770 m_private_state_control_broadcaster.SetEventName(
771 eBroadcastInternalStateControlStop, "control-stop");
772 m_private_state_control_broadcaster.SetEventName(
773 eBroadcastInternalStateControlPause, "control-pause");
774 m_private_state_control_broadcaster.SetEventName(
775 eBroadcastInternalStateControlResume, "control-resume");
776
777 m_listener_sp->StartListeningForEvents(
778 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
779 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
780 eBroadcastBitProfileData | eBroadcastBitStructuredData);
781
782 m_private_state_listener_sp->StartListeningForEvents(
783 &m_private_state_broadcaster,
784 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
785
786 m_private_state_listener_sp->StartListeningForEvents(
787 &m_private_state_control_broadcaster,
788 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
789 eBroadcastInternalStateControlResume);
790 // We need something valid here, even if just the default UnixSignalsSP.
791 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
792
793 // Allow the platform to override the default cache line size
794 OptionValueSP value_sp =
795 m_collection_sp
796 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
797 ->GetValue();
798 uint32_t platform_cache_line_size =
799 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
800 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
801 value_sp->SetUInt64Value(platform_cache_line_size);
802}
803
804Process::~Process() {
805 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
806 if (log)
807 log->Printf("%p Process::~Process()", static_cast<void *>(this));
808 StopPrivateStateThread();
809
810 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000811 // explicitly clear the thread list here to ensure that the mutex is not
812 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 m_thread_list.Clear();
814}
815
816const ProcessPropertiesSP &Process::GetGlobalProperties() {
817 // NOTE: intentional leak so we don't crash if global destructor chain gets
818 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000819 static ProcessPropertiesSP *g_settings_sp_ptr =
820 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 return *g_settings_sp_ptr;
822}
823
824void Process::Finalize() {
825 m_finalizing = true;
826
827 // Destroy this process if needed
828 switch (GetPrivateState()) {
829 case eStateConnected:
830 case eStateAttaching:
831 case eStateLaunching:
832 case eStateStopped:
833 case eStateRunning:
834 case eStateStepping:
835 case eStateCrashed:
836 case eStateSuspended:
837 Destroy(false);
838 break;
839
840 case eStateInvalid:
841 case eStateUnloaded:
842 case eStateDetached:
843 case eStateExited:
844 break;
845 }
846
847 // Clear our broadcaster before we proceed with destroying
848 Broadcaster::Clear();
849
Adrian Prantl05097242018-04-30 16:49:04 +0000850 // Do any cleanup needed prior to being destructed... Subclasses that
851 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852
853 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000854 // destroyed since it is very likely that undoing the loader will require
855 // access to the real process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000856 m_dynamic_checkers_ap.reset();
857 m_abi_sp.reset();
858 m_os_ap.reset();
859 m_system_runtime_ap.reset();
860 m_dyld_ap.reset();
861 m_jit_loaders_ap.reset();
862 m_thread_list_real.Destroy();
863 m_thread_list.Destroy();
864 m_extended_thread_list.Destroy();
865 m_queue_list.Clear();
866 m_queue_list_stop_id = 0;
867 std::vector<Notifications> empty_notifications;
868 m_notifications.swap(empty_notifications);
869 m_image_tokens.clear();
870 m_memory_cache.Clear();
871 m_allocated_memory_cache.Clear();
872 m_language_runtimes.clear();
873 m_instrumentation_runtimes.clear();
874 m_next_event_action_ap.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000875 // Clear the last natural stop ID since it has a strong reference to this
876 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
878 //#ifdef LLDB_CONFIGURATION_DEBUG
879 // StreamFile s(stdout, false);
880 // EventSP event_sp;
881 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
882 // {
883 // event_sp->Dump (&s);
884 // s.EOL();
885 // }
886 //#endif
887 // We have to be very careful here as the m_private_state_listener might
888 // contain events that have ProcessSP values in them which can keep this
889 // process around forever. These events need to be cleared out.
890 m_private_state_listener_sp->Clear();
891 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
892 m_public_run_lock.SetStopped();
893 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
894 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000895 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 m_finalize_called = true;
897}
898
899void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
900 m_notifications.push_back(callbacks);
901 if (callbacks.initialize != nullptr)
902 callbacks.initialize(callbacks.baton, this);
903}
904
905bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
906 std::vector<Notifications>::iterator pos, end = m_notifications.end();
907 for (pos = m_notifications.begin(); pos != end; ++pos) {
908 if (pos->baton == callbacks.baton &&
909 pos->initialize == callbacks.initialize &&
910 pos->process_state_changed == callbacks.process_state_changed) {
911 m_notifications.erase(pos);
912 return true;
913 }
914 }
915 return false;
916}
917
918void Process::SynchronouslyNotifyStateChanged(StateType state) {
919 std::vector<Notifications>::iterator notification_pos,
920 notification_end = m_notifications.end();
921 for (notification_pos = m_notifications.begin();
922 notification_pos != notification_end; ++notification_pos) {
923 if (notification_pos->process_state_changed)
924 notification_pos->process_state_changed(notification_pos->baton, this,
925 state);
926 }
927}
928
929// FIXME: We need to do some work on events before the general Listener sees
930// them.
931// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000932// we do the little "insert real insn, step & stop" trick. But we can't do
933// that when the event is delivered by the broadcaster - since that is done on
934// the thread that is waiting for new events, so if we needed more than one
935// event for our handling, we would stall. So instead we do it when we fetch
936// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000937//
938
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939StateType Process::GetNextEvent(EventSP &event_sp) {
940 StateType state = eStateInvalid;
941
Pavel Labathd35031e12016-11-30 10:41:42 +0000942 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
943 std::chrono::seconds(0)) &&
944 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
946
947 return state;
948}
949
Pavel Labath3879fe02018-05-09 14:29:30 +0000950void Process::SyncIOHandler(uint32_t iohandler_id,
951 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 // don't sync (potentially context switch) in case where there is no process
953 // IO
954 if (!m_process_input_reader)
955 return;
956
Pavel Labath3879fe02018-05-09 14:29:30 +0000957 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958
959 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000960 if (Result) {
961 LLDB_LOG(
962 log,
963 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
964 iohandler_id, *Result);
965 } else {
966 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
967 iohandler_id);
968 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969}
970
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000971StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
972 EventSP *event_sp_ptr, bool wait_always,
973 ListenerSP hijack_listener_sp,
974 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000976 // have restarted the target. We have to actually check each event, and in
977 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 if (event_sp_ptr)
979 event_sp_ptr->reset();
980 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000981 // If we are exited or detached, we won't ever get back to any other valid
982 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000985
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000987 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000988
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 if (!wait_always && StateIsStoppedState(state, true) &&
990 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000991 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992 log->Printf("Process::%s returning without waiting for events; process "
993 "private and public states are already 'stopped'.",
994 __FUNCTION__);
995 // We need to toggle the run lock as this won't get done in
996 // SetPublicState() if the process is hijacked.
997 if (hijack_listener_sp && use_run_lock)
998 m_public_run_lock.SetStopped();
999 return state;
1000 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002 while (state != eStateInvalid) {
1003 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001004 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005 if (event_sp_ptr && event_sp)
1006 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001007
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1009 Process::HandleProcessStateChangedEvent(event_sp, stream,
1010 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +00001011
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 switch (state) {
1013 case eStateCrashed:
1014 case eStateDetached:
1015 case eStateExited:
1016 case eStateUnloaded:
1017 // We need to toggle the run lock as this won't get done in
1018 // SetPublicState() if the process is hijacked.
1019 if (hijack_listener_sp && use_run_lock)
1020 m_public_run_lock.SetStopped();
1021 return state;
1022 case eStateStopped:
1023 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1024 continue;
1025 else {
Pavel Labath78521ef2015-03-06 10:52:47 +00001026 // We need to toggle the run lock as this won't get done in
1027 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001028 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001029 m_public_run_lock.SetStopped();
1030 return state;
1031 }
1032 default:
1033 continue;
1034 }
1035 }
1036 return state;
1037}
1038
1039bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1040 Stream *stream,
1041 bool &pop_process_io_handler) {
1042 const bool handle_pop = pop_process_io_handler;
1043
1044 pop_process_io_handler = false;
1045 ProcessSP process_sp =
1046 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1047
1048 if (!process_sp)
1049 return false;
1050
1051 StateType event_state =
1052 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1053 if (event_state == eStateInvalid)
1054 return false;
1055
1056 switch (event_state) {
1057 case eStateInvalid:
1058 case eStateUnloaded:
1059 case eStateAttaching:
1060 case eStateLaunching:
1061 case eStateStepping:
1062 case eStateDetached:
1063 if (stream)
1064 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1065 StateAsCString(event_state));
1066 if (event_state == eStateDetached)
1067 pop_process_io_handler = true;
1068 break;
1069
1070 case eStateConnected:
1071 case eStateRunning:
1072 // Don't be chatty when we run...
1073 break;
1074
1075 case eStateExited:
1076 if (stream)
1077 process_sp->GetStatus(*stream);
1078 pop_process_io_handler = true;
1079 break;
1080
1081 case eStateStopped:
1082 case eStateCrashed:
1083 case eStateSuspended:
1084 // Make sure the program hasn't been auto-restarted:
1085 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1086 if (stream) {
1087 size_t num_reasons =
1088 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1089 if (num_reasons > 0) {
1090 // FIXME: Do we want to report this, or would that just be annoyingly
1091 // chatty?
1092 if (num_reasons == 1) {
1093 const char *reason =
1094 Process::ProcessEventData::GetRestartedReasonAtIndex(
1095 event_sp.get(), 0);
1096 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1097 process_sp->GetID(),
1098 reason ? reason : "<UNKNOWN REASON>");
1099 } else {
1100 stream->Printf("Process %" PRIu64
1101 " stopped and restarted, reasons:\n",
1102 process_sp->GetID());
1103
1104 for (size_t i = 0; i < num_reasons; i++) {
1105 const char *reason =
1106 Process::ProcessEventData::GetRestartedReasonAtIndex(
1107 event_sp.get(), i);
1108 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1109 }
1110 }
1111 }
1112 }
1113 } else {
1114 StopInfoSP curr_thread_stop_info_sp;
1115 // Lock the thread list so it doesn't change on us, this is the scope for
1116 // the locker:
1117 {
1118 ThreadList &thread_list = process_sp->GetThreadList();
1119 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1120
1121 ThreadSP curr_thread(thread_list.GetSelectedThread());
1122 ThreadSP thread;
1123 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1124 if (curr_thread) {
1125 curr_thread_stop_reason = curr_thread->GetStopReason();
1126 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1127 }
1128 if (!curr_thread || !curr_thread->IsValid() ||
1129 curr_thread_stop_reason == eStopReasonInvalid ||
1130 curr_thread_stop_reason == eStopReasonNone) {
1131 // Prefer a thread that has just completed its plan over another
1132 // thread as current thread.
1133 ThreadSP plan_thread;
1134 ThreadSP other_thread;
1135
1136 const size_t num_threads = thread_list.GetSize();
1137 size_t i;
1138 for (i = 0; i < num_threads; ++i) {
1139 thread = thread_list.GetThreadAtIndex(i);
1140 StopReason thread_stop_reason = thread->GetStopReason();
1141 switch (thread_stop_reason) {
1142 case eStopReasonInvalid:
1143 case eStopReasonNone:
1144 break;
1145
1146 case eStopReasonSignal: {
1147 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +00001148 // that signal. We have to have had another reason for stopping
1149 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001150 uint64_t signo = thread->GetStopInfo()->GetValue();
1151 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1152 if (!other_thread)
1153 other_thread = thread;
1154 }
1155 break;
1156 }
1157 case eStopReasonTrace:
1158 case eStopReasonBreakpoint:
1159 case eStopReasonWatchpoint:
1160 case eStopReasonException:
1161 case eStopReasonExec:
1162 case eStopReasonThreadExiting:
1163 case eStopReasonInstrumentation:
1164 if (!other_thread)
1165 other_thread = thread;
1166 break;
1167 case eStopReasonPlanComplete:
1168 if (!plan_thread)
1169 plan_thread = thread;
1170 break;
1171 }
1172 }
1173 if (plan_thread)
1174 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1175 else if (other_thread)
1176 thread_list.SetSelectedThreadByID(other_thread->GetID());
1177 else {
1178 if (curr_thread && curr_thread->IsValid())
1179 thread = curr_thread;
1180 else
1181 thread = thread_list.GetThreadAtIndex(0);
1182
1183 if (thread)
1184 thread_list.SetSelectedThreadByID(thread->GetID());
1185 }
1186 }
1187 }
1188 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +00001189 // have to run code, e.g. for Data formatters, and if we hold the
1190 // ThreadList mutex, then the process is going to have a hard time
1191 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192 if (stream) {
1193 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1194 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1195 &process_sp->GetTarget()) {
1196 const bool only_threads_with_stop_reason = true;
1197 const uint32_t start_frame = 0;
1198 const uint32_t num_frames = 1;
1199 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001200 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 process_sp->GetStatus(*stream);
1202 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1203 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001204 num_frames_with_source,
1205 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 if (curr_thread_stop_info_sp) {
1207 lldb::addr_t crashing_address;
1208 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1209 curr_thread_stop_info_sp, &crashing_address);
1210 if (valobj_sp) {
1211 const bool qualify_cxx_base_classes = false;
1212
1213 const ValueObject::GetExpressionPathFormat format =
1214 ValueObject::GetExpressionPathFormat::
1215 eGetExpressionPathFormatHonorPointers;
1216 stream->PutCString("Likely cause: ");
1217 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1218 format);
1219 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1220 }
1221 }
1222 } else {
1223 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1224 process_sp->GetTarget().shared_from_this());
1225 if (target_idx != UINT32_MAX)
1226 stream->Printf("Target %d: (", target_idx);
1227 else
1228 stream->Printf("Target <unknown index>: (");
1229 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1230 stream->Printf(") stopped.\n");
1231 }
1232 }
1233
1234 // Pop the process IO handler
1235 pop_process_io_handler = true;
1236 }
1237 break;
1238 }
1239
1240 if (handle_pop && pop_process_io_handler)
1241 process_sp->PopProcessIOHandler();
1242
1243 return true;
1244}
1245
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1247 if (listener_sp) {
1248 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1249 eBroadcastBitInterrupt);
1250 } else
1251 return false;
1252}
Greg Claytondc6224e2014-10-21 01:00:42 +00001253
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001255
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001256StateType Process::GetStateChangedEvents(EventSP &event_sp,
1257 const Timeout<std::micro> &timeout,
1258 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001259 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001260 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001261
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 ListenerSP listener_sp = hijack_listener_sp;
1263 if (!listener_sp)
1264 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001265
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001267 if (listener_sp->GetEventForBroadcasterWithType(
1268 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001269 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1271 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001272 else
1273 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001275
Pavel Labathd02b1c82017-02-10 11:49:33 +00001276 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001277 return state;
1278}
Greg Claytondc6224e2014-10-21 01:00:42 +00001279
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280Event *Process::PeekAtStateChangedEvents() {
1281 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001282
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283 if (log)
1284 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001285
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286 Event *event_ptr;
1287 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1288 this, eBroadcastBitStateChanged);
1289 if (log) {
1290 if (event_ptr) {
1291 log->Printf(
1292 "Process::%s (event_ptr) => %s", __FUNCTION__,
1293 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1294 } else {
1295 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001296 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001297 }
1298 return event_ptr;
1299}
Greg Claytondc6224e2014-10-21 01:00:42 +00001300
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001301StateType
1302Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1303 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001305 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001306
1307 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001308 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1309 &m_private_state_broadcaster,
1310 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001311 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1313 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1314
Pavel Labathd02b1c82017-02-10 11:49:33 +00001315 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1316 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 return state;
1318}
1319
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001320bool Process::GetEventsPrivate(EventSP &event_sp,
1321 const Timeout<std::micro> &timeout,
1322 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001323 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001324 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001325
1326 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001327 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001328 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001329 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001330 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331}
1332
1333bool Process::IsRunning() const {
1334 return StateIsRunningState(m_public_state.GetValue());
1335}
1336
1337int Process::GetExitStatus() {
1338 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1339
1340 if (m_public_state.GetValue() == eStateExited)
1341 return m_exit_status;
1342 return -1;
1343}
1344
1345const char *Process::GetExitDescription() {
1346 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1347
1348 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1349 return m_exit_string.c_str();
1350 return nullptr;
1351}
1352
1353bool Process::SetExitStatus(int status, const char *cstr) {
1354 // Use a mutex to protect setting the exit status.
1355 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1356
1357 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1358 LIBLLDB_LOG_PROCESS));
1359 if (log)
1360 log->Printf(
1361 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1362 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1363 cstr ? "\"" : "");
1364
1365 // We were already in the exited state
1366 if (m_private_state.GetValue() == eStateExited) {
1367 if (log)
1368 log->Printf("Process::SetExitStatus () ignoring exit status because "
1369 "state was already set to eStateExited");
1370 return false;
1371 }
1372
1373 m_exit_status = status;
1374 if (cstr)
1375 m_exit_string = cstr;
1376 else
1377 m_exit_string.clear();
1378
Adrian Prantl05097242018-04-30 16:49:04 +00001379 // Clear the last natural stop ID since it has a strong reference to this
1380 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001381 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1382
1383 SetPrivateState(eStateExited);
1384
1385 // Allow subclasses to do some cleanup
1386 DidExit();
1387
1388 return true;
1389}
1390
1391bool Process::IsAlive() {
1392 switch (m_private_state.GetValue()) {
1393 case eStateConnected:
1394 case eStateAttaching:
1395 case eStateLaunching:
1396 case eStateStopped:
1397 case eStateRunning:
1398 case eStateStepping:
1399 case eStateCrashed:
1400 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001401 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001402 default:
1403 return false;
1404 }
Jason Molendaa814f702015-11-05 23:03:44 +00001405}
1406
Adrian Prantl05097242018-04-30 16:49:04 +00001407// This static callback can be used to watch for local child processes on the
1408// current host. The child process exits, the process will be found in the
1409// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001410// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001411bool Process::SetProcessExitStatus(
1412 lldb::pid_t pid, bool exited,
1413 int signo, // Zero for no signal
1414 int exit_status // Exit value of process if signal is zero
1415 ) {
1416 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1417 if (log)
1418 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1419 ", exited=%i, signal=%i, exit_status=%i)\n",
1420 pid, exited, signo, exit_status);
1421
1422 if (exited) {
1423 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1424 if (target_sp) {
1425 ProcessSP process_sp(target_sp->GetProcessSP());
1426 if (process_sp) {
1427 const char *signal_cstr = nullptr;
1428 if (signo)
1429 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1430
1431 process_sp->SetExitStatus(exit_status, signal_cstr);
1432 }
1433 }
1434 return true;
1435 }
1436 return false;
1437}
1438
1439void Process::UpdateThreadListIfNeeded() {
1440 const uint32_t stop_id = GetStopID();
1441 if (m_thread_list.GetSize(false) == 0 ||
1442 stop_id != m_thread_list.GetStopID()) {
1443 const StateType state = GetPrivateState();
1444 if (StateIsStoppedState(state, true)) {
1445 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Adrian Prantl05097242018-04-30 16:49:04 +00001446 // m_thread_list does have its own mutex, but we need to hold onto the
1447 // mutex between the call to UpdateThreadList(...) and the
1448 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 ThreadList &old_thread_list = m_thread_list;
1450 ThreadList real_thread_list(this);
1451 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001452 // Always update the thread list with the protocol specific thread list,
1453 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1455 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001456 // are shutting down, since that may call back into the SBAPI's,
1457 // requiring the API lock which is already held by whoever is shutting
1458 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001459 OperatingSystem *os = GetOperatingSystem();
1460 if (os && !m_destroy_in_process) {
1461 // Clear any old backing threads where memory threads might have been
1462 // backed by actual threads from the lldb_private::Process subclass
1463 size_t num_old_threads = old_thread_list.GetSize(false);
1464 for (size_t i = 0; i < num_old_threads; ++i)
1465 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1466
1467 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl05097242018-04-30 16:49:04 +00001468 // Objective C can run an expression to determine if a SBValue is a
1469 // dynamic type or not and we need to avoid this. OperatingSystem
1470 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001471
1472 Target &target = GetTarget();
1473 const lldb::DynamicValueType saved_prefer_dynamic =
1474 target.GetPreferDynamicValue();
1475 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1476 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1477
1478 // Now let the OperatingSystem plug-in update the thread list
1479
1480 os->UpdateThreadList(
1481 old_thread_list, // Old list full of threads created by OS plug-in
1482 real_thread_list, // The actual thread list full of threads
1483 // created by each lldb_private::Process
1484 // subclass
1485 new_thread_list); // The new thread list that we will show to the
1486 // user that gets filled in
1487
1488 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1489 target.SetPreferDynamicValue(saved_prefer_dynamic);
1490 } else {
1491 // No OS plug-in, the new thread list is the same as the real thread
1492 // list
1493 new_thread_list = real_thread_list;
1494 }
1495
1496 m_thread_list_real.Update(real_thread_list);
1497 m_thread_list.Update(new_thread_list);
1498 m_thread_list.SetStopID(stop_id);
1499
1500 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1501 // Clear any extended threads that we may have accumulated previously
1502 m_extended_thread_list.Clear();
1503 m_extended_thread_stop_id = GetLastNaturalStopID();
1504
1505 m_queue_list.Clear();
1506 m_queue_list_stop_id = GetLastNaturalStopID();
1507 }
1508 }
1509 }
1510 }
1511}
1512
1513void Process::UpdateQueueListIfNeeded() {
1514 if (m_system_runtime_ap) {
1515 if (m_queue_list.GetSize() == 0 ||
1516 m_queue_list_stop_id != GetLastNaturalStopID()) {
1517 const StateType state = GetPrivateState();
1518 if (StateIsStoppedState(state, true)) {
1519 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1520 m_queue_list_stop_id = GetLastNaturalStopID();
1521 }
1522 }
1523 }
1524}
1525
1526ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1527 OperatingSystem *os = GetOperatingSystem();
1528 if (os)
1529 return os->CreateThread(tid, context);
1530 return ThreadSP();
1531}
1532
1533uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1534 return AssignIndexIDToThread(thread_id);
1535}
1536
1537bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1538 return (m_thread_id_to_index_id_map.find(thread_id) !=
1539 m_thread_id_to_index_id_map.end());
1540}
1541
1542uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1543 uint32_t result = 0;
1544 std::map<uint64_t, uint32_t>::iterator iterator =
1545 m_thread_id_to_index_id_map.find(thread_id);
1546 if (iterator == m_thread_id_to_index_id_map.end()) {
1547 result = ++m_thread_index_id;
1548 m_thread_id_to_index_id_map[thread_id] = result;
1549 } else {
1550 result = iterator->second;
1551 }
1552
1553 return result;
1554}
1555
1556StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001557 return m_public_state.GetValue();
1558}
1559
1560bool Process::StateChangedIsExternallyHijacked() {
1561 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1562 const char *hijacking_name = GetHijackingListenerName();
1563 if (hijacking_name &&
1564 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1565 return true;
1566 }
1567 return false;
1568}
1569
1570void Process::SetPublicState(StateType new_state, bool restarted) {
1571 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1572 LIBLLDB_LOG_PROCESS));
1573 if (log)
1574 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1575 StateAsCString(new_state), restarted);
1576 const StateType old_state = m_public_state.GetValue();
1577 m_public_state.SetValue(new_state);
1578
Adrian Prantl05097242018-04-30 16:49:04 +00001579 // On the transition from Run to Stopped, we unlock the writer end of the run
1580 // lock. The lock gets locked in Resume, which is the public API to tell the
1581 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001582 if (!StateChangedIsExternallyHijacked()) {
1583 if (new_state == eStateDetached) {
1584 if (log)
1585 log->Printf(
1586 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1587 StateAsCString(new_state));
1588 m_public_run_lock.SetStopped();
1589 } else {
1590 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1591 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1592 if ((old_state_is_stopped != new_state_is_stopped)) {
1593 if (new_state_is_stopped && !restarted) {
1594 if (log)
1595 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1596 StateAsCString(new_state));
1597 m_public_run_lock.SetStopped();
1598 }
1599 }
1600 }
1601 }
1602}
1603
Zachary Turner97206d52017-05-12 04:51:55 +00001604Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001605 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1606 LIBLLDB_LOG_PROCESS));
1607 if (log)
1608 log->Printf("Process::Resume -- locking run lock");
1609 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001610 Status error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001611 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001612 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001613 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001614 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001615 Status error = PrivateResume();
1616 if (!error.Success()) {
1617 // Undo running state change
1618 m_public_run_lock.SetStopped();
1619 }
1620 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001621}
1622
Zachary Turner97206d52017-05-12 04:51:55 +00001623Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001624 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1625 LIBLLDB_LOG_PROCESS));
1626 if (log)
1627 log->Printf("Process::ResumeSynchronous -- locking run lock");
1628 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001629 Status error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001630 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001631 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1632 return error;
1633 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001634
Kate Stoneb9c1b512016-09-06 20:57:50 +00001635 ListenerSP listener_sp(
1636 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1637 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001638
Zachary Turner97206d52017-05-12 04:51:55 +00001639 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001640 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001641 StateType state =
1642 WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643 const bool must_be_alive =
1644 false; // eStateExited is ok, so this must be false
1645 if (!StateIsStoppedState(state, must_be_alive))
1646 error.SetErrorStringWithFormat(
1647 "process not in stopped state after synchronous resume: %s",
1648 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001649 } else {
1650 // Undo running state change
1651 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001652 }
Ed Mastec29693f2013-07-02 16:35:47 +00001653
Kate Stoneb9c1b512016-09-06 20:57:50 +00001654 // Undo the hijacking of process events...
1655 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001656
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657 return error;
1658}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001659
Kate Stoneb9c1b512016-09-06 20:57:50 +00001660StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001661
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662void Process::SetPrivateState(StateType new_state) {
1663 if (m_finalize_called)
1664 return;
1665
1666 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1667 LIBLLDB_LOG_PROCESS));
1668 bool state_changed = false;
1669
1670 if (log)
1671 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1672
1673 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1674 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1675
1676 const StateType old_state = m_private_state.GetValueNoLock();
1677 state_changed = old_state != new_state;
1678
1679 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1680 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1681 if (old_state_is_stopped != new_state_is_stopped) {
1682 if (new_state_is_stopped)
1683 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001684 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001685 m_private_run_lock.SetRunning();
1686 }
1687
1688 if (state_changed) {
1689 m_private_state.SetValueNoLock(new_state);
1690 EventSP event_sp(
1691 new Event(eBroadcastBitStateChanged,
1692 new ProcessEventData(shared_from_this(), new_state)));
1693 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001694 // Note, this currently assumes that all threads in the list stop when
1695 // the process stops. In the future we will want to support a debugging
1696 // model where some threads continue to run while others are stopped.
1697 // When that happens we will either need a way for the thread list to
1698 // identify which threads are stopping or create a special thread list
1699 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001700 //
Adrian Prantl05097242018-04-30 16:49:04 +00001701 // The process plugin is responsible for managing the actual behavior of
1702 // the threads and should have stopped any threads that are going to stop
1703 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001704 m_thread_list.DidStop();
1705
1706 m_mod_id.BumpStopID();
1707 if (!m_mod_id.IsLastResumeForUserExpression())
1708 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1709 m_memory_cache.Clear();
1710 if (log)
1711 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1712 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001713 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001714
Kate Stoneb9c1b512016-09-06 20:57:50 +00001715 // Use our target to get a shared pointer to ourselves...
1716 if (m_finalize_called && !PrivateStateThreadIsValid())
1717 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001718 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001719 m_private_state_broadcaster.BroadcastEvent(event_sp);
1720 } else {
1721 if (log)
1722 log->Printf(
1723 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1724 StateAsCString(new_state));
1725 }
Jim Ingham22777012010-09-23 02:01:19 +00001726}
1727
Kate Stoneb9c1b512016-09-06 20:57:50 +00001728void Process::SetRunningUserExpression(bool on) {
1729 m_mod_id.SetRunningUserExpression(on);
1730}
1731
1732addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1733
1734const lldb::ABISP &Process::GetABI() {
1735 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001736 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001737 return m_abi_sp;
1738}
1739
1740LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1741 bool retry_if_null) {
1742 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001743 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001744
1745 LanguageRuntimeCollection::iterator pos;
1746 pos = m_language_runtimes.find(language);
1747 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1748 lldb::LanguageRuntimeSP runtime_sp(
1749 LanguageRuntime::FindPlugin(this, language));
1750
1751 m_language_runtimes[language] = runtime_sp;
1752 return runtime_sp.get();
1753 } else
1754 return (*pos).second.get();
Jim Ingham22777012010-09-23 02:01:19 +00001755}
1756
Kate Stoneb9c1b512016-09-06 20:57:50 +00001757CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1758 LanguageRuntime *runtime =
1759 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1760 if (runtime != nullptr &&
1761 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1762 return static_cast<CPPLanguageRuntime *>(runtime);
1763 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001764}
1765
Kate Stoneb9c1b512016-09-06 20:57:50 +00001766ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1767 LanguageRuntime *runtime =
1768 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1769 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1770 return static_cast<ObjCLanguageRuntime *>(runtime);
1771 return nullptr;
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001772}
1773
Kate Stoneb9c1b512016-09-06 20:57:50 +00001774bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1775 if (m_finalizing)
1776 return false;
1777
1778 if (in_value.IsDynamic())
1779 return false;
1780 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1781
1782 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1783 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1784 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1785 }
1786
1787 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1788 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1789 return true;
1790
1791 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1792 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001793}
1794
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1796 m_dynamic_checkers_ap.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001797}
1798
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799BreakpointSiteList &Process::GetBreakpointSiteList() {
1800 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001801}
1802
Kate Stoneb9c1b512016-09-06 20:57:50 +00001803const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1804 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001805}
1806
Kate Stoneb9c1b512016-09-06 20:57:50 +00001807void Process::DisableAllBreakpointSites() {
1808 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1809 // bp_site->SetEnabled(true);
1810 DisableBreakpointSite(bp_site);
1811 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812}
1813
Zachary Turner97206d52017-05-12 04:51:55 +00001814Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1815 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001816
Kate Stoneb9c1b512016-09-06 20:57:50 +00001817 if (error.Success())
1818 m_breakpoint_site_list.Remove(break_id);
1819
1820 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001821}
1822
Zachary Turner97206d52017-05-12 04:51:55 +00001823Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1824 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001825 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1826 if (bp_site_sp) {
1827 if (bp_site_sp->IsEnabled())
1828 error = DisableBreakpointSite(bp_site_sp.get());
1829 } else {
1830 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1831 break_id);
1832 }
1833
1834 return error;
1835}
1836
Zachary Turner97206d52017-05-12 04:51:55 +00001837Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1838 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001839 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1840 if (bp_site_sp) {
1841 if (!bp_site_sp->IsEnabled())
1842 error = EnableBreakpointSite(bp_site_sp.get());
1843 } else {
1844 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1845 break_id);
1846 }
1847 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001848}
1849
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001850lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001851Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1852 bool use_hardware) {
1853 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001854
Kate Stoneb9c1b512016-09-06 20:57:50 +00001855 bool show_error = true;
1856 switch (GetState()) {
1857 case eStateInvalid:
1858 case eStateUnloaded:
1859 case eStateConnected:
1860 case eStateAttaching:
1861 case eStateLaunching:
1862 case eStateDetached:
1863 case eStateExited:
1864 show_error = false;
1865 break;
1866
1867 case eStateStopped:
1868 case eStateRunning:
1869 case eStateStepping:
1870 case eStateCrashed:
1871 case eStateSuspended:
1872 show_error = IsAlive();
1873 break;
1874 }
1875
Adrian Prantl05097242018-04-30 16:49:04 +00001876 // Reset the IsIndirect flag here, in case the location changes from pointing
1877 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001878 owner->SetIsIndirect(false);
1879
1880 if (owner->ShouldResolveIndirectFunctions()) {
1881 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1882 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001883 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001884 Address symbol_address = symbol->GetAddress();
1885 load_addr = ResolveIndirectFunction(&symbol_address, error);
1886 if (!error.Success() && show_error) {
1887 GetTarget().GetDebugger().GetErrorFile()->Printf(
1888 "warning: failed to resolve indirect function at 0x%" PRIx64
1889 " for breakpoint %i.%i: %s\n",
1890 symbol->GetLoadAddress(&GetTarget()),
1891 owner->GetBreakpoint().GetID(), owner->GetID(),
1892 error.AsCString() ? error.AsCString() : "unknown error");
1893 return LLDB_INVALID_BREAK_ID;
1894 }
1895 Address resolved_address(load_addr);
1896 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1897 owner->SetIsIndirect(true);
1898 } else
1899 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1900 } else
1901 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1902
1903 if (load_addr != LLDB_INVALID_ADDRESS) {
1904 BreakpointSiteSP bp_site_sp;
1905
1906 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001907 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001908
1909 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1910
1911 if (bp_site_sp) {
1912 bp_site_sp->AddOwner(owner);
1913 owner->SetBreakpointSite(bp_site_sp);
1914 return bp_site_sp->GetID();
1915 } else {
1916 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1917 load_addr, use_hardware));
1918 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001919 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001920 if (error.Success()) {
1921 owner->SetBreakpointSite(bp_site_sp);
1922 return m_breakpoint_site_list.Add(bp_site_sp);
1923 } else {
1924 if (show_error) {
1925 // Report error for setting breakpoint...
1926 GetTarget().GetDebugger().GetErrorFile()->Printf(
1927 "warning: failed to set breakpoint site at 0x%" PRIx64
1928 " for breakpoint %i.%i: %s\n",
1929 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1930 error.AsCString() ? error.AsCString() : "unknown error");
1931 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001932 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001933 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001934 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935 }
1936 // We failed to enable the breakpoint
1937 return LLDB_INVALID_BREAK_ID;
1938}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001939
Kate Stoneb9c1b512016-09-06 20:57:50 +00001940void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1941 lldb::user_id_t owner_loc_id,
1942 BreakpointSiteSP &bp_site_sp) {
1943 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1944 if (num_owners == 0) {
1945 // Don't try to disable the site if we don't have a live process anymore.
1946 if (IsAlive())
1947 DisableBreakpointSite(bp_site_sp.get());
1948 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1949 }
1950}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001951
Kate Stoneb9c1b512016-09-06 20:57:50 +00001952size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1953 uint8_t *buf) const {
1954 size_t bytes_removed = 0;
1955 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001956
Kate Stoneb9c1b512016-09-06 20:57:50 +00001957 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1958 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001959 bp_sites_in_range.ForEach([bp_addr, size,
1960 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001961 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1962 addr_t intersect_addr;
1963 size_t intersect_size;
1964 size_t opcode_offset;
1965 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1966 &intersect_size, &opcode_offset)) {
1967 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1968 assert(bp_addr < intersect_addr + intersect_size &&
1969 intersect_addr + intersect_size <= bp_addr + size);
1970 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1971 size_t buf_offset = intersect_addr - bp_addr;
1972 ::memcpy(buf + buf_offset,
1973 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1974 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001975 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001976 }
1977 });
1978 }
1979 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001980}
1981
Kate Stoneb9c1b512016-09-06 20:57:50 +00001982size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1983 PlatformSP platform_sp(GetTarget().GetPlatform());
1984 if (platform_sp)
1985 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1986 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001987}
1988
Zachary Turner97206d52017-05-12 04:51:55 +00001989Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1990 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001991 assert(bp_site != nullptr);
1992 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1993 const addr_t bp_addr = bp_site->GetLoadAddress();
1994 if (log)
1995 log->Printf(
1996 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1997 bp_site->GetID(), (uint64_t)bp_addr);
1998 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001999 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002000 log->Printf(
2001 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2002 " -- already enabled",
2003 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002004 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002005 }
2006
2007 if (bp_addr == LLDB_INVALID_ADDRESS) {
2008 error.SetErrorString("BreakpointSite contains an invalid load address.");
2009 return error;
2010 }
2011 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2012 // trap for the breakpoint site
2013 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2014
2015 if (bp_opcode_size == 0) {
2016 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2017 "returned zero, unable to get breakpoint "
2018 "trap for address 0x%" PRIx64,
2019 bp_addr);
2020 } else {
2021 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2022
2023 if (bp_opcode_bytes == nullptr) {
2024 error.SetErrorString(
2025 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2026 return error;
2027 }
2028
2029 // Save the original opcode by reading it
2030 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2031 error) == bp_opcode_size) {
2032 // Write a software breakpoint in place of the original opcode
2033 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2034 bp_opcode_size) {
2035 uint8_t verify_bp_opcode_bytes[64];
2036 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2037 error) == bp_opcode_size) {
2038 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2039 bp_opcode_size) == 0) {
2040 bp_site->SetEnabled(true);
2041 bp_site->SetType(BreakpointSite::eSoftware);
2042 if (log)
2043 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2044 "addr = 0x%" PRIx64 " -- SUCCESS",
2045 bp_site->GetID(), (uint64_t)bp_addr);
2046 } else
2047 error.SetErrorString(
2048 "failed to verify the breakpoint trap in memory.");
2049 } else
2050 error.SetErrorString(
2051 "Unable to read memory to verify breakpoint trap.");
2052 } else
2053 error.SetErrorString("Unable to write breakpoint trap to memory.");
2054 } else
2055 error.SetErrorString("Unable to read memory at breakpoint address.");
2056 }
2057 if (log && error.Fail())
2058 log->Printf(
2059 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2060 " -- FAILED: %s",
2061 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2062 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002063}
2064
Zachary Turner97206d52017-05-12 04:51:55 +00002065Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2066 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002067 assert(bp_site != nullptr);
2068 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2069 addr_t bp_addr = bp_site->GetLoadAddress();
2070 lldb::user_id_t breakID = bp_site->GetID();
2071 if (log)
2072 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2073 ") addr = 0x%" PRIx64,
2074 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002075
Kate Stoneb9c1b512016-09-06 20:57:50 +00002076 if (bp_site->IsHardware()) {
2077 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2078 } else if (bp_site->IsEnabled()) {
2079 const size_t break_op_size = bp_site->GetByteSize();
2080 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2081 if (break_op_size > 0) {
2082 // Clear a software breakpoint instruction
2083 uint8_t curr_break_op[8];
2084 assert(break_op_size <= sizeof(curr_break_op));
2085 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002086
Kate Stoneb9c1b512016-09-06 20:57:50 +00002087 // Read the breakpoint opcode
2088 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2089 break_op_size) {
2090 bool verify = false;
2091 // Make sure the breakpoint opcode exists at this address
2092 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2093 break_op_found = true;
2094 // We found a valid breakpoint opcode at this address, now restore
2095 // the saved opcode.
2096 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2097 break_op_size, error) == break_op_size) {
2098 verify = true;
2099 } else
2100 error.SetErrorString(
2101 "Memory write failed when restoring original opcode.");
2102 } else {
2103 error.SetErrorString(
2104 "Original breakpoint trap is no longer in memory.");
2105 // Set verify to true and so we can check if the original opcode has
2106 // already been restored
2107 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002109
Kate Stoneb9c1b512016-09-06 20:57:50 +00002110 if (verify) {
2111 uint8_t verify_opcode[8];
2112 assert(break_op_size < sizeof(verify_opcode));
2113 // Verify that our original opcode made it back to the inferior
2114 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2115 break_op_size) {
2116 // compare the memory we just read with the original opcode
2117 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2118 break_op_size) == 0) {
2119 // SUCCESS
2120 bp_site->SetEnabled(false);
2121 if (log)
2122 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2123 "addr = 0x%" PRIx64 " -- SUCCESS",
2124 bp_site->GetID(), (uint64_t)bp_addr);
2125 return error;
2126 } else {
2127 if (break_op_found)
2128 error.SetErrorString("Failed to restore original opcode.");
2129 }
2130 } else
2131 error.SetErrorString("Failed to read memory to verify that "
2132 "breakpoint trap was restored.");
2133 }
2134 } else
2135 error.SetErrorString(
2136 "Unable to read memory that should contain the breakpoint trap.");
2137 }
2138 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002139 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002140 log->Printf(
2141 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2142 " -- already disabled",
2143 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145 }
2146
2147 if (log)
2148 log->Printf(
2149 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2150 " -- FAILED: %s",
2151 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2152 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002153}
2154
Adrian Prantl05097242018-04-30 16:49:04 +00002155// Uncomment to verify memory caching works after making changes to caching
2156// code
Greg Clayton58be07b2011-01-07 06:08:19 +00002157//#define VERIFY_MEMORY_READS
2158
Zachary Turner97206d52017-05-12 04:51:55 +00002159size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002160 error.Clear();
2161 if (!GetDisableMemoryCache()) {
2162#if defined(VERIFY_MEMORY_READS)
2163 // Memory caching is enabled, with debug verification
2164
2165 if (buf && size) {
2166 // Uncomment the line below to make sure memory caching is working.
2167 // I ran this through the test suite and got no assertions, so I am
2168 // pretty confident this is working well. If any changes are made to
2169 // memory caching, uncomment the line below and test your changes!
2170
2171 // Verify all memory reads by using the cache first, then redundantly
2172 // reading the same memory from the inferior and comparing to make sure
2173 // everything is exactly the same.
2174 std::string verify_buf(size, '\0');
2175 assert(verify_buf.size() == size);
2176 const size_t cache_bytes_read =
2177 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00002178 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002179 const size_t verify_bytes_read =
2180 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2181 verify_buf.size(), verify_error);
2182 assert(cache_bytes_read == verify_bytes_read);
2183 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2184 assert(verify_error.Success() == error.Success());
2185 return cache_bytes_read;
2186 }
2187 return 0;
2188#else // !defined(VERIFY_MEMORY_READS)
2189 // Memory caching is enabled, without debug verification
2190
2191 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002192#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002193 } else {
2194 // Memory caching is disabled
2195
2196 return ReadMemoryFromInferior(addr, buf, size, error);
2197 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002198}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002199
2200size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00002201 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002202 char buf[256];
2203 out_str.clear();
2204 addr_t curr_addr = addr;
2205 while (true) {
2206 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2207 if (length == 0)
2208 break;
2209 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00002210 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2211 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00002212 if (length == sizeof(buf) - 1)
2213 curr_addr += length;
2214 else
2215 break;
2216 }
2217 return out_str.size();
2218}
2219
2220size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00002221 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002222 size_t total_bytes_read = 0;
2223 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00002224 // Ensure a null terminator independent of the number of bytes that is
2225 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226 memset(dst, 0, max_bytes);
2227 size_t bytes_left = max_bytes - type_width;
2228
2229 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2230 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2231 "string with more than 4 bytes "
2232 "per character!");
2233
Greg Clayton4c82d422012-05-18 23:20:01 +00002234 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2236 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002237
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 error.Clear();
2239 while (bytes_left > 0 && error.Success()) {
2240 addr_t cache_line_bytes_left =
2241 cache_line_size - (curr_addr % cache_line_size);
2242 addr_t bytes_to_read =
2243 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2244 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002245
Kate Stoneb9c1b512016-09-06 20:57:50 +00002246 if (bytes_read == 0)
2247 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002248
Kate Stoneb9c1b512016-09-06 20:57:50 +00002249 // Search for a null terminator of correct size and alignment in
2250 // bytes_read
2251 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2252 for (size_t i = aligned_start;
2253 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2254 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2255 error.Clear();
2256 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002257 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002258
2259 total_bytes_read += bytes_read;
2260 curr_dst += bytes_read;
2261 curr_addr += bytes_read;
2262 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002263 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002264 } else {
2265 if (max_bytes)
2266 error.SetErrorString("invalid arguments");
2267 }
2268 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002269}
2270
Kate Stoneb9c1b512016-09-06 20:57:50 +00002271// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002272// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002274 size_t dst_max_len,
2275 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002276 size_t total_cstr_len = 0;
2277 if (dst && dst_max_len) {
2278 result_error.Clear();
2279 // NULL out everything just to be safe
2280 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002281 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002282 addr_t curr_addr = addr;
2283 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2284 size_t bytes_left = dst_max_len - 1;
2285 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002286
Kate Stoneb9c1b512016-09-06 20:57:50 +00002287 while (bytes_left > 0) {
2288 addr_t cache_line_bytes_left =
2289 cache_line_size - (curr_addr % cache_line_size);
2290 addr_t bytes_to_read =
2291 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2292 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002293
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294 if (bytes_read == 0) {
2295 result_error = error;
2296 dst[total_cstr_len] = '\0';
2297 break;
2298 }
2299 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002300
Kate Stoneb9c1b512016-09-06 20:57:50 +00002301 total_cstr_len += len;
2302
2303 if (len < bytes_to_read)
2304 break;
2305
2306 curr_dst += bytes_read;
2307 curr_addr += bytes_read;
2308 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002309 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002310 } else {
2311 if (dst == nullptr)
2312 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002313 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002314 result_error.Clear();
2315 }
2316 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002317}
2318
Kate Stoneb9c1b512016-09-06 20:57:50 +00002319size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002320 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002321 if (buf == nullptr || size == 0)
2322 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002323
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324 size_t bytes_read = 0;
2325 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326
Kate Stoneb9c1b512016-09-06 20:57:50 +00002327 while (bytes_read < size) {
2328 const size_t curr_size = size - bytes_read;
2329 const size_t curr_bytes_read =
2330 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2331 bytes_read += curr_bytes_read;
2332 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2333 break;
2334 }
2335
2336 // Replace any software breakpoint opcodes that fall into this range back
2337 // into "buf" before we return
2338 if (bytes_read > 0)
2339 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2340 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002341}
2342
Kate Stoneb9c1b512016-09-06 20:57:50 +00002343uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2344 size_t integer_byte_size,
2345 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002346 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002347 Scalar scalar;
2348 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2349 error))
2350 return scalar.ULongLong(fail_value);
2351 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002352}
2353
Kate Stoneb9c1b512016-09-06 20:57:50 +00002354int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2355 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002356 int64_t fail_value,
2357 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002358 Scalar scalar;
2359 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2360 error))
2361 return scalar.SLongLong(fail_value);
2362 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002363}
2364
Zachary Turner97206d52017-05-12 04:51:55 +00002365addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002366 Scalar scalar;
2367 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2368 error))
2369 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2370 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002371}
2372
Kate Stoneb9c1b512016-09-06 20:57:50 +00002373bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002374 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002375 Scalar scalar;
2376 const uint32_t addr_byte_size = GetAddressByteSize();
2377 if (addr_byte_size <= 4)
2378 scalar = (uint32_t)ptr_value;
2379 else
2380 scalar = ptr_value;
2381 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2382 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002383}
2384
Kate Stoneb9c1b512016-09-06 20:57:50 +00002385size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002386 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002387 size_t bytes_written = 0;
2388 const uint8_t *bytes = (const uint8_t *)buf;
2389
2390 while (bytes_written < size) {
2391 const size_t curr_size = size - bytes_written;
2392 const size_t curr_bytes_written = DoWriteMemory(
2393 addr + bytes_written, bytes + bytes_written, curr_size, error);
2394 bytes_written += curr_bytes_written;
2395 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2396 break;
2397 }
2398 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002399}
2400
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002402 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403#if defined(ENABLE_MEMORY_CACHING)
2404 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002405#endif
2406
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407 if (buf == nullptr || size == 0)
2408 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002409
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002411
Kate Stoneb9c1b512016-09-06 20:57:50 +00002412 // We need to write any data that would go where any current software traps
2413 // (enabled software breakpoints) any software traps (breakpoints) that we
2414 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415
Kate Stoneb9c1b512016-09-06 20:57:50 +00002416 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002417
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2419 bp_sites_in_range)) {
2420 // No breakpoint sites overlap
2421 if (bp_sites_in_range.IsEmpty())
2422 return WriteMemoryPrivate(addr, buf, size, error);
2423 else {
2424 const uint8_t *ubuf = (const uint8_t *)buf;
2425 uint64_t bytes_written = 0;
2426
2427 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2428 &error](BreakpointSite *bp) -> void {
2429
2430 if (error.Success()) {
2431 addr_t intersect_addr;
2432 size_t intersect_size;
2433 size_t opcode_offset;
2434 const bool intersects = bp->IntersectsRange(
2435 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2436 UNUSED_IF_ASSERT_DISABLED(intersects);
2437 assert(intersects);
2438 assert(addr <= intersect_addr && intersect_addr < addr + size);
2439 assert(addr < intersect_addr + intersect_size &&
2440 intersect_addr + intersect_size <= addr + size);
2441 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2442
2443 // Check for bytes before this breakpoint
2444 const addr_t curr_addr = addr + bytes_written;
2445 if (intersect_addr > curr_addr) {
Adrian Prantl05097242018-04-30 16:49:04 +00002446 // There are some bytes before this breakpoint that we need to just
2447 // write to memory
Kate Stoneb9c1b512016-09-06 20:57:50 +00002448 size_t curr_size = intersect_addr - curr_addr;
2449 size_t curr_bytes_written = WriteMemoryPrivate(
2450 curr_addr, ubuf + bytes_written, curr_size, error);
2451 bytes_written += curr_bytes_written;
2452 if (curr_bytes_written != curr_size) {
Adrian Prantl05097242018-04-30 16:49:04 +00002453 // We weren't able to write all of the requested bytes, we are
2454 // done looping and will return the number of bytes that we have
2455 // written so far.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002456 if (error.Success())
2457 error.SetErrorToGenericError();
2458 }
2459 }
2460 // Now write any bytes that would cover up any software breakpoints
2461 // directly into the breakpoint opcode buffer
2462 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2463 ubuf + bytes_written, intersect_size);
2464 bytes_written += intersect_size;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002465 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002466 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002467
Kate Stoneb9c1b512016-09-06 20:57:50 +00002468 if (bytes_written < size)
2469 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2470 size - bytes_written, error);
2471 }
2472 } else {
2473 return WriteMemoryPrivate(addr, buf, size, error);
2474 }
2475
2476 // Write any remaining bytes after the last breakpoint if we have any left
2477 return 0; // bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002478}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002479
Kate Stoneb9c1b512016-09-06 20:57:50 +00002480size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002481 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002482 if (byte_size == UINT32_MAX)
2483 byte_size = scalar.GetByteSize();
2484 if (byte_size > 0) {
2485 uint8_t buf[32];
2486 const size_t mem_size =
2487 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2488 if (mem_size > 0)
2489 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002490 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002491 error.SetErrorString("failed to get scalar as memory data");
2492 } else {
2493 error.SetErrorString("invalid scalar value");
2494 }
2495 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002496}
2497
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2499 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002500 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002501 uint64_t uval = 0;
2502 if (byte_size == 0) {
2503 error.SetErrorString("byte size is zero");
2504 } else if (byte_size & (byte_size - 1)) {
2505 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2506 byte_size);
2507 } else if (byte_size <= sizeof(uval)) {
2508 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2509 if (bytes_read == byte_size) {
2510 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2511 GetAddressByteSize());
2512 lldb::offset_t offset = 0;
2513 if (byte_size <= 4)
2514 scalar = data.GetMaxU32(&offset, byte_size);
2515 else
2516 scalar = data.GetMaxU64(&offset, byte_size);
2517 if (is_signed)
2518 scalar.SignExtend(byte_size * 8);
2519 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002520 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002521 } else {
2522 error.SetErrorStringWithFormat(
2523 "byte size of %u is too large for integer scalar type", byte_size);
2524 }
2525 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002526}
2527
Pavel Labath16064d32018-03-20 11:56:24 +00002528Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2529 Status error;
2530 for (const auto &Entry : entries) {
2531 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2532 error);
2533 if (!error.Success())
2534 break;
2535 }
2536 return error;
2537}
2538
Greg Claytond495c532011-05-17 03:37:42 +00002539#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002540addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002541 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002542 if (GetPrivateState() != eStateStopped)
2543 return LLDB_INVALID_ADDRESS;
2544
2545#if defined(USE_ALLOCATE_MEMORY_CACHE)
2546 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002547#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002548 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2549 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2550 if (log)
2551 log->Printf("Process::AllocateMemory(size=%" PRIu64
2552 ", permissions=%s) => 0x%16.16" PRIx64
2553 " (m_stop_id = %u m_memory_id = %u)",
2554 (uint64_t)size, GetPermissionsAsCString(permissions),
2555 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2556 m_mod_id.GetMemoryID());
2557 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002558#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002559}
2560
Kate Stoneb9c1b512016-09-06 20:57:50 +00002561addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002562 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002563 addr_t return_addr = AllocateMemory(size, permissions, error);
2564 if (error.Success()) {
2565 std::string buffer(size, 0);
2566 WriteMemory(return_addr, buffer.c_str(), size, error);
2567 }
2568 return return_addr;
2569}
2570
2571bool Process::CanJIT() {
2572 if (m_can_jit == eCanJITDontKnow) {
2573 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002574 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002575
2576 uint64_t allocated_memory = AllocateMemory(
2577 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2578 err);
2579
2580 if (err.Success()) {
2581 m_can_jit = eCanJITYes;
2582 if (log)
2583 log->Printf("Process::%s pid %" PRIu64
2584 " allocation test passed, CanJIT () is true",
2585 __FUNCTION__, GetID());
2586 } else {
2587 m_can_jit = eCanJITNo;
2588 if (log)
2589 log->Printf("Process::%s pid %" PRIu64
2590 " allocation test failed, CanJIT () is false: %s",
2591 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002592 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002593
2594 DeallocateMemory(allocated_memory);
2595 }
2596
2597 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002598}
2599
Kate Stoneb9c1b512016-09-06 20:57:50 +00002600void Process::SetCanJIT(bool can_jit) {
2601 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002602}
2603
Kate Stoneb9c1b512016-09-06 20:57:50 +00002604void Process::SetCanRunCode(bool can_run_code) {
2605 SetCanJIT(can_run_code);
2606 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002607}
2608
Zachary Turner97206d52017-05-12 04:51:55 +00002609Status Process::DeallocateMemory(addr_t ptr) {
2610 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002611#if defined(USE_ALLOCATE_MEMORY_CACHE)
2612 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2613 error.SetErrorStringWithFormat(
2614 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2615 }
Greg Claytond495c532011-05-17 03:37:42 +00002616#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002617 error = DoDeallocateMemory(ptr);
2618
2619 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2620 if (log)
2621 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2622 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2623 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2624 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002625#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002626 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002627}
2628
Kate Stoneb9c1b512016-09-06 20:57:50 +00002629ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2630 lldb::addr_t header_addr,
2631 size_t size_to_read) {
2632 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2633 if (log) {
2634 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2635 file_spec.GetPath().c_str());
2636 }
2637 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2638 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002639 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002640 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2641 shared_from_this(), header_addr, error, size_to_read);
2642 if (objfile)
2643 return module_sp;
2644 }
2645 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002646}
2647
Kate Stoneb9c1b512016-09-06 20:57:50 +00002648bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2649 uint32_t &permissions) {
2650 MemoryRegionInfo range_info;
2651 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002652 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002653 if (!error.Success())
2654 return false;
2655 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2656 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2657 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2658 return false;
2659 }
2660
2661 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2662 permissions |= lldb::ePermissionsReadable;
2663
2664 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2665 permissions |= lldb::ePermissionsWritable;
2666
2667 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2668 permissions |= lldb::ePermissionsExecutable;
2669
2670 return true;
2671}
2672
Zachary Turner97206d52017-05-12 04:51:55 +00002673Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2674 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002675 error.SetErrorString("watchpoints are not supported");
2676 return error;
2677}
2678
Zachary Turner97206d52017-05-12 04:51:55 +00002679Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2680 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002681 error.SetErrorString("watchpoints are not supported");
2682 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002683}
2684
2685StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002686Process::WaitForProcessStopPrivate(EventSP &event_sp,
2687 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002688 StateType state;
Adrian Prantl05097242018-04-30 16:49:04 +00002689 // Now wait for the process to launch and return control to us, and then call
2690 // DidLaunch:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002691 while (true) {
2692 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002693 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002694
Kate Stoneb9c1b512016-09-06 20:57:50 +00002695 if (StateIsStoppedState(state, false))
2696 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002697
Kate Stoneb9c1b512016-09-06 20:57:50 +00002698 // If state is invalid, then we timed out
2699 if (state == eStateInvalid)
2700 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002701
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702 if (event_sp)
2703 HandlePrivateEvent(event_sp);
2704 }
2705 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002706}
2707
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708void Process::LoadOperatingSystemPlugin(bool flush) {
2709 if (flush)
2710 m_thread_list.Clear();
2711 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2712 if (flush)
2713 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002714}
2715
Zachary Turner97206d52017-05-12 04:51:55 +00002716Status Process::Launch(ProcessLaunchInfo &launch_info) {
2717 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718 m_abi_sp.reset();
2719 m_dyld_ap.reset();
2720 m_jit_loaders_ap.reset();
2721 m_system_runtime_ap.reset();
2722 m_os_ap.reset();
2723 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724
Kate Stoneb9c1b512016-09-06 20:57:50 +00002725 Module *exe_module = GetTarget().GetExecutableModulePointer();
2726 if (exe_module) {
2727 char local_exec_file_path[PATH_MAX];
2728 char platform_exec_file_path[PATH_MAX];
2729 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2730 sizeof(local_exec_file_path));
2731 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2732 sizeof(platform_exec_file_path));
2733 if (exe_module->GetFileSpec().Exists()) {
2734 // Install anything that might need to be installed prior to launching.
2735 // For host systems, this will do nothing, but if we are connected to a
2736 // remote platform it will install any needed binaries
2737 error = GetTarget().Install(&launch_info);
2738 if (error.Fail())
2739 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002740
Kate Stoneb9c1b512016-09-06 20:57:50 +00002741 if (PrivateStateThreadIsValid())
2742 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002743
Kate Stoneb9c1b512016-09-06 20:57:50 +00002744 error = WillLaunch(exe_module);
2745 if (error.Success()) {
2746 const bool restarted = false;
2747 SetPublicState(eStateLaunching, restarted);
2748 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002749
Kate Stoneb9c1b512016-09-06 20:57:50 +00002750 if (m_public_run_lock.TrySetRunning()) {
2751 // Now launch using these arguments.
2752 error = DoLaunch(exe_module, launch_info);
2753 } else {
2754 // This shouldn't happen
2755 error.SetErrorString("failed to acquire process run lock");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002757
Kate Stoneb9c1b512016-09-06 20:57:50 +00002758 if (error.Fail()) {
2759 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2760 SetID(LLDB_INVALID_PROCESS_ID);
2761 const char *error_string = error.AsCString();
2762 if (error_string == nullptr)
2763 error_string = "launch failed";
2764 SetExitStatus(-1, error_string);
2765 }
2766 } else {
2767 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002768 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Greg Clayton35824e32015-02-20 20:59:47 +00002769
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770 if (state == eStateInvalid || !event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002771 // We were able to launch the process, but we failed to catch the
2772 // initial stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 error.SetErrorString("failed to catch stop after launch");
2774 SetExitStatus(0, "failed to catch stop after launch");
2775 Destroy(false);
2776 } else if (state == eStateStopped || state == eStateCrashed) {
2777 DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002778
Kate Stoneb9c1b512016-09-06 20:57:50 +00002779 DynamicLoader *dyld = GetDynamicLoader();
2780 if (dyld)
2781 dyld->DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002782
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 GetJITLoaders().DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002784
Kate Stoneb9c1b512016-09-06 20:57:50 +00002785 SystemRuntime *system_runtime = GetSystemRuntime();
2786 if (system_runtime)
2787 system_runtime->DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002788
Greg Clayton29eeea02017-02-09 18:55:41 +00002789 if (!m_os_ap)
2790 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002791
Adrian Prantl05097242018-04-30 16:49:04 +00002792 // We successfully launched the process and stopped, now it the
2793 // right time to set up signal filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002794 UpdateAutomaticSignalFiltering();
2795
Kate Stoneb9c1b512016-09-06 20:57:50 +00002796 // Note, the stop event was consumed above, but not handled. This
Adrian Prantl05097242018-04-30 16:49:04 +00002797 // was done to give DidLaunch a chance to run. The target is either
2798 // stopped or crashed. Directly set the state. This is done to
2799 // prevent a stop message with a bunch of spurious output on thread
2800 // status, as well as not pop a ProcessIOHandler.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002801 SetPublicState(state, false);
Greg Claytonc3776bf2012-02-09 06:16:32 +00002802
Kate Stoneb9c1b512016-09-06 20:57:50 +00002803 if (PrivateStateThreadIsValid())
2804 ResumePrivateStateThread();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002805 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806 StartPrivateStateThread();
Todd Fiala76e0fc92014-08-27 22:58:26 +00002807
Kate Stoneb9c1b512016-09-06 20:57:50 +00002808 // Target was stopped at entry as was intended. Need to notify the
Adrian Prantl05097242018-04-30 16:49:04 +00002809 // listeners about it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002810 if (state == eStateStopped &&
2811 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2812 HandlePrivateEvent(event_sp);
2813 } else if (state == eStateExited) {
2814 // We exited while trying to launch somehow. Don't call DidLaunch
Adrian Prantl05097242018-04-30 16:49:04 +00002815 // as that's not likely to work, and return an invalid pid.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002816 HandlePrivateEvent(event_sp);
2817 }
2818 }
2819 }
2820 } else {
2821 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2822 local_exec_file_path);
Jim Inghambb3a2832011-01-29 01:49:25 +00002823 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002824 }
2825 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002826}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002827
Zachary Turner97206d52017-05-12 04:51:55 +00002828Status Process::LoadCore() {
2829 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 if (error.Success()) {
2831 ListenerSP listener_sp(
2832 Listener::MakeListener("lldb.process.load_core_listener"));
2833 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002834
Kate Stoneb9c1b512016-09-06 20:57:50 +00002835 if (PrivateStateThreadIsValid())
2836 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002837 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002838 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002839
Kate Stoneb9c1b512016-09-06 20:57:50 +00002840 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002841 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002842 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002843
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002844 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002845
Kate Stoneb9c1b512016-09-06 20:57:50 +00002846 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002847 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002848 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002849
Greg Clayton29eeea02017-02-09 18:55:41 +00002850 if (!m_os_ap)
2851 LoadOperatingSystemPlugin(false);
2852
Kate Stoneb9c1b512016-09-06 20:57:50 +00002853 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002854 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002856
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002857 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002858 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002859 StateType state =
2860 WaitForProcessToStop(seconds(10), &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002861
2862 if (!StateIsStoppedState(state, false)) {
2863 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2864 if (log)
2865 log->Printf("Process::Halt() failed to stop, state is: %s",
2866 StateAsCString(state));
2867 error.SetErrorString(
2868 "Did not get stopped event after loading the core file.");
2869 }
2870 RestoreProcessEvents();
2871 }
2872 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002873}
2874
Kate Stoneb9c1b512016-09-06 20:57:50 +00002875DynamicLoader *Process::GetDynamicLoader() {
2876 if (!m_dyld_ap)
2877 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2878 return m_dyld_ap.get();
2879}
2880
2881const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2882
2883JITLoaderList &Process::GetJITLoaders() {
2884 if (!m_jit_loaders_ap) {
2885 m_jit_loaders_ap.reset(new JITLoaderList());
2886 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2887 }
2888 return *m_jit_loaders_ap;
2889}
2890
2891SystemRuntime *Process::GetSystemRuntime() {
2892 if (!m_system_runtime_ap)
2893 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2894 return m_system_runtime_ap.get();
2895}
2896
2897Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2898 uint32_t exec_count)
2899 : NextEventAction(process), m_exec_count(exec_count) {
2900 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2901 if (log)
2902 log->Printf(
2903 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2904 __FUNCTION__, static_cast<void *>(process), exec_count);
2905}
2906
2907Process::NextEventAction::EventActionResult
2908Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2909 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2910
2911 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2912 if (log)
2913 log->Printf(
2914 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2915 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2916
2917 switch (state) {
2918 case eStateAttaching:
2919 return eEventActionSuccess;
2920
2921 case eStateRunning:
2922 case eStateConnected:
2923 return eEventActionRetry;
2924
2925 case eStateStopped:
2926 case eStateCrashed:
2927 // During attach, prior to sending the eStateStopped event,
2928 // lldb_private::Process subclasses must set the new process ID.
2929 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002930 // We don't want these events to be reported, so go set the
2931 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002932 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2933
2934 if (m_exec_count > 0) {
2935 --m_exec_count;
2936
2937 if (log)
2938 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2939 "remaining exec count to %" PRIu32 ", requesting resume",
2940 __FUNCTION__, StateAsCString(state), m_exec_count);
2941
2942 RequestResume();
2943 return eEventActionRetry;
2944 } else {
2945 if (log)
2946 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2947 "execs expected to start, continuing with attach",
2948 __FUNCTION__, StateAsCString(state));
2949
2950 m_process->CompleteAttach();
2951 return eEventActionSuccess;
2952 }
2953 break;
2954
2955 default:
2956 case eStateExited:
2957 case eStateInvalid:
2958 break;
2959 }
2960
2961 m_exit_string.assign("No valid Process");
2962 return eEventActionExit;
2963}
2964
2965Process::NextEventAction::EventActionResult
2966Process::AttachCompletionHandler::HandleBeingInterrupted() {
2967 return eEventActionSuccess;
2968}
2969
2970const char *Process::AttachCompletionHandler::GetExitString() {
2971 return m_exit_string.c_str();
2972}
2973
2974ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2975 if (m_listener_sp)
2976 return m_listener_sp;
2977 else
2978 return debugger.GetListener();
2979}
2980
Zachary Turner97206d52017-05-12 04:51:55 +00002981Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982 m_abi_sp.reset();
2983 m_process_input_reader.reset();
2984 m_dyld_ap.reset();
2985 m_jit_loaders_ap.reset();
2986 m_system_runtime_ap.reset();
2987 m_os_ap.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002988
2989 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002990 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2992 char process_name[PATH_MAX];
2993
2994 if (attach_info.GetExecutableFile().GetPath(process_name,
2995 sizeof(process_name))) {
2996 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2997
2998 if (wait_for_launch) {
2999 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3000 if (error.Success()) {
3001 if (m_public_run_lock.TrySetRunning()) {
3002 m_should_detach = true;
3003 const bool restarted = false;
3004 SetPublicState(eStateAttaching, restarted);
3005 // Now attach using these arguments.
3006 error = DoAttachToProcessWithName(process_name, attach_info);
3007 } else {
3008 // This shouldn't happen
3009 error.SetErrorString("failed to acquire process run lock");
3010 }
3011
3012 if (error.Fail()) {
3013 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3014 SetID(LLDB_INVALID_PROCESS_ID);
3015 if (error.AsCString() == nullptr)
3016 error.SetErrorString("attach failed");
3017
3018 SetExitStatus(-1, error.AsCString());
3019 }
3020 } else {
3021 SetNextEventAction(new Process::AttachCompletionHandler(
3022 this, attach_info.GetResumeCount()));
3023 StartPrivateStateThread();
3024 }
3025 return error;
3026 }
3027 } else {
3028 ProcessInstanceInfoList process_infos;
3029 PlatformSP platform_sp(GetTarget().GetPlatform());
3030
3031 if (platform_sp) {
3032 ProcessInstanceInfoMatch match_info;
3033 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00003034 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003035 platform_sp->FindProcesses(match_info, process_infos);
3036 const uint32_t num_matches = process_infos.GetSize();
3037 if (num_matches == 1) {
3038 attach_pid = process_infos.GetProcessIDAtIndex(0);
3039 // Fall through and attach using the above process ID
3040 } else {
3041 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3042 process_name, sizeof(process_name));
3043 if (num_matches > 1) {
3044 StreamString s;
3045 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3046 false);
3047 for (size_t i = 0; i < num_matches; i++) {
3048 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3049 s, platform_sp.get(), true, false);
3050 }
3051 error.SetErrorStringWithFormat(
3052 "more than one process named %s:\n%s", process_name,
3053 s.GetData());
3054 } else
3055 error.SetErrorStringWithFormat(
3056 "could not find a process named %s", process_name);
3057 }
3058 } else {
3059 error.SetErrorString(
3060 "invalid platform, can't find processes by name");
3061 return error;
3062 }
3063 }
3064 } else {
3065 error.SetErrorString("invalid process name");
3066 }
3067 }
3068
3069 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3070 error = WillAttachToProcessWithID(attach_pid);
3071 if (error.Success()) {
3072
3073 if (m_public_run_lock.TrySetRunning()) {
3074 // Now attach using these arguments.
3075 m_should_detach = true;
3076 const bool restarted = false;
3077 SetPublicState(eStateAttaching, restarted);
3078 error = DoAttachToProcessWithID(attach_pid, attach_info);
3079 } else {
3080 // This shouldn't happen
3081 error.SetErrorString("failed to acquire process run lock");
3082 }
3083
3084 if (error.Success()) {
3085 SetNextEventAction(new Process::AttachCompletionHandler(
3086 this, attach_info.GetResumeCount()));
3087 StartPrivateStateThread();
3088 } else {
Greg Clayton71337622011-02-24 22:24:29 +00003089 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003090 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003091
Kate Stoneb9c1b512016-09-06 20:57:50 +00003092 const char *error_string = error.AsCString();
3093 if (error_string == nullptr)
3094 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00003095
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096 SetExitStatus(-1, error_string);
3097 }
Greg Claytonb766a732011-02-04 01:58:07 +00003098 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 }
3100 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00003101}
3102
Kate Stoneb9c1b512016-09-06 20:57:50 +00003103void Process::CompleteAttach() {
3104 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3105 LIBLLDB_LOG_TARGET));
3106 if (log)
3107 log->Printf("Process::%s()", __FUNCTION__);
3108
3109 // Let the process subclass figure out at much as it can about the process
3110 // before we go looking for a dynamic loader plug-in.
3111 ArchSpec process_arch;
3112 DidAttach(process_arch);
3113
3114 if (process_arch.IsValid()) {
3115 GetTarget().SetArchitecture(process_arch);
3116 if (log) {
3117 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3118 log->Printf("Process::%s replacing process architecture with DidAttach() "
3119 "architecture: %s",
3120 __FUNCTION__, triple_str ? triple_str : "<null>");
3121 }
3122 }
3123
3124 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00003125 // architecture, and if it isn't the same as the one we've already set,
3126 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003127 PlatformSP platform_sp(GetTarget().GetPlatform());
3128 assert(platform_sp);
3129 if (platform_sp) {
3130 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3131 if (target_arch.IsValid() &&
3132 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3133 ArchSpec platform_arch;
3134 platform_sp =
3135 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3136 if (platform_sp) {
3137 GetTarget().SetPlatform(platform_sp);
3138 GetTarget().SetArchitecture(platform_arch);
3139 if (log)
3140 log->Printf("Process::%s switching platform to %s and architecture "
3141 "to %s based on info from attach",
3142 __FUNCTION__, platform_sp->GetName().AsCString(""),
3143 platform_arch.GetTriple().getTriple().c_str());
3144 }
3145 } else if (!process_arch.IsValid()) {
3146 ProcessInstanceInfo process_info;
3147 GetProcessInfo(process_info);
3148 const ArchSpec &process_arch = process_info.GetArchitecture();
3149 if (process_arch.IsValid() &&
3150 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3151 GetTarget().SetArchitecture(process_arch);
3152 if (log)
3153 log->Printf("Process::%s switching architecture to %s based on info "
3154 "the platform retrieved for pid %" PRIu64,
3155 __FUNCTION__,
3156 process_arch.GetTriple().getTriple().c_str(), GetID());
3157 }
3158 }
3159 }
3160
3161 // We have completed the attach, now it is time to find the dynamic loader
3162 // plug-in
3163 DynamicLoader *dyld = GetDynamicLoader();
3164 if (dyld) {
3165 dyld->DidAttach();
3166 if (log) {
3167 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3168 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3169 "executable is %s (using %s plugin)",
3170 __FUNCTION__,
3171 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3172 : "<none>",
3173 dyld->GetPluginName().AsCString("<unnamed>"));
3174 }
3175 }
3176
3177 GetJITLoaders().DidAttach();
3178
3179 SystemRuntime *system_runtime = GetSystemRuntime();
3180 if (system_runtime) {
3181 system_runtime->DidAttach();
3182 if (log) {
3183 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3184 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3185 "executable is %s (using %s plugin)",
3186 __FUNCTION__,
3187 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3188 : "<none>",
3189 system_runtime->GetPluginName().AsCString("<unnamed>"));
3190 }
3191 }
3192
Greg Clayton29eeea02017-02-09 18:55:41 +00003193 if (!m_os_ap)
3194 LoadOperatingSystemPlugin(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003195 // Figure out which one is the executable, and set that in our target:
3196 const ModuleList &target_modules = GetTarget().GetImages();
3197 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3198 size_t num_modules = target_modules.GetSize();
3199 ModuleSP new_executable_module_sp;
3200
3201 for (size_t i = 0; i < num_modules; i++) {
3202 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3203 if (module_sp && module_sp->IsExecutable()) {
3204 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3205 new_executable_module_sp = module_sp;
3206 break;
3207 }
3208 }
3209 if (new_executable_module_sp) {
3210 GetTarget().SetExecutableModule(new_executable_module_sp, false);
3211 if (log) {
3212 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3213 log->Printf(
3214 "Process::%s after looping through modules, target executable is %s",
3215 __FUNCTION__,
3216 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3217 : "<none>");
3218 }
3219 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003220}
3221
Zachary Turner97206d52017-05-12 04:51:55 +00003222Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003223 m_abi_sp.reset();
3224 m_process_input_reader.reset();
3225
3226 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003227 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003228
Zachary Turner97206d52017-05-12 04:51:55 +00003229 Status error(DoConnectRemote(strm, remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003230 if (error.Success()) {
3231 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3232 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003233 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003234
3235 if (state == eStateStopped || state == eStateCrashed) {
3236 // If we attached and actually have a process on the other end, then
3237 // this ended up being the equivalent of an attach.
3238 CompleteAttach();
3239
3240 // This delays passing the stopped event to listeners till
3241 // CompleteAttach gets a chance to complete...
3242 HandlePrivateEvent(event_sp);
3243 }
3244 }
3245
3246 if (PrivateStateThreadIsValid())
3247 ResumePrivateStateThread();
3248 else
3249 StartPrivateStateThread();
3250 }
3251 return error;
3252}
3253
Zachary Turner97206d52017-05-12 04:51:55 +00003254Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003255 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3256 LIBLLDB_LOG_STEP));
3257 if (log)
3258 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3259 "private state: %s",
3260 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3261 StateAsCString(m_private_state.GetValue()));
3262
Adrian Prantl05097242018-04-30 16:49:04 +00003263 // If signals handing status changed we might want to update our signal
3264 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003265 UpdateAutomaticSignalFiltering();
3266
Zachary Turner97206d52017-05-12 04:51:55 +00003267 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003268 // Tell the process it is about to resume before the thread list
3269 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003270 // Now let the thread list know we are about to resume so it can let all of
3271 // our threads know that they are about to be resumed. Threads will each be
3272 // called with Thread::WillResume(StateType) where StateType contains the
3273 // state that they are supposed to have when the process is resumed
3274 // (suspended/running/stepping). Threads should also check their resume
3275 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3276 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003277 if (m_thread_list.WillResume()) {
3278 // Last thing, do the PreResumeActions.
3279 if (!RunPreResumeActions()) {
3280 error.SetErrorStringWithFormat(
3281 "Process::PrivateResume PreResumeActions failed, not resuming.");
3282 } else {
3283 m_mod_id.BumpResumeID();
3284 error = DoResume();
3285 if (error.Success()) {
3286 DidResume();
3287 m_thread_list.DidResume();
3288 if (log)
3289 log->Printf("Process thinks the process has resumed.");
3290 }
3291 }
3292 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003293 // Somebody wanted to run without running (e.g. we were faking a step
3294 // from one frame of a set of inlined frames that share the same PC to
3295 // another.) So generate a continue & a stopped event, and let the world
3296 // handle them.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003297 if (log)
3298 log->Printf(
3299 "Process::PrivateResume() asked to simulate a start & stop.");
3300
3301 SetPrivateState(eStateRunning);
3302 SetPrivateState(eStateStopped);
3303 }
3304 } else if (log)
3305 log->Printf("Process::PrivateResume() got an error \"%s\".",
3306 error.AsCString("<unknown error>"));
3307 return error;
3308}
3309
Zachary Turner97206d52017-05-12 04:51:55 +00003310Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003311 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003312 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003313
Adrian Prantl05097242018-04-30 16:49:04 +00003314 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3315 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003316 m_clear_thread_plans_on_stop |= clear_thread_plans;
3317
3318 ListenerSP halt_listener_sp(
3319 Listener::MakeListener("lldb.process.halt_listener"));
3320 HijackProcessEvents(halt_listener_sp);
3321
3322 EventSP event_sp;
3323
3324 SendAsyncInterrupt();
3325
3326 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003327 // Don't hijack and eat the eStateExited as the code that was doing the
3328 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003329 RestoreProcessEvents();
3330 SetExitStatus(SIGKILL, "Cancelled async attach.");
3331 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003332 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003333 }
3334
3335 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003336 StateType state = WaitForProcessToStop(
3337 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003338 RestoreProcessEvents();
3339
3340 if (state == eStateInvalid || !event_sp) {
3341 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003342 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003343 }
3344
3345 BroadcastEvent(event_sp);
3346
Zachary Turner97206d52017-05-12 04:51:55 +00003347 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003348}
3349
Zachary Turner97206d52017-05-12 04:51:55 +00003350Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3351 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003352
3353 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003354 // expression, for instance, then the public state will be stopped, but we
3355 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003356 if (m_public_state.GetValue() == eStateRunning ||
3357 m_private_state.GetValue() == eStateRunning) {
3358 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003359 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003360 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003361
Kate Stoneb9c1b512016-09-06 20:57:50 +00003362 ListenerSP listener_sp(
3363 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3364 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003365
Pavel Labath19da1f12015-12-07 12:36:52 +00003366 SendAsyncInterrupt();
3367
Kate Stoneb9c1b512016-09-06 20:57:50 +00003368 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003369 StateType state =
3370 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003371
Pavel Labath19da1f12015-12-07 12:36:52 +00003372 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003373
Kate Stoneb9c1b512016-09-06 20:57:50 +00003374 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003375 // exited event into the shared pointer passed in and return. Our caller
3376 // doesn't need to do anything else, since they don't have a process
3377 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003378
3379 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3380 if (log)
3381 log->Printf("Process::%s() Process exited while waiting to stop.",
3382 __FUNCTION__);
3383 return error;
3384 } else
3385 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3386
3387 if (state != eStateStopped) {
3388 if (log)
3389 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3390 StateAsCString(state));
3391 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003392 // here, but if the lower levels just bobbled sending the event and we
3393 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003394 StateType private_state = m_private_state.GetValue();
3395 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003396 return Status(
3397 "Attempt to stop the target in order to detach timed out. "
3398 "State = %s",
3399 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003400 }
3401 }
3402 }
3403 return error;
3404}
3405
Zachary Turner97206d52017-05-12 04:51:55 +00003406Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003407 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003408 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003409 m_destroy_in_process = true;
3410
3411 error = WillDetach();
3412
3413 if (error.Success()) {
3414 if (DetachRequiresHalt()) {
3415 error = StopForDestroyOrDetach(exit_event_sp);
3416 if (!error.Success()) {
3417 m_destroy_in_process = false;
3418 return error;
3419 } else if (exit_event_sp) {
3420 // We shouldn't need to do anything else here. There's no process left
3421 // to detach from...
3422 StopPrivateStateThread();
3423 m_destroy_in_process = false;
3424 return error;
3425 }
3426 }
3427
3428 m_thread_list.DiscardThreadPlans();
3429 DisableAllBreakpointSites();
3430
3431 error = DoDetach(keep_stopped);
3432 if (error.Success()) {
3433 DidDetach();
3434 StopPrivateStateThread();
3435 } else {
3436 return error;
3437 }
3438 }
3439 m_destroy_in_process = false;
3440
Adrian Prantl05097242018-04-30 16:49:04 +00003441 // If we exited when we were waiting for a process to stop, then forward the
3442 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003443 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003444 // Directly broadcast our exited event because we shut down our private
3445 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003446 BroadcastEvent(exit_event_sp);
3447 }
3448
3449 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003450 // not end up propagating the last events through the event system, in which
3451 // case we might strand the write lock. Unlock it here so when we do to tear
3452 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003453
3454 m_public_run_lock.SetStopped();
3455 return error;
3456}
3457
Zachary Turner97206d52017-05-12 04:51:55 +00003458Status Process::Destroy(bool force_kill) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003459
3460 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003461 // don't do any unnecessary work that might hinder the destruction. Remember
3462 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003463 // failed and the process stays around for some reason it won't be in a
3464 // confused state.
3465
3466 if (force_kill)
3467 m_should_detach = false;
3468
3469 if (GetShouldDetach()) {
3470 // FIXME: This will have to be a process setting:
3471 bool keep_stopped = false;
3472 Detach(keep_stopped);
3473 }
3474
3475 m_destroy_in_process = true;
3476
Zachary Turner97206d52017-05-12 04:51:55 +00003477 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003478 if (error.Success()) {
3479 EventSP exit_event_sp;
3480 if (DestroyRequiresHalt()) {
3481 error = StopForDestroyOrDetach(exit_event_sp);
3482 }
3483
3484 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003485 // Ditch all thread plans, and remove all our breakpoints: in case we
3486 // have to restart the target to kill it, we don't want it hitting a
3487 // breakpoint... Only do this if we've stopped, however, since if we
3488 // didn't manage to halt it above, then we're not going to have much luck
3489 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003490 m_thread_list.DiscardThreadPlans();
3491 DisableAllBreakpointSites();
3492 }
3493
3494 error = DoDestroy();
3495 if (error.Success()) {
3496 DidDestroy();
3497 StopPrivateStateThread();
3498 }
3499 m_stdio_communication.Disconnect();
3500 m_stdio_communication.StopReadThread();
3501 m_stdin_forward = false;
3502
3503 if (m_process_input_reader) {
3504 m_process_input_reader->SetIsDone(true);
3505 m_process_input_reader->Cancel();
3506 m_process_input_reader.reset();
3507 }
3508
Adrian Prantl05097242018-04-30 16:49:04 +00003509 // If we exited when we were waiting for a process to stop, then forward
3510 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003511 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003512 // Directly broadcast our exited event because we shut down our private
3513 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003514 BroadcastEvent(exit_event_sp);
3515 }
3516
Adrian Prantl05097242018-04-30 16:49:04 +00003517 // If we have been interrupted (to kill us) in the middle of running, we
3518 // may not end up propagating the last events through the event system, in
3519 // which case we might strand the write lock. Unlock it here so when we do
3520 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003521 m_public_run_lock.SetStopped();
3522 }
3523
3524 m_destroy_in_process = false;
3525
3526 return error;
3527}
3528
Zachary Turner97206d52017-05-12 04:51:55 +00003529Status Process::Signal(int signal) {
3530 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003531 if (error.Success()) {
3532 error = DoSignal(signal);
3533 if (error.Success())
3534 DidSignal();
3535 }
3536 return error;
3537}
3538
3539void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3540 assert(signals_sp && "null signals_sp");
3541 m_unix_signals_sp = signals_sp;
3542}
3543
3544const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3545 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3546 return m_unix_signals_sp;
3547}
3548
3549lldb::ByteOrder Process::GetByteOrder() const {
3550 return GetTarget().GetArchitecture().GetByteOrder();
3551}
3552
3553uint32_t Process::GetAddressByteSize() const {
3554 return GetTarget().GetArchitecture().GetAddressByteSize();
3555}
3556
3557bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3558 const StateType state =
3559 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3560 bool return_value = true;
3561 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3562 LIBLLDB_LOG_PROCESS));
3563
3564 switch (state) {
3565 case eStateDetached:
3566 case eStateExited:
3567 case eStateUnloaded:
3568 m_stdio_communication.SynchronizeWithReadThread();
3569 m_stdio_communication.Disconnect();
3570 m_stdio_communication.StopReadThread();
3571 m_stdin_forward = false;
3572
3573 LLVM_FALLTHROUGH;
3574 case eStateConnected:
3575 case eStateAttaching:
3576 case eStateLaunching:
3577 // These events indicate changes in the state of the debugging session,
3578 // always report them.
3579 return_value = true;
3580 break;
3581 case eStateInvalid:
3582 // We stopped for no apparent reason, don't report it.
3583 return_value = false;
3584 break;
3585 case eStateRunning:
3586 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003587 // If we've started the target running, we handle the cases where we are
3588 // already running and where there is a transition from stopped to running
3589 // differently. running -> running: Automatically suppress extra running
3590 // events stopped -> running: Report except when there is one or more no
3591 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003592 // and no yes votes.
3593 SynchronouslyNotifyStateChanged(state);
3594 if (m_force_next_event_delivery)
3595 return_value = true;
3596 else {
3597 switch (m_last_broadcast_state) {
3598 case eStateRunning:
3599 case eStateStepping:
3600 // We always suppress multiple runnings with no PUBLIC stop in between.
3601 return_value = false;
3602 break;
3603 default:
3604 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003605 // run if we aren't running so we don't miss any running events. If I
3606 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3607 // and hit the breakpoints on multiple threads, then somehow during the
3608 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003609
3610 // This is a transition from stop to run.
3611 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3612 case eVoteYes:
3613 case eVoteNoOpinion:
3614 return_value = true;
3615 break;
3616 case eVoteNo:
3617 return_value = false;
3618 break;
3619 }
3620 break;
3621 }
3622 }
3623 break;
3624 case eStateStopped:
3625 case eStateCrashed:
3626 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003627 // We've stopped. First see if we're going to restart the target. If we
3628 // are going to stop, then we always broadcast the event. If we aren't
3629 // going to stop, let the thread plans decide if we're going to report this
3630 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003631
3632 m_stdio_communication.SynchronizeWithReadThread();
3633 RefreshStateAfterStop();
3634 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3635 if (log)
3636 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3637 "interrupt, state: %s",
3638 static_cast<void *>(event_ptr), StateAsCString(state));
3639 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003640 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003641 m_thread_list.ShouldStop(event_ptr);
3642 return_value = true;
3643 } else {
3644 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3645 bool should_resume = false;
3646
3647 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003648 // restarted... Asking the thread list is also not likely to go well,
3649 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003650
3651 if (!was_restarted)
3652 should_resume = !m_thread_list.ShouldStop(event_ptr);
3653
3654 if (was_restarted || should_resume || m_resume_requested) {
3655 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3656 if (log)
3657 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3658 "%s was_restarted: %i stop_vote: %d.",
3659 should_resume, StateAsCString(state), was_restarted,
3660 stop_vote);
3661
3662 switch (stop_vote) {
3663 case eVoteYes:
3664 return_value = true;
3665 break;
3666 case eVoteNoOpinion:
3667 case eVoteNo:
3668 return_value = false;
3669 break;
3670 }
3671
3672 if (!was_restarted) {
3673 if (log)
3674 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3675 "from state: %s",
3676 static_cast<void *>(event_ptr), StateAsCString(state));
3677 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3678 PrivateResume();
3679 }
3680 } else {
3681 return_value = true;
3682 SynchronouslyNotifyStateChanged(state);
3683 }
3684 }
3685 break;
3686 }
3687
3688 // Forcing the next event delivery is a one shot deal. So reset it here.
3689 m_force_next_event_delivery = false;
3690
3691 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003692 // events get coalesced.) But we only coalesce against events we actually
3693 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3694 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3695 // done, because the PublicState reflects the last event pulled off the
3696 // queue, and there may be several events stacked up on the queue unserviced.
3697 // So the PublicState may not reflect the last broadcasted event yet.
3698 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003699
3700 if (return_value)
3701 m_last_broadcast_state = state;
3702
3703 if (log)
3704 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3705 "broadcast state: %s - %s",
3706 static_cast<void *>(event_ptr), StateAsCString(state),
3707 StateAsCString(m_last_broadcast_state),
3708 return_value ? "YES" : "NO");
3709 return return_value;
3710}
3711
3712bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3713 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3714
3715 bool already_running = PrivateStateThreadIsValid();
3716 if (log)
3717 log->Printf("Process::%s()%s ", __FUNCTION__,
3718 already_running ? " already running"
3719 : " starting private state thread");
3720
3721 if (!is_secondary_thread && already_running)
3722 return true;
3723
Adrian Prantl05097242018-04-30 16:49:04 +00003724 // Create a thread that watches our internal state and controls which events
3725 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003726 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003727 uint32_t max_len = llvm::get_max_thread_name_length();
3728 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003729 // On platforms with abbreviated thread name lengths, choose thread names
3730 // that fit within the limit.
3731 if (already_running)
3732 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3733 else
3734 snprintf(thread_name, sizeof(thread_name), "intern-state");
3735 } else {
3736 if (already_running)
3737 snprintf(thread_name, sizeof(thread_name),
3738 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3739 GetID());
3740 else
3741 snprintf(thread_name, sizeof(thread_name),
3742 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3743 }
3744
3745 // Create the private state thread, and start it running.
3746 PrivateStateThreadArgs *args_ptr =
3747 new PrivateStateThreadArgs(this, is_secondary_thread);
3748 m_private_state_thread =
3749 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3750 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3751 if (m_private_state_thread.IsJoinable()) {
3752 ResumePrivateStateThread();
3753 return true;
3754 } else
3755 return false;
3756}
3757
3758void Process::PausePrivateStateThread() {
3759 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3760}
3761
3762void Process::ResumePrivateStateThread() {
3763 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3764}
3765
3766void Process::StopPrivateStateThread() {
3767 if (m_private_state_thread.IsJoinable())
3768 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3769 else {
3770 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3771 if (log)
3772 log->Printf(
3773 "Went to stop the private state thread, but it was already invalid.");
3774 }
3775}
3776
3777void Process::ControlPrivateStateThread(uint32_t signal) {
3778 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3779
3780 assert(signal == eBroadcastInternalStateControlStop ||
3781 signal == eBroadcastInternalStateControlPause ||
3782 signal == eBroadcastInternalStateControlResume);
3783
3784 if (log)
3785 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3786
3787 // Signal the private state thread
3788 if (m_private_state_thread.IsJoinable()) {
3789 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003790 // It is important to do this outside of the if below, because it's
3791 // possible that the thread state is invalid but that the thread is waiting
3792 // on a control event instead of simply being on its way out (this should
3793 // not happen, but it apparently can).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003794 if (log)
3795 log->Printf("Sending control event of type: %d.", signal);
3796 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3797 m_private_state_control_broadcaster.BroadcastEvent(signal,
3798 event_receipt_sp);
3799
3800 // Wait for the event receipt or for the private state thread to exit
3801 bool receipt_received = false;
3802 if (PrivateStateThreadIsValid()) {
3803 while (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003804 // Check for a receipt for 2 seconds and then check if the private
3805 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003806 receipt_received =
3807 event_receipt_sp->WaitForEventReceived(std::chrono::seconds(2));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003808 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003809 // Check if the private state thread is still around. If it isn't
3810 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003811 if (!PrivateStateThreadIsValid())
3812 break; // Private state thread exited or is exiting, we are done
3813 }
3814 }
3815 }
3816
3817 if (signal == eBroadcastInternalStateControlStop) {
3818 thread_result_t result = NULL;
3819 m_private_state_thread.Join(&result);
3820 m_private_state_thread.Reset();
3821 }
3822 } else {
3823 if (log)
3824 log->Printf(
3825 "Private state thread already dead, no need to signal it to stop.");
3826 }
3827}
3828
3829void Process::SendAsyncInterrupt() {
3830 if (PrivateStateThreadIsValid())
3831 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3832 nullptr);
3833 else
3834 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3835}
3836
3837void Process::HandlePrivateEvent(EventSP &event_sp) {
3838 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3839 m_resume_requested = false;
3840
3841 const StateType new_state =
3842 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3843
3844 // First check to see if anybody wants a shot at this event:
3845 if (m_next_event_action_ap) {
3846 NextEventAction::EventActionResult action_result =
3847 m_next_event_action_ap->PerformAction(event_sp);
3848 if (log)
3849 log->Printf("Ran next event action, result was %d.", action_result);
3850
3851 switch (action_result) {
3852 case NextEventAction::eEventActionSuccess:
3853 SetNextEventAction(nullptr);
3854 break;
3855
3856 case NextEventAction::eEventActionRetry:
3857 break;
3858
3859 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003860 // Handle Exiting Here. If we already got an exited event, we should
3861 // just propagate it. Otherwise, swallow this event, and set our state
3862 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003863 if (new_state != eStateExited) {
3864 // FIXME: should cons up an exited event, and discard this one.
3865 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3866 SetNextEventAction(nullptr);
3867 return;
3868 }
3869 SetNextEventAction(nullptr);
3870 break;
3871 }
3872 }
3873
3874 // See if we should broadcast this state to external clients?
3875 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3876
3877 if (should_broadcast) {
3878 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3879 if (log) {
3880 log->Printf("Process::%s (pid = %" PRIu64
3881 ") broadcasting new state %s (old state %s) to %s",
3882 __FUNCTION__, GetID(), StateAsCString(new_state),
3883 StateAsCString(GetState()),
3884 is_hijacked ? "hijacked" : "public");
3885 }
3886 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3887 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003888 // Only push the input handler if we aren't fowarding events, as this
3889 // means the curses GUI is in use... Or don't push it if we are launching
3890 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003891 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3892 new_state != eStateLaunching && new_state != eStateAttaching) {
3893 PushProcessIOHandler();
3894 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3895 eBroadcastAlways);
3896 if (log)
3897 log->Printf("Process::%s updated m_iohandler_sync to %d",
3898 __FUNCTION__, m_iohandler_sync.GetValue());
3899 }
3900 } else if (StateIsStoppedState(new_state, false)) {
3901 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003902 // If the lldb_private::Debugger is handling the events, we don't want
3903 // to pop the process IOHandler here, we want to do it when we receive
3904 // the stopped event so we can carefully control when the process
3905 // IOHandler is popped because when we stop we want to display some
3906 // text stating how and why we stopped, then maybe some
3907 // process/thread/frame info, and then we want the "(lldb) " prompt to
3908 // show up. If we pop the process IOHandler here, then we will cause
3909 // the command interpreter to become the top IOHandler after the
3910 // process pops off and it will update its prompt right away... See the
3911 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003912 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3913 // Otherwise we end up getting overlapping "(lldb) " prompts and
3914 // garbled output.
3915 //
3916 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003917 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3918 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003919 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003920 // thread plans, or when commands want to run in synchronous mode and
3921 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003922 // that will hijack the events is a simple expression:
3923 //
3924 // (lldb) expr (int)puts("hello")
3925 //
3926 // This will cause the internal process state thread to resume and halt
3927 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3928 // events) and we do need the IO handler to be pushed and popped
3929 // correctly.
3930
3931 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3932 PopProcessIOHandler();
3933 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003934 }
3935
3936 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003937 } else {
3938 if (log) {
3939 log->Printf(
3940 "Process::%s (pid = %" PRIu64
3941 ") suppressing state %s (old state %s): should_broadcast == false",
3942 __FUNCTION__, GetID(), StateAsCString(new_state),
3943 StateAsCString(GetState()));
3944 }
3945 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003946}
3947
Zachary Turner97206d52017-05-12 04:51:55 +00003948Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003949 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003950 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003951 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003952 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003953
3954 // Ask the process subclass to actually halt our process
3955 bool caused_stop;
3956 error = DoHalt(caused_stop);
3957
3958 DidHalt();
3959 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003960}
3961
Kate Stoneb9c1b512016-09-06 20:57:50 +00003962thread_result_t Process::PrivateStateThread(void *arg) {
3963 std::unique_ptr<PrivateStateThreadArgs> args_up(
3964 static_cast<PrivateStateThreadArgs *>(arg));
3965 thread_result_t result =
3966 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3967 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003968}
3969
Kate Stoneb9c1b512016-09-06 20:57:50 +00003970thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3971 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003972
Kate Stoneb9c1b512016-09-06 20:57:50 +00003973 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3974 if (log)
3975 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3976 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003977
Kate Stoneb9c1b512016-09-06 20:57:50 +00003978 bool exit_now = false;
3979 bool interrupt_requested = false;
3980 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003981 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003982 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003983 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3984 if (log)
3985 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3986 ") got a control event: %d",
3987 __FUNCTION__, static_cast<void *>(this), GetID(),
3988 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003989
Kate Stoneb9c1b512016-09-06 20:57:50 +00003990 switch (event_sp->GetType()) {
3991 case eBroadcastInternalStateControlStop:
3992 exit_now = true;
3993 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003994
Kate Stoneb9c1b512016-09-06 20:57:50 +00003995 case eBroadcastInternalStateControlPause:
3996 control_only = true;
3997 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003998
Kate Stoneb9c1b512016-09-06 20:57:50 +00003999 case eBroadcastInternalStateControlResume:
4000 control_only = false;
4001 break;
4002 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004003
Kate Stoneb9c1b512016-09-06 20:57:50 +00004004 continue;
4005 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4006 if (m_public_state.GetValue() == eStateAttaching) {
4007 if (log)
4008 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4009 ") woke up with an interrupt while attaching - "
4010 "forwarding interrupt.",
4011 __FUNCTION__, static_cast<void *>(this), GetID());
4012 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4013 } else if (StateIsRunningState(m_last_broadcast_state)) {
4014 if (log)
4015 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4016 ") woke up with an interrupt - Halting.",
4017 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00004018 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004019 if (error.Fail() && log)
4020 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4021 ") failed to halt the process: %s",
4022 __FUNCTION__, static_cast<void *>(this), GetID(),
4023 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00004024 // Halt should generate a stopped event. Make a note of the fact that
4025 // we were doing the interrupt, so we can set the interrupted flag
4026 // after we receive the event. We deliberately set this to true even if
4027 // HaltPrivate failed, so that we can interrupt on the next natural
4028 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004029 interrupt_requested = true;
4030 } else {
4031 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00004032 // running and sends an interrupt request, but the process actually
4033 // stops before we receive it. In that case, we can just ignore the
4034 // request. We use m_last_broadcast_state, because the Stopped event
4035 // may not have been popped of the event queue yet, which is when the
4036 // public state gets updated.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004037 if (log)
4038 log->Printf(
4039 "Process::%s ignoring interrupt as we have already stopped.",
4040 __FUNCTION__);
4041 }
4042 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004043 }
4044
Kate Stoneb9c1b512016-09-06 20:57:50 +00004045 const StateType internal_state =
4046 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004047
Kate Stoneb9c1b512016-09-06 20:57:50 +00004048 if (internal_state != eStateInvalid) {
4049 if (m_clear_thread_plans_on_stop &&
4050 StateIsStoppedState(internal_state, true)) {
4051 m_clear_thread_plans_on_stop = false;
4052 m_thread_list.DiscardThreadPlans();
4053 }
4054
4055 if (interrupt_requested) {
4056 if (StateIsStoppedState(internal_state, true)) {
4057 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00004058 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00004059 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4060 interrupt_requested = false;
4061 } else if (log) {
4062 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4063 "state '%s' received.",
4064 __FUNCTION__, StateAsCString(internal_state));
4065 }
4066 }
4067
4068 HandlePrivateEvent(event_sp);
4069 }
4070
4071 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4072 internal_state == eStateDetached) {
4073 if (log)
4074 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4075 ") about to exit with internal state %s...",
4076 __FUNCTION__, static_cast<void *>(this), GetID(),
4077 StateAsCString(internal_state));
4078
4079 break;
4080 }
4081 }
4082
4083 // Verify log is still enabled before attempting to write to it...
4084 if (log)
4085 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4086 __FUNCTION__, static_cast<void *>(this), GetID());
4087
4088 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00004089 // will have already acquired the public_run_lock, and isn't done with what
4090 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004091 if (!is_secondary_thread)
4092 m_public_run_lock.SetStopped();
4093 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004094}
4095
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004096//------------------------------------------------------------------
4097// Process Event Data
4098//------------------------------------------------------------------
4099
Kate Stoneb9c1b512016-09-06 20:57:50 +00004100Process::ProcessEventData::ProcessEventData()
4101 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4102 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004103
Kate Stoneb9c1b512016-09-06 20:57:50 +00004104Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4105 StateType state)
4106 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4107 m_update_state(0), m_interrupted(false) {
4108 if (process_sp)
4109 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004110}
4111
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004112Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004113
Kate Stoneb9c1b512016-09-06 20:57:50 +00004114const ConstString &Process::ProcessEventData::GetFlavorString() {
4115 static ConstString g_flavor("Process::ProcessEventData");
4116 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004117}
4118
Kate Stoneb9c1b512016-09-06 20:57:50 +00004119const ConstString &Process::ProcessEventData::GetFlavor() const {
4120 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004121}
4122
Kate Stoneb9c1b512016-09-06 20:57:50 +00004123void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4124 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004125
Kate Stoneb9c1b512016-09-06 20:57:50 +00004126 if (!process_sp)
4127 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004128
Kate Stoneb9c1b512016-09-06 20:57:50 +00004129 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00004130 // pulled off of the private process event queue, and then any number of
4131 // times, first when it gets pulled off of the public event queue, then other
4132 // times when we're pretending that this is where we stopped at the end of
4133 // expression evaluation. m_update_state is used to distinguish these three
4134 // cases; it is 0 when we're just pulling it off for private handling, and >
4135 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00004136 // command handling then.
4137 if (m_update_state != 1)
4138 return;
4139
4140 process_sp->SetPublicState(
4141 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4142
Jason Molendab3a3cd12016-12-08 06:27:29 +00004143 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00004144 // Let process subclasses know we are about to do a public stop and do
4145 // anything they might need to in order to speed up register and memory
4146 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00004147 process_sp->WillPublicStop();
4148 }
4149
Kate Stoneb9c1b512016-09-06 20:57:50 +00004150 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00004151 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4152 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00004153 // end up restarting the process.
4154 if (m_interrupted)
4155 return;
4156
4157 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4158 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004159 ThreadList &curr_thread_list = process_sp->GetThreadList();
4160 uint32_t num_threads = curr_thread_list.GetSize();
4161 uint32_t idx;
4162
4163 // The actions might change one of the thread's stop_info's opinions about
Adrian Prantl05097242018-04-30 16:49:04 +00004164 // whether we should stop the process, so we need to query that as we go.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004165
4166 // One other complication here, is that we try to catch any case where the
Adrian Prantl05097242018-04-30 16:49:04 +00004167 // target has run (except for expressions) and immediately exit, but if we
4168 // get that wrong (which is possible) then the thread list might have
4169 // changed, and that would cause our iteration here to crash. We could
4170 // make a copy of the thread list, but we'd really like to also know if it
4171 // has changed at all, so we make up a vector of the thread ID's and check
4172 // what we get back against this list & bag out if anything differs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004173 std::vector<uint32_t> thread_index_array(num_threads);
4174 for (idx = 0; idx < num_threads; ++idx)
4175 thread_index_array[idx] =
4176 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4177
4178 // Use this to track whether we should continue from here. We will only
Adrian Prantl05097242018-04-30 16:49:04 +00004179 // continue the target running if no thread says we should stop. Of course
4180 // if some thread's PerformAction actually sets the target running, then it
4181 // doesn't matter what the other threads say...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004182
4183 bool still_should_stop = false;
4184
4185 // Sometimes - for instance if we have a bug in the stub we are talking to,
Adrian Prantl05097242018-04-30 16:49:04 +00004186 // we stop but no thread has a valid stop reason. In that case we should
4187 // just stop, because we have no way of telling what the right thing to do
4188 // is, and it's better to let the user decide than continue behind their
4189 // backs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004190
4191 bool does_anybody_have_an_opinion = false;
4192
4193 for (idx = 0; idx < num_threads; ++idx) {
4194 curr_thread_list = process_sp->GetThreadList();
4195 if (curr_thread_list.GetSize() != num_threads) {
4196 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4197 LIBLLDB_LOG_PROCESS));
4198 if (log)
4199 log->Printf(
4200 "Number of threads changed from %u to %u while processing event.",
4201 num_threads, curr_thread_list.GetSize());
4202 break;
4203 }
4204
4205 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4206
4207 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4208 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4209 LIBLLDB_LOG_PROCESS));
4210 if (log)
4211 log->Printf("The thread at position %u changed from %u to %u while "
4212 "processing event.",
4213 idx, thread_index_array[idx], thread_sp->GetIndexID());
4214 break;
4215 }
4216
4217 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4218 if (stop_info_sp && stop_info_sp->IsValid()) {
4219 does_anybody_have_an_opinion = true;
4220 bool this_thread_wants_to_stop;
4221 if (stop_info_sp->GetOverrideShouldStop()) {
4222 this_thread_wants_to_stop =
4223 stop_info_sp->GetOverriddenShouldStopValue();
4224 } else {
4225 stop_info_sp->PerformAction(event_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +00004226 // The stop action might restart the target. If it does, then we
4227 // want to mark that in the event so that whoever is receiving it
4228 // will know to wait for the running event and reflect that state
4229 // appropriately. We also need to stop processing actions, since they
4230 // aren't expecting the target to be running.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004231
4232 // FIXME: we might have run.
4233 if (stop_info_sp->HasTargetRunSinceMe()) {
4234 SetRestarted(true);
4235 break;
4236 }
4237
4238 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004239 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004240
4241 if (!still_should_stop)
4242 still_should_stop = this_thread_wants_to_stop;
4243 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004244 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004245
4246 if (!GetRestarted()) {
4247 if (!still_should_stop && does_anybody_have_an_opinion) {
4248 // We've been asked to continue, so do that here.
4249 SetRestarted(true);
Adrian Prantl05097242018-04-30 16:49:04 +00004250 // Use the public resume method here, since this is just extending a
4251 // public resume.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004252 process_sp->PrivateResume();
4253 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004254 // If we didn't restart, run the Stop Hooks here: They might also
4255 // restart the target, so watch for that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004256 process_sp->GetTarget().RunStopHooks();
4257 if (process_sp->GetPrivateState() == eStateRunning)
4258 SetRestarted(true);
4259 }
4260 }
4261 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004262}
4263
Kate Stoneb9c1b512016-09-06 20:57:50 +00004264void Process::ProcessEventData::Dump(Stream *s) const {
4265 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004266
Kate Stoneb9c1b512016-09-06 20:57:50 +00004267 if (process_sp)
4268 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4269 static_cast<void *>(process_sp.get()), process_sp->GetID());
4270 else
4271 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004272
Kate Stoneb9c1b512016-09-06 20:57:50 +00004273 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004274}
4275
4276const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004277Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4278 if (event_ptr) {
4279 const EventData *event_data = event_ptr->GetData();
4280 if (event_data &&
4281 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4282 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4283 }
4284 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004285}
4286
4287ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004288Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4289 ProcessSP process_sp;
4290 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4291 if (data)
4292 process_sp = data->GetProcessSP();
4293 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004294}
4295
Kate Stoneb9c1b512016-09-06 20:57:50 +00004296StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4297 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4298 if (data == nullptr)
4299 return eStateInvalid;
4300 else
4301 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004302}
4303
Kate Stoneb9c1b512016-09-06 20:57:50 +00004304bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4305 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4306 if (data == nullptr)
4307 return false;
4308 else
4309 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004310}
4311
Kate Stoneb9c1b512016-09-06 20:57:50 +00004312void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4313 bool new_value) {
4314 ProcessEventData *data =
4315 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4316 if (data != nullptr)
4317 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004318}
4319
Jim Ingham0161b492013-02-09 01:29:05 +00004320size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004321Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4322 ProcessEventData *data =
4323 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4324 if (data != nullptr)
4325 return data->GetNumRestartedReasons();
4326 else
4327 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004328}
4329
4330const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004331Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4332 size_t idx) {
4333 ProcessEventData *data =
4334 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4335 if (data != nullptr)
4336 return data->GetRestartedReasonAtIndex(idx);
4337 else
4338 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004339}
4340
Kate Stoneb9c1b512016-09-06 20:57:50 +00004341void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4342 const char *reason) {
4343 ProcessEventData *data =
4344 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4345 if (data != nullptr)
4346 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004347}
4348
Kate Stoneb9c1b512016-09-06 20:57:50 +00004349bool Process::ProcessEventData::GetInterruptedFromEvent(
4350 const Event *event_ptr) {
4351 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4352 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004353 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004354 else
4355 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004356}
4357
Kate Stoneb9c1b512016-09-06 20:57:50 +00004358void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4359 bool new_value) {
4360 ProcessEventData *data =
4361 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4362 if (data != nullptr)
4363 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004364}
4365
Kate Stoneb9c1b512016-09-06 20:57:50 +00004366bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4367 ProcessEventData *data =
4368 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4369 if (data) {
4370 data->SetUpdateStateOnRemoval();
4371 return true;
4372 }
4373 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004374}
4375
Kate Stoneb9c1b512016-09-06 20:57:50 +00004376lldb::TargetSP Process::CalculateTarget() { return m_target_sp.lock(); }
4377
4378void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4379 exe_ctx.SetTargetPtr(&GetTarget());
4380 exe_ctx.SetProcessPtr(this);
4381 exe_ctx.SetThreadPtr(nullptr);
4382 exe_ctx.SetFramePtr(nullptr);
4383}
4384
4385// uint32_t
4386// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4387// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004388//{
4389// return 0;
4390//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004391//
4392// ArchSpec
4393// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004394//{
4395// return Host::GetArchSpecForExistingProcess (pid);
4396//}
4397//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004398// ArchSpec
4399// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004400//{
4401// return Host::GetArchSpecForExistingProcess (process_name);
4402//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004403
Kate Stoneb9c1b512016-09-06 20:57:50 +00004404void Process::AppendSTDOUT(const char *s, size_t len) {
4405 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4406 m_stdout_data.append(s, len);
4407 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4408 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004409}
4410
Kate Stoneb9c1b512016-09-06 20:57:50 +00004411void Process::AppendSTDERR(const char *s, size_t len) {
4412 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4413 m_stderr_data.append(s, len);
4414 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4415 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004416}
4417
Kate Stoneb9c1b512016-09-06 20:57:50 +00004418void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4419 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4420 m_profile_data.push_back(one_profile_data);
4421 BroadcastEventIfUnique(eBroadcastBitProfileData,
4422 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004423}
4424
Kate Stoneb9c1b512016-09-06 20:57:50 +00004425void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4426 const StructuredDataPluginSP &plugin_sp) {
4427 BroadcastEvent(
4428 eBroadcastBitStructuredData,
4429 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004430}
4431
4432StructuredDataPluginSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004433Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4434 auto find_it = m_structured_data_plugin_map.find(type_name);
4435 if (find_it != m_structured_data_plugin_map.end())
4436 return find_it->second;
4437 else
4438 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004439}
4440
Zachary Turner97206d52017-05-12 04:51:55 +00004441size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004442 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4443 if (m_profile_data.empty())
4444 return 0;
4445
4446 std::string &one_profile_data = m_profile_data.front();
4447 size_t bytes_available = one_profile_data.size();
4448 if (bytes_available > 0) {
4449 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4450 if (log)
4451 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4452 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4453 if (bytes_available > buf_size) {
4454 memcpy(buf, one_profile_data.c_str(), buf_size);
4455 one_profile_data.erase(0, buf_size);
4456 bytes_available = buf_size;
4457 } else {
4458 memcpy(buf, one_profile_data.c_str(), bytes_available);
4459 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004460 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004461 }
4462 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004463}
4464
Greg Clayton93e86192011-11-13 04:45:22 +00004465//------------------------------------------------------------------
4466// Process STDIO
4467//------------------------------------------------------------------
4468
Zachary Turner97206d52017-05-12 04:51:55 +00004469size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004470 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4471 size_t bytes_available = m_stdout_data.size();
4472 if (bytes_available > 0) {
4473 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4474 if (log)
4475 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4476 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4477 if (bytes_available > buf_size) {
4478 memcpy(buf, m_stdout_data.c_str(), buf_size);
4479 m_stdout_data.erase(0, buf_size);
4480 bytes_available = buf_size;
4481 } else {
4482 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4483 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004484 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004485 }
4486 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004487}
4488
Zachary Turner97206d52017-05-12 04:51:55 +00004489size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004490 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4491 size_t bytes_available = m_stderr_data.size();
4492 if (bytes_available > 0) {
4493 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4494 if (log)
4495 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4496 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4497 if (bytes_available > buf_size) {
4498 memcpy(buf, m_stderr_data.c_str(), buf_size);
4499 m_stderr_data.erase(0, buf_size);
4500 bytes_available = buf_size;
4501 } else {
4502 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4503 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004504 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004505 }
4506 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004507}
4508
Kate Stoneb9c1b512016-09-06 20:57:50 +00004509void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4510 size_t src_len) {
4511 Process *process = (Process *)baton;
4512 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004513}
4514
Kate Stoneb9c1b512016-09-06 20:57:50 +00004515class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004516public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004517 IOHandlerProcessSTDIO(Process *process, int write_fd)
4518 : IOHandler(process->GetTarget().GetDebugger(),
4519 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004520 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004521 m_pipe.CreateNew(false);
4522 m_read_file.SetDescriptor(GetInputFD(), false);
4523 }
4524
4525 ~IOHandlerProcessSTDIO() override = default;
4526
Adrian Prantl05097242018-04-30 16:49:04 +00004527 // Each IOHandler gets to run until it is done. It should read data from the
4528 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004529 void Run() override {
4530 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4531 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4532 SetIsDone(true);
4533 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004534 }
4535
Kate Stoneb9c1b512016-09-06 20:57:50 +00004536 SetIsDone(false);
4537 const int read_fd = m_read_file.GetDescriptor();
4538 TerminalState terminal_state;
4539 terminal_state.Save(read_fd, false);
4540 Terminal terminal(read_fd);
4541 terminal.SetCanonical(false);
4542 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004543// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004544#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004545 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4546 m_is_running = true;
4547 while (!GetIsDone()) {
4548 SelectHelper select_helper;
4549 select_helper.FDSetRead(read_fd);
4550 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004551 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004552
Kate Stoneb9c1b512016-09-06 20:57:50 +00004553 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004554 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004555 } else {
4556 char ch = 0;
4557 size_t n;
4558 if (select_helper.FDIsSetRead(read_fd)) {
4559 n = 1;
4560 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4561 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4562 SetIsDone(true);
4563 } else
4564 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004565 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004566 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4567 size_t bytes_read;
4568 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004569 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004570 if (error.Success()) {
4571 switch (ch) {
4572 case 'q':
4573 SetIsDone(true);
4574 break;
4575 case 'i':
4576 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004577 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004578 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004579 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004580 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004582 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004583 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004584 m_is_running = false;
4585#endif
4586 terminal_state.Restore();
4587 }
4588
4589 void Cancel() override {
4590 SetIsDone(true);
4591 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004592 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4593 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004594 //
4595 // (lldb) step_process_thousands_of_times
4596 //
4597 // In this case the command interpreter will be in the middle of handling
4598 // the command and if the process pushes and pops the IOHandler thousands
4599 // of times, we can end up writing to m_pipe without ever consuming the
4600 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4601 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4602 if (m_is_running) {
4603 char ch = 'q'; // Send 'q' for quit
4604 size_t bytes_written = 0;
4605 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004606 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004607 }
4608
4609 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004610 // Do only things that are safe to do in an interrupt context (like in a
4611 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004612 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4613 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004614 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004615 if (m_active) {
4616 char ch = 'i'; // Send 'i' for interrupt
4617 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004618 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004619 return result.Success();
4620 } else {
4621 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004622 // currently so do the right thing if we aren't actively watching for
4623 // STDIN by sending the interrupt to the process. Otherwise the write to
4624 // the pipe above would do nothing. This can happen when the command
4625 // interpreter is running and gets a "expression ...". It will be on the
4626 // IOHandler thread and sending the input is complete to the delegate
4627 // which will cause the expression to run, which will push the process IO
4628 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004629
4630 if (StateIsRunningState(m_process->GetState())) {
4631 m_process->SendAsyncInterrupt();
4632 return true;
4633 }
4634 }
4635 return false;
4636 }
4637
4638 void GotEOF() override {}
4639
Greg Clayton44d93782014-01-27 23:43:24 +00004640protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004641 Process *m_process;
4642 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4643 File m_write_file; // Write to this file (usually the master pty for getting
4644 // io to debuggee)
4645 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004646 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004647};
4648
Kate Stoneb9c1b512016-09-06 20:57:50 +00004649void Process::SetSTDIOFileDescriptor(int fd) {
4650 // First set up the Read Thread for reading/handling process I/O
4651
4652 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4653 new ConnectionFileDescriptor(fd, true));
4654
4655 if (conn_ap) {
4656 m_stdio_communication.SetConnection(conn_ap.release());
4657 if (m_stdio_communication.IsConnected()) {
4658 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4659 STDIOReadThreadBytesReceived, this);
4660 m_stdio_communication.StartReadThread();
4661
4662 // Now read thread is set up, set up input reader.
4663
4664 if (!m_process_input_reader)
4665 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004666 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004667 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004668}
4669
Kate Stoneb9c1b512016-09-06 20:57:50 +00004670bool Process::ProcessIOHandlerIsActive() {
4671 IOHandlerSP io_handler_sp(m_process_input_reader);
4672 if (io_handler_sp)
4673 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4674 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004675}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004676bool Process::PushProcessIOHandler() {
4677 IOHandlerSP io_handler_sp(m_process_input_reader);
4678 if (io_handler_sp) {
4679 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4680 if (log)
4681 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004682
Kate Stoneb9c1b512016-09-06 20:57:50 +00004683 io_handler_sp->SetIsDone(false);
4684 GetTarget().GetDebugger().PushIOHandler(io_handler_sp);
4685 return true;
4686 }
4687 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004688}
4689
Kate Stoneb9c1b512016-09-06 20:57:50 +00004690bool Process::PopProcessIOHandler() {
4691 IOHandlerSP io_handler_sp(m_process_input_reader);
4692 if (io_handler_sp)
4693 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4694 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004695}
4696
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004697// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004698void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004699
Kate Stoneb9c1b512016-09-06 20:57:50 +00004700void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004701
Kate Stoneb9c1b512016-09-06 20:57:50 +00004702namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004703// RestorePlanState is used to record the "is private", "is master" and "okay
4704// to discard" fields of the plan we are running, and reset it on Clean or on
4705// destruction. It will only reset the state once, so you can call Clean and
4706// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004707
Kate Stoneb9c1b512016-09-06 20:57:50 +00004708class RestorePlanState {
4709public:
4710 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4711 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4712 if (m_thread_plan_sp) {
4713 m_private = m_thread_plan_sp->GetPrivate();
4714 m_is_master = m_thread_plan_sp->IsMasterPlan();
4715 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4716 }
4717 }
4718
4719 ~RestorePlanState() { Clean(); }
4720
4721 void Clean() {
4722 if (!m_already_reset && m_thread_plan_sp) {
4723 m_already_reset = true;
4724 m_thread_plan_sp->SetPrivate(m_private);
4725 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4726 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4727 }
4728 }
4729
4730private:
4731 lldb::ThreadPlanSP m_thread_plan_sp;
4732 bool m_already_reset;
4733 bool m_private;
4734 bool m_is_master;
4735 bool m_okay_to_discard;
4736};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004737} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004738
Pavel Labath2ce22162016-12-01 10:57:30 +00004739static microseconds
4740GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4741 const milliseconds default_one_thread_timeout(250);
4742
4743 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004744 if (!options.GetTimeout()) {
4745 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4746 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004747 }
4748
4749 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004750 if (options.GetOneThreadTimeout())
4751 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004752
4753 // Otherwise use half the total timeout, bounded by the
4754 // default_one_thread_timeout.
4755 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004756 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004757}
4758
4759static Timeout<std::micro>
4760GetExpressionTimeout(const EvaluateExpressionOptions &options,
4761 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004762 // If we are going to run all threads the whole time, or if we are only going
4763 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004764 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004765 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004766
4767 if (before_first_timeout)
4768 return GetOneThreadExpressionTimeout(options);
4769
Pavel Labath43d35412016-12-06 11:24:51 +00004770 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004771 return llvm::None;
4772 else
Pavel Labath43d35412016-12-06 11:24:51 +00004773 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004774}
4775
Pavel Labath45dde232017-05-25 10:50:06 +00004776static llvm::Optional<ExpressionResults>
4777HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4778 RestorePlanState &restorer, const EventSP &event_sp,
4779 EventSP &event_to_broadcast_sp,
4780 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4781 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4782
4783 ThreadPlanSP plan = thread.GetCompletedPlan();
4784 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4785 LLDB_LOG(log, "execution completed successfully");
4786
4787 // Restore the plan state so it will get reported as intended when we are
4788 // done.
4789 restorer.Clean();
4790 return eExpressionCompleted;
4791 }
4792
4793 StopInfoSP stop_info_sp = thread.GetStopInfo();
4794 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4795 stop_info_sp->ShouldNotify(event_sp.get())) {
4796 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4797 if (!options.DoesIgnoreBreakpoints()) {
4798 // Restore the plan state and then force Private to false. We are going
4799 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004800 // it won't report correctly when we continue to its termination later
4801 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004802 restorer.Clean();
4803 thread_plan_sp->SetPrivate(false);
4804 event_to_broadcast_sp = event_sp;
4805 }
4806 return eExpressionHitBreakpoint;
4807 }
4808
4809 if (!handle_interrupts &&
4810 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4811 return llvm::None;
4812
4813 LLDB_LOG(log, "thread plan did not successfully complete");
4814 if (!options.DoesUnwindOnError())
4815 event_to_broadcast_sp = event_sp;
4816 return eExpressionInterrupted;
4817}
4818
Jim Ingham1624a2d2014-05-05 02:26:40 +00004819ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004820Process::RunThreadPlan(ExecutionContext &exe_ctx,
4821 lldb::ThreadPlanSP &thread_plan_sp,
4822 const EvaluateExpressionOptions &options,
4823 DiagnosticManager &diagnostic_manager) {
4824 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004825
Kate Stoneb9c1b512016-09-06 20:57:50 +00004826 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4827
4828 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004829 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004830 eDiagnosticSeverityError,
4831 "RunThreadPlan called with empty thread plan.");
4832 return eExpressionSetupError;
4833 }
4834
4835 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004836 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004837 eDiagnosticSeverityError,
4838 "RunThreadPlan called with an invalid thread plan.");
4839 return eExpressionSetupError;
4840 }
4841
4842 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004843 diagnostic_manager.PutString(eDiagnosticSeverityError,
4844 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004845 return eExpressionSetupError;
4846 }
4847
4848 Thread *thread = exe_ctx.GetThreadPtr();
4849 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004850 diagnostic_manager.PutString(eDiagnosticSeverityError,
4851 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004852 return eExpressionSetupError;
4853 }
4854
4855 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004856 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004857
4858 RestorePlanState thread_plan_restorer(thread_plan_sp);
4859
Adrian Prantl05097242018-04-30 16:49:04 +00004860 // We rely on the thread plan we are running returning "PlanCompleted" if
4861 // when it successfully completes. For that to be true the plan can't be
4862 // private - since private plans suppress themselves in the GetCompletedPlan
4863 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004864
4865 thread_plan_sp->SetPrivate(false);
4866
4867 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004868 // when they are done we will end up asking the plan above us whether we
4869 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004870
4871 thread_plan_sp->SetIsMasterPlan(true);
4872 thread_plan_sp->SetOkayToDiscard(false);
4873
4874 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004875 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004876 eDiagnosticSeverityError,
4877 "RunThreadPlan called while the private state was not stopped.");
4878 return eExpressionSetupError;
4879 }
4880
4881 // Save the thread & frame from the exe_ctx for restoration after we run
4882 const uint32_t thread_idx_id = thread->GetIndexID();
4883 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4884 if (!selected_frame_sp) {
4885 thread->SetSelectedFrame(nullptr);
4886 selected_frame_sp = thread->GetSelectedFrame();
4887 if (!selected_frame_sp) {
4888 diagnostic_manager.Printf(
4889 eDiagnosticSeverityError,
4890 "RunThreadPlan called without a selected frame on thread %d",
4891 thread_idx_id);
4892 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004893 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004894 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004895
Adrian Prantl05097242018-04-30 16:49:04 +00004896 // Make sure the timeout values make sense. The one thread timeout needs to
4897 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004898 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4899 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004900 diagnostic_manager.PutString(eDiagnosticSeverityError,
4901 "RunThreadPlan called with one thread "
4902 "timeout greater than total timeout");
4903 return eExpressionSetupError;
4904 }
4905
Kate Stoneb9c1b512016-09-06 20:57:50 +00004906 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004907
Kate Stoneb9c1b512016-09-06 20:57:50 +00004908 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004909 // We don't want to do that either, so we should arrange to reset them as
4910 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004911
Kate Stoneb9c1b512016-09-06 20:57:50 +00004912 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004913
Kate Stoneb9c1b512016-09-06 20:57:50 +00004914 uint32_t selected_tid;
4915 StackID selected_stack_id;
4916 if (selected_thread_sp) {
4917 selected_tid = selected_thread_sp->GetIndexID();
4918 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4919 } else {
4920 selected_tid = LLDB_INVALID_THREAD_ID;
4921 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004922
Kate Stoneb9c1b512016-09-06 20:57:50 +00004923 HostThread backup_private_state_thread;
4924 lldb::StateType old_state = eStateInvalid;
4925 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004926
Kate Stoneb9c1b512016-09-06 20:57:50 +00004927 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4928 LIBLLDB_LOG_PROCESS));
4929 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4930 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004931 // public events on this thread, since we are the thread that is generating
4932 // public events. The simplest thing to do is to spin up a temporary thread
4933 // to handle private state thread events while we are fielding public
4934 // events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004935 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004936 log->Printf("Running thread plan on private state thread, spinning up "
4937 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004938
Kate Stoneb9c1b512016-09-06 20:57:50 +00004939 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004940
Kate Stoneb9c1b512016-09-06 20:57:50 +00004941 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004942 // anything it pushes, and then stop, returning control here. But in the
4943 // normal course of things, the plan above us on the stack would be given a
4944 // shot at the stop event before deciding to stop, and we don't want that.
4945 // So we insert a "stopper" base plan on the stack before the plan we want
4946 // to run. Since base plans always stop and return control to the user,
4947 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004948 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4949 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4950 // Have to make sure our public state is stopped, since otherwise the
4951 // reporting logic below doesn't work correctly.
4952 old_state = m_public_state.GetValue();
4953 m_public_state.SetValueNoLock(eStateStopped);
4954
4955 // Now spin up the private state thread:
4956 StartPrivateStateThread(true);
4957 }
4958
4959 thread->QueueThreadPlan(
4960 thread_plan_sp, false); // This used to pass "true" does that make sense?
4961
4962 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004963 // In this case, we aren't actually going to run, we just want to stop
4964 // right away. Flush this thread so we will refetch the stacks and show the
4965 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004966 // FIXME: To make this prettier we should invent some stop reason for this,
4967 // but that
4968 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004969 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004970 thread->Flush();
4971 return eExpressionStoppedForDebug;
4972 }
4973
4974 ListenerSP listener_sp(
4975 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4976
4977 lldb::EventSP event_to_broadcast_sp;
4978
4979 {
4980 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004981 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004982 //
4983 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004984 // exits during execution), then the event is put into
4985 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004986
4987 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4988
4989 if (log) {
4990 StreamString s;
4991 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4992 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4993 " to run thread plan \"%s\".",
4994 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004995 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004996
4997 bool got_event;
4998 lldb::EventSP event_sp;
4999 lldb::StateType stop_state = lldb::eStateInvalid;
5000
5001 bool before_first_timeout = true; // This is set to false the first time
5002 // that we have to halt the target.
5003 bool do_resume = true;
5004 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005005
5006 // This is just for accounting:
5007 uint32_t num_resumes = 0;
5008
Kate Stoneb9c1b512016-09-06 20:57:50 +00005009 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00005010 // going to run one thread, then we don't need the first timeout. So we
5011 // pretend we are after the first timeout already.
5012 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00005013 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005014
Kate Stoneb9c1b512016-09-06 20:57:50 +00005015 if (log)
Pavel Labath2ce22162016-12-01 10:57:30 +00005016 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
5017 options.GetStopOthers(), options.GetTryAllThreads(),
5018 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005019
Adrian Prantl05097242018-04-30 16:49:04 +00005020 // This isn't going to work if there are unfetched events on the queue. Are
5021 // there cases where we might want to run the remaining events here, and
5022 // then try to call the function? That's probably being too tricky for our
5023 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005024
5025 Event *other_events = listener_sp->PeekAtNextEvent();
5026 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00005027 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005028 eDiagnosticSeverityError,
5029 "RunThreadPlan called with pending events on the queue.");
5030 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00005031 }
5032
Kate Stoneb9c1b512016-09-06 20:57:50 +00005033 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00005034 // calling a function as part of a thread plan, in which case the last
5035 // delivered event could be the running event, and we don't want event
5036 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00005037 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00005038
Kate Stoneb9c1b512016-09-06 20:57:50 +00005039// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00005040// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00005041
Kate Stoneb9c1b512016-09-06 20:57:50 +00005042#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00005043 // It's pretty much impossible to write test cases for things like: One
5044 // thread timeout expires, I go to halt, but the process already stopped on
5045 // the function call stop breakpoint. Turning on this define will make us
5046 // not fetch the first event till after the halt. So if you run a quick
5047 // function, it will have completed, and the completion event will be
5048 // waiting, when you interrupt for halt. The expression evaluation should
5049 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005050 bool miss_first_event = true;
5051#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00005052 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00005053 // We usually want to resume the process if we get to the top of the
5054 // loop. The only exception is if we get two running events with no
5055 // intervening stop, which can happen, we will just wait for then next
5056 // stop event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005057 if (log)
5058 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5059 "before_first_timeout: %i.",
5060 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00005061
Kate Stoneb9c1b512016-09-06 20:57:50 +00005062 if (do_resume || handle_running_event) {
5063 // Do the initial resume and wait for the running event before going
5064 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00005065
Kate Stoneb9c1b512016-09-06 20:57:50 +00005066 if (do_resume) {
5067 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00005068 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005069 if (!resume_error.Success()) {
5070 diagnostic_manager.Printf(
5071 eDiagnosticSeverityError,
5072 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5073 resume_error.AsCString());
5074 return_value = eExpressionSetupError;
5075 break;
5076 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005077 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005078
Pavel Labathd35031e12016-11-30 10:41:42 +00005079 got_event =
5080 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005081 if (!got_event) {
5082 if (log)
5083 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5084 "resume %" PRIu32 ", exiting.",
5085 num_resumes);
5086
5087 diagnostic_manager.Printf(eDiagnosticSeverityError,
5088 "didn't get any event after resume %" PRIu32
5089 ", exiting.",
5090 num_resumes);
5091 return_value = eExpressionSetupError;
5092 break;
5093 }
5094
5095 stop_state =
5096 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5097
5098 if (stop_state != eStateRunning) {
5099 bool restarted = false;
5100
5101 if (stop_state == eStateStopped) {
5102 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5103 event_sp.get());
5104 if (log)
5105 log->Printf(
5106 "Process::RunThreadPlan(): didn't get running event after "
5107 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5108 "handle_running_event: %i).",
5109 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5110 handle_running_event);
5111 }
5112
5113 if (restarted) {
5114 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00005115 // should ever get a stopped & restarted event here. But if I do,
5116 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005117 const bool clear_thread_plans = false;
5118 const bool use_run_lock = false;
5119 Halt(clear_thread_plans, use_run_lock);
5120 }
5121
5122 diagnostic_manager.Printf(
5123 eDiagnosticSeverityError,
5124 "didn't get running event after initial resume, got %s instead.",
5125 StateAsCString(stop_state));
5126 return_value = eExpressionSetupError;
5127 break;
5128 }
5129
5130 if (log)
5131 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00005132 // We need to call the function synchronously, so spin waiting for it
5133 // to return. If we get interrupted while executing, we're going to
5134 // lose our context, and won't be able to gather the result at this
5135 // point. We set the timeout AFTER the resume, since the resume takes
5136 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005137 } else {
5138 if (log)
5139 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5140 }
5141
Kate Stoneb9c1b512016-09-06 20:57:50 +00005142 do_resume = true;
5143 handle_running_event = true;
5144
5145 // Now wait for the process to stop again:
5146 event_sp.reset();
5147
Pavel Labath2ce22162016-12-01 10:57:30 +00005148 Timeout<std::micro> timeout =
5149 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005150 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005151 if (timeout) {
5152 auto now = system_clock::now();
5153 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
5154 "endpoint is %s",
5155 llvm::to_string(now).c_str(),
5156 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005157 } else {
5158 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005159 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005160 }
5161
5162#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5163 // See comment above...
5164 if (miss_first_event) {
5165 usleep(1000);
5166 miss_first_event = false;
5167 got_event = false;
5168 } else
5169#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005170 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005171
5172 if (got_event) {
5173 if (event_sp) {
5174 bool keep_going = false;
5175 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5176 const bool clear_thread_plans = false;
5177 const bool use_run_lock = false;
5178 Halt(clear_thread_plans, use_run_lock);
5179 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005180 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5181 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005182 if (log)
5183 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5184 "eBroadcastBitInterrupted, exiting.");
5185 break;
5186 } else {
5187 stop_state =
5188 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5189 if (log)
5190 log->Printf(
5191 "Process::RunThreadPlan(): in while loop, got event: %s.",
5192 StateAsCString(stop_state));
5193
5194 switch (stop_state) {
5195 case lldb::eStateStopped: {
5196 // We stopped, figure out what we are going to do now.
5197 ThreadSP thread_sp =
5198 GetThreadList().FindThreadByIndexID(thread_idx_id);
5199 if (!thread_sp) {
5200 // Ooh, our thread has vanished. Unlikely that this was
5201 // successful execution...
5202 if (log)
5203 log->Printf("Process::RunThreadPlan(): execution completed "
5204 "but our thread (index-id=%u) has vanished.",
5205 thread_idx_id);
5206 return_value = eExpressionInterrupted;
Pavel Labath45dde232017-05-25 10:50:06 +00005207 } else if (Process::ProcessEventData::GetRestartedFromEvent(
5208 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005209 // If we were restarted, we just need to go back up to fetch
5210 // another event.
Pavel Labath45dde232017-05-25 10:50:06 +00005211 if (log) {
5212 log->Printf("Process::RunThreadPlan(): Got a stop and "
5213 "restart, so we'll continue waiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005214 }
Pavel Labath45dde232017-05-25 10:50:06 +00005215 keep_going = true;
5216 do_resume = false;
5217 handle_running_event = true;
5218 } else {
5219 const bool handle_interrupts = true;
5220 return_value = *HandleStoppedEvent(
5221 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5222 event_to_broadcast_sp, options, handle_interrupts);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005223 }
5224 } break;
5225
5226 case lldb::eStateRunning:
5227 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005228 // running events without an intervening stop, and in that case
5229 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005230 do_resume = false;
5231 keep_going = true;
5232 handle_running_event = false;
5233 break;
5234
5235 default:
5236 if (log)
5237 log->Printf("Process::RunThreadPlan(): execution stopped with "
5238 "unexpected state: %s.",
5239 StateAsCString(stop_state));
5240
5241 if (stop_state == eStateExited)
5242 event_to_broadcast_sp = event_sp;
5243
Zachary Turnere2411fa2016-11-12 19:12:56 +00005244 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005245 eDiagnosticSeverityError,
5246 "execution stopped with unexpected state.");
5247 return_value = eExpressionInterrupted;
5248 break;
5249 }
5250 }
5251
5252 if (keep_going)
5253 continue;
5254 else
5255 break;
5256 } else {
5257 if (log)
5258 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5259 "the event pointer was null. How odd...");
5260 return_value = eExpressionInterrupted;
5261 break;
5262 }
5263 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005264 // If we didn't get an event that means we've timed out... We will
5265 // interrupt the process here. Depending on what we were asked to do
5266 // we will either exit, or try with all threads running for the same
5267 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005268
5269 if (log) {
5270 if (options.GetTryAllThreads()) {
5271 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005272 LLDB_LOG(log,
5273 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005274 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005275 LLDB_LOG(log, "Restarting function with all threads enabled and "
5276 "timeout: {0} timed out, abandoning execution.",
5277 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005278 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005279 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5280 "abandoning execution.",
5281 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005282 }
5283
5284 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005285 // around to calling Halt the target could have stopped. That's fine,
5286 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005287 // BUT it is also possible that we stopped & restarted (e.g. hit a
5288 // signal with "stop" set to false.) In
5289 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005290 // back to waiting for the Halt's stopped event. That's what this
5291 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005292
5293 bool back_to_top = true;
5294 uint32_t try_halt_again = 0;
5295 bool do_halt = true;
5296 const uint32_t num_retries = 5;
5297 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005298 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005299 if (do_halt) {
5300 if (log)
5301 log->Printf("Process::RunThreadPlan(): Running Halt.");
5302 const bool clear_thread_plans = false;
5303 const bool use_run_lock = false;
5304 Halt(clear_thread_plans, use_run_lock);
5305 }
5306 if (halt_error.Success()) {
5307 if (log)
5308 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5309
Pavel Labathd35031e12016-11-30 10:41:42 +00005310 got_event =
5311 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005312
5313 if (got_event) {
5314 stop_state =
5315 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5316 if (log) {
5317 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5318 StateAsCString(stop_state));
5319 if (stop_state == lldb::eStateStopped &&
5320 Process::ProcessEventData::GetInterruptedFromEvent(
5321 event_sp.get()))
5322 log->PutCString(" Event was the Halt interruption event.");
5323 }
5324
5325 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005326 if (Process::ProcessEventData::GetRestartedFromEvent(
5327 event_sp.get())) {
5328 if (log)
5329 log->PutCString("Process::RunThreadPlan(): Went to halt "
5330 "but got a restarted event, there must be "
5331 "an un-restarted stopped event so try "
5332 "again... "
5333 "Exiting wait loop.");
5334 try_halt_again++;
5335 do_halt = false;
5336 continue;
5337 }
5338
Pavel Labath45dde232017-05-25 10:50:06 +00005339 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005340 // delivered it, the process could have already finished its
5341 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005342 const bool handle_interrupts = false;
5343 if (auto result = HandleStoppedEvent(
5344 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5345 event_to_broadcast_sp, options, handle_interrupts)) {
5346 return_value = *result;
5347 back_to_top = false;
5348 break;
5349 }
5350
Kate Stoneb9c1b512016-09-06 20:57:50 +00005351 if (!options.GetTryAllThreads()) {
5352 if (log)
5353 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5354 "was false, we stopped so now we're "
5355 "quitting.");
5356 return_value = eExpressionInterrupted;
5357 back_to_top = false;
5358 break;
5359 }
5360
5361 if (before_first_timeout) {
5362 // Set all the other threads to run, and return to the top of
5363 // the loop, which will continue;
5364 before_first_timeout = false;
5365 thread_plan_sp->SetStopOthers(false);
5366 if (log)
5367 log->PutCString(
5368 "Process::RunThreadPlan(): about to resume.");
5369
5370 back_to_top = true;
5371 break;
5372 } else {
5373 // Running all threads failed, so return Interrupted.
5374 if (log)
5375 log->PutCString("Process::RunThreadPlan(): running all "
5376 "threads timed out.");
5377 return_value = eExpressionInterrupted;
5378 back_to_top = false;
5379 break;
5380 }
5381 }
5382 } else {
5383 if (log)
5384 log->PutCString("Process::RunThreadPlan(): halt said it "
5385 "succeeded, but I got no event. "
5386 "I'm getting out of here passing Interrupted.");
5387 return_value = eExpressionInterrupted;
5388 back_to_top = false;
5389 break;
5390 }
5391 } else {
5392 try_halt_again++;
5393 continue;
5394 }
5395 }
5396
5397 if (!back_to_top || try_halt_again > num_retries)
5398 break;
5399 else
5400 continue;
5401 }
5402 } // END WAIT LOOP
5403
Adrian Prantl05097242018-04-30 16:49:04 +00005404 // If we had to start up a temporary private state thread to run this
5405 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005406 if (backup_private_state_thread.IsJoinable()) {
5407 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005408 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005409 m_private_state_thread = backup_private_state_thread;
5410 if (stopper_base_plan_sp) {
5411 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5412 }
5413 if (old_state != eStateInvalid)
5414 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005415 }
5416
Kate Stoneb9c1b512016-09-06 20:57:50 +00005417 if (return_value != eExpressionCompleted && log) {
5418 // Print a backtrace into the log so we can figure out where we are:
5419 StreamString s;
5420 s.PutCString("Thread state after unsuccessful completion: \n");
5421 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005422 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005423 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005424 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005425 // There are three cases where this could happen: 1) The execution
5426 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5427 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005428 bool should_unwind = (return_value == eExpressionInterrupted &&
5429 options.DoesUnwindOnError()) ||
5430 (return_value == eExpressionHitBreakpoint &&
5431 options.DoesIgnoreBreakpoints());
5432
5433 if (return_value == eExpressionCompleted || should_unwind) {
5434 thread_plan_sp->RestoreThreadState();
5435 }
5436
5437 // Now do some processing on the results of the run:
5438 if (return_value == eExpressionInterrupted ||
5439 return_value == eExpressionHitBreakpoint) {
5440 if (log) {
5441 StreamString s;
5442 if (event_sp)
5443 event_sp->Dump(&s);
5444 else {
5445 log->PutCString("Process::RunThreadPlan(): Stop event that "
5446 "interrupted us is NULL.");
5447 }
5448
5449 StreamString ts;
5450
5451 const char *event_explanation = nullptr;
5452
5453 do {
5454 if (!event_sp) {
5455 event_explanation = "<no event>";
5456 break;
5457 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5458 event_explanation = "<user interrupt>";
5459 break;
5460 } else {
5461 const Process::ProcessEventData *event_data =
5462 Process::ProcessEventData::GetEventDataFromEvent(
5463 event_sp.get());
5464
5465 if (!event_data) {
5466 event_explanation = "<no event data>";
5467 break;
5468 }
5469
5470 Process *process = event_data->GetProcessSP().get();
5471
5472 if (!process) {
5473 event_explanation = "<no process>";
5474 break;
5475 }
5476
5477 ThreadList &thread_list = process->GetThreadList();
5478
5479 uint32_t num_threads = thread_list.GetSize();
5480 uint32_t thread_index;
5481
5482 ts.Printf("<%u threads> ", num_threads);
5483
5484 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5485 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5486
5487 if (!thread) {
5488 ts.Printf("<?> ");
5489 continue;
5490 }
5491
5492 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5493 RegisterContext *register_context =
5494 thread->GetRegisterContext().get();
5495
5496 if (register_context)
5497 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5498 else
5499 ts.Printf("[ip unknown] ");
5500
5501 // Show the private stop info here, the public stop info will be
5502 // from the last natural stop.
5503 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5504 if (stop_info_sp) {
5505 const char *stop_desc = stop_info_sp->GetDescription();
5506 if (stop_desc)
5507 ts.PutCString(stop_desc);
5508 }
5509 ts.Printf(">");
5510 }
5511
5512 event_explanation = ts.GetData();
5513 }
5514 } while (0);
5515
5516 if (event_explanation)
5517 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5518 s.GetData(), event_explanation);
5519 else
5520 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5521 s.GetData());
5522 }
5523
5524 if (should_unwind) {
5525 if (log)
5526 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5527 "discarding thread plans up to %p.",
5528 static_cast<void *>(thread_plan_sp.get()));
5529 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5530 } else {
5531 if (log)
5532 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5533 "plan: %p not discarding.",
5534 static_cast<void *>(thread_plan_sp.get()));
5535 }
5536 } else if (return_value == eExpressionSetupError) {
5537 if (log)
5538 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5539
5540 if (options.DoesUnwindOnError()) {
5541 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5542 }
5543 } else {
5544 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5545 if (log)
5546 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5547 return_value = eExpressionCompleted;
5548 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5549 if (log)
5550 log->PutCString(
5551 "Process::RunThreadPlan(): thread plan was discarded");
5552 return_value = eExpressionDiscarded;
5553 } else {
5554 if (log)
5555 log->PutCString(
5556 "Process::RunThreadPlan(): thread plan stopped in mid course");
5557 if (options.DoesUnwindOnError() && thread_plan_sp) {
5558 if (log)
5559 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5560 "'cause unwind_on_error is set.");
5561 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5562 }
5563 }
5564 }
5565
5566 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005567 // target Check that it's still there, and if it is put it back in the
5568 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005569 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5570 if (thread) {
5571 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5572 }
5573
5574 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005575 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005576
5577 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5578 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5579 selected_stack_id.IsValid()) {
5580 // We were able to restore the selected thread, now restore the frame:
5581 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5582 StackFrameSP old_frame_sp =
5583 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5584 selected_stack_id);
5585 if (old_frame_sp)
5586 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5587 old_frame_sp.get());
5588 }
5589 }
5590 }
5591
5592 // If the process exited during the run of the thread plan, notify everyone.
5593
5594 if (event_to_broadcast_sp) {
5595 if (log)
5596 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5597 BroadcastEvent(event_to_broadcast_sp);
5598 }
5599
5600 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005601}
5602
Kate Stoneb9c1b512016-09-06 20:57:50 +00005603const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5604 const char *result_name;
5605
5606 switch (result) {
5607 case eExpressionCompleted:
5608 result_name = "eExpressionCompleted";
5609 break;
5610 case eExpressionDiscarded:
5611 result_name = "eExpressionDiscarded";
5612 break;
5613 case eExpressionInterrupted:
5614 result_name = "eExpressionInterrupted";
5615 break;
5616 case eExpressionHitBreakpoint:
5617 result_name = "eExpressionHitBreakpoint";
5618 break;
5619 case eExpressionSetupError:
5620 result_name = "eExpressionSetupError";
5621 break;
5622 case eExpressionParseError:
5623 result_name = "eExpressionParseError";
5624 break;
5625 case eExpressionResultUnavailable:
5626 result_name = "eExpressionResultUnavailable";
5627 break;
5628 case eExpressionTimedOut:
5629 result_name = "eExpressionTimedOut";
5630 break;
5631 case eExpressionStoppedForDebug:
5632 result_name = "eExpressionStoppedForDebug";
5633 break;
5634 }
5635 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005636}
5637
Kate Stoneb9c1b512016-09-06 20:57:50 +00005638void Process::GetStatus(Stream &strm) {
5639 const StateType state = GetState();
5640 if (StateIsStoppedState(state, false)) {
5641 if (state == eStateExited) {
5642 int exit_status = GetExitStatus();
5643 const char *exit_description = GetExitDescription();
5644 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5645 GetID(), exit_status, exit_status,
5646 exit_description ? exit_description : "");
5647 } else {
5648 if (state == eStateConnected)
5649 strm.Printf("Connected to remote target.\n");
5650 else
5651 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5652 }
5653 } else {
5654 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5655 }
Pavel Labatha933d512016-04-05 13:07:16 +00005656}
5657
Kate Stoneb9c1b512016-09-06 20:57:50 +00005658size_t Process::GetThreadStatus(Stream &strm,
5659 bool only_threads_with_stop_reason,
5660 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005661 uint32_t num_frames_with_source,
5662 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005663 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005664
Kate Stoneb9c1b512016-09-06 20:57:50 +00005665 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005666 // very well might run code (e.g. if we need it to get return values or
5667 // arguments.) For that to work the process has to be able to acquire it.
5668 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005669
5670 uint32_t num_threads;
5671 std::vector<lldb::tid_t> thread_id_array;
5672 // Scope for thread list locker;
5673 {
5674 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5675 ThreadList &curr_thread_list = GetThreadList();
5676 num_threads = curr_thread_list.GetSize();
5677 uint32_t idx;
5678 thread_id_array.resize(num_threads);
5679 for (idx = 0; idx < num_threads; ++idx)
5680 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5681 }
5682
5683 for (uint32_t i = 0; i < num_threads; i++) {
5684 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5685 if (thread_sp) {
5686 if (only_threads_with_stop_reason) {
5687 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5688 if (!stop_info_sp || !stop_info_sp->IsValid())
5689 continue;
5690 }
5691 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005692 num_frames_with_source,
5693 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005694 ++num_thread_infos_dumped;
5695 } else {
5696 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5697 if (log)
5698 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5699 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005700 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005701 }
5702 return num_thread_infos_dumped;
5703}
5704
5705void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5706 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5707}
5708
5709bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5710 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5711 region.GetByteSize());
5712}
5713
5714void Process::AddPreResumeAction(PreResumeActionCallback callback,
5715 void *baton) {
5716 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5717}
5718
5719bool Process::RunPreResumeActions() {
5720 bool result = true;
5721 while (!m_pre_resume_actions.empty()) {
5722 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5723 m_pre_resume_actions.pop_back();
5724 bool this_result = action.callback(action.baton);
5725 if (result)
5726 result = this_result;
5727 }
5728 return result;
5729}
5730
5731void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5732
Jim Inghamffd91752016-10-20 22:50:00 +00005733void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5734{
5735 PreResumeCallbackAndBaton element(callback, baton);
5736 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5737 if (found_iter != m_pre_resume_actions.end())
5738 {
5739 m_pre_resume_actions.erase(found_iter);
5740 }
5741}
5742
Kate Stoneb9c1b512016-09-06 20:57:50 +00005743ProcessRunLock &Process::GetRunLock() {
5744 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5745 return m_private_run_lock;
5746 else
5747 return m_public_run_lock;
5748}
5749
5750void Process::Flush() {
5751 m_thread_list.Flush();
5752 m_extended_thread_list.Flush();
5753 m_extended_thread_stop_id = 0;
5754 m_queue_list.Clear();
5755 m_queue_list_stop_id = 0;
5756}
5757
5758void Process::DidExec() {
5759 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5760 if (log)
5761 log->Printf("Process::%s()", __FUNCTION__);
5762
5763 Target &target = GetTarget();
5764 target.CleanupProcess();
5765 target.ClearModules(false);
5766 m_dynamic_checkers_ap.reset();
5767 m_abi_sp.reset();
5768 m_system_runtime_ap.reset();
5769 m_os_ap.reset();
5770 m_dyld_ap.reset();
5771 m_jit_loaders_ap.reset();
5772 m_image_tokens.clear();
5773 m_allocated_memory_cache.Clear();
5774 m_language_runtimes.clear();
5775 m_instrumentation_runtimes.clear();
5776 m_thread_list.DiscardThreadPlans();
5777 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005778 DoDidExec();
5779 CompleteAttach();
5780 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005781 // CompleteAttach() in case the dynamic loader loaded things in new
5782 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005783 Flush();
5784
Adrian Prantl05097242018-04-30 16:49:04 +00005785 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5786 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005787 target.DidExec();
5788}
5789
Zachary Turner97206d52017-05-12 04:51:55 +00005790addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005791 if (address == nullptr) {
5792 error.SetErrorString("Invalid address argument");
5793 return LLDB_INVALID_ADDRESS;
5794 }
5795
5796 addr_t function_addr = LLDB_INVALID_ADDRESS;
5797
5798 addr_t addr = address->GetLoadAddress(&GetTarget());
5799 std::map<addr_t, addr_t>::const_iterator iter =
5800 m_resolved_indirect_addresses.find(addr);
5801 if (iter != m_resolved_indirect_addresses.end()) {
5802 function_addr = (*iter).second;
5803 } else {
5804 if (!InferiorCall(this, address, function_addr)) {
5805 Symbol *symbol = address->CalculateSymbolContextSymbol();
5806 error.SetErrorStringWithFormat(
5807 "Unable to call resolver for indirect function %s",
5808 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5809 function_addr = LLDB_INVALID_ADDRESS;
5810 } else {
5811 m_resolved_indirect_addresses.insert(
5812 std::pair<addr_t, addr_t>(addr, function_addr));
5813 }
5814 }
5815 return function_addr;
5816}
5817
5818void Process::ModulesDidLoad(ModuleList &module_list) {
5819 SystemRuntime *sys_runtime = GetSystemRuntime();
5820 if (sys_runtime) {
5821 sys_runtime->ModulesDidLoad(module_list);
5822 }
5823
5824 GetJITLoaders().ModulesDidLoad(module_list);
5825
5826 // Give runtimes a chance to be created.
5827 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5828 m_instrumentation_runtimes);
5829
5830 // Tell runtimes about new modules.
5831 for (auto pos = m_instrumentation_runtimes.begin();
5832 pos != m_instrumentation_runtimes.end(); ++pos) {
5833 InstrumentationRuntimeSP runtime = pos->second;
5834 runtime->ModulesDidLoad(module_list);
5835 }
5836
Adrian Prantl05097242018-04-30 16:49:04 +00005837 // Let any language runtimes we have already created know about the modules
5838 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005839
Adrian Prantl05097242018-04-30 16:49:04 +00005840 // Iterate over a copy of this language runtime list in case the language
5841 // runtime ModulesDidLoad somehow causes the language riuntime to be
5842 // unloaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005843 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5844 for (const auto &pair : language_runtimes) {
Adrian Prantl05097242018-04-30 16:49:04 +00005845 // We must check language_runtime_sp to make sure it is not nullptr as we
5846 // might cache the fact that we didn't have a language runtime for a
5847 // language.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005848 LanguageRuntimeSP language_runtime_sp = pair.second;
5849 if (language_runtime_sp)
5850 language_runtime_sp->ModulesDidLoad(module_list);
5851 }
5852
5853 // If we don't have an operating system plug-in, try to load one since
5854 // loading shared libraries might cause a new one to try and load
5855 if (!m_os_ap)
5856 LoadOperatingSystemPlugin(false);
5857
5858 // Give structured-data plugins a chance to see the modified modules.
5859 for (auto pair : m_structured_data_plugin_map) {
5860 if (pair.second)
5861 pair.second->ModulesDidLoad(*this, module_list);
5862 }
5863}
5864
5865void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5866 const char *fmt, ...) {
5867 bool print_warning = true;
5868
5869 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5870 if (!stream_sp)
5871 return;
5872 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5873 return;
5874 }
5875
5876 if (repeat_key != nullptr) {
5877 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5878 if (it == m_warnings_issued.end()) {
5879 m_warnings_issued[warning_type] = WarningsPointerSet();
5880 m_warnings_issued[warning_type].insert(repeat_key);
5881 } else {
5882 if (it->second.find(repeat_key) != it->second.end()) {
5883 print_warning = false;
5884 } else {
5885 it->second.insert(repeat_key);
5886 }
5887 }
5888 }
5889
5890 if (print_warning) {
5891 va_list args;
5892 va_start(args, fmt);
5893 stream_sp->PrintfVarArg(fmt, args);
5894 va_end(args);
5895 }
5896}
5897
5898void Process::PrintWarningOptimization(const SymbolContext &sc) {
5899 if (GetWarningsOptimization() && sc.module_sp &&
5900 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5901 sc.function->GetIsOptimized()) {
5902 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5903 "%s was compiled with optimization - stepping may behave "
5904 "oddly; variables may not be available.\n",
5905 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5906 }
5907}
5908
5909bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5910 info.Clear();
5911
5912 PlatformSP platform_sp = GetTarget().GetPlatform();
5913 if (!platform_sp)
5914 return false;
5915
5916 return platform_sp->GetProcessInfo(GetID(), info);
5917}
5918
5919ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5920 ThreadCollectionSP threads;
5921
5922 const MemoryHistorySP &memory_history =
5923 MemoryHistory::FindPlugin(shared_from_this());
5924
5925 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005926 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005927 }
5928
5929 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
5930
5931 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005932}
Kuba Brecka63927542014-10-11 01:59:32 +00005933
5934InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005935Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5936 InstrumentationRuntimeCollection::iterator pos;
5937 pos = m_instrumentation_runtimes.find(type);
5938 if (pos == m_instrumentation_runtimes.end()) {
5939 return InstrumentationRuntimeSP();
5940 } else
5941 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005942}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005943
Kate Stoneb9c1b512016-09-06 20:57:50 +00005944bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5945 const ArchSpec &arch, ModuleSpec &module_spec) {
5946 module_spec.Clear();
5947 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005948}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005949
Kate Stoneb9c1b512016-09-06 20:57:50 +00005950size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5951 m_image_tokens.push_back(image_ptr);
5952 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005953}
5954
Kate Stoneb9c1b512016-09-06 20:57:50 +00005955lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5956 if (token < m_image_tokens.size())
5957 return m_image_tokens[token];
5958 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005959}
5960
Kate Stoneb9c1b512016-09-06 20:57:50 +00005961void Process::ResetImageToken(size_t token) {
5962 if (token < m_image_tokens.size())
5963 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005964}
Jason Molendafd4cea52016-01-08 21:40:11 +00005965
5966Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005967Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5968 AddressRange range_bounds) {
5969 Target &target = GetTarget();
5970 DisassemblerSP disassembler_sp;
5971 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005972
Kate Stoneb9c1b512016-09-06 20:57:50 +00005973 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005974
Kate Stoneb9c1b512016-09-06 20:57:50 +00005975 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005976 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005977 if (!default_stop_addr.IsValid())
5978 return retval;
5979
5980 ExecutionContext exe_ctx(this);
5981 const char *plugin_name = nullptr;
5982 const char *flavor = nullptr;
5983 const bool prefer_file_cache = true;
5984 disassembler_sp = Disassembler::DisassembleRange(
5985 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
5986 prefer_file_cache);
5987 if (disassembler_sp)
5988 insn_list = &disassembler_sp->GetInstructionList();
5989
5990 if (insn_list == nullptr) {
5991 return retval;
5992 }
5993
5994 size_t insn_offset =
5995 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5996 if (insn_offset == UINT32_MAX) {
5997 return retval;
5998 }
5999
6000 uint32_t branch_index =
6001 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6002 if (branch_index == UINT32_MAX) {
6003 return retval;
6004 }
6005
6006 if (branch_index > insn_offset) {
6007 Address next_branch_insn_address =
6008 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6009 if (next_branch_insn_address.IsValid() &&
6010 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6011 retval = next_branch_insn_address;
6012 }
6013 }
6014
6015 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00006016}
Howard Hellyerad007562016-07-07 08:21:28 +00006017
Zachary Turner97206d52017-05-12 04:51:55 +00006018Status
6019Process::GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00006020
Zachary Turner97206d52017-05-12 04:51:55 +00006021 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00006022
Kate Stoneb9c1b512016-09-06 20:57:50 +00006023 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00006024
Kate Stoneb9c1b512016-09-06 20:57:50 +00006025 region_list.clear();
6026 do {
6027 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6028 error = GetMemoryRegionInfo(range_end, *region_info);
6029 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6030 if (error.Fail()) {
6031 region_list.clear();
6032 break;
Todd Fiala75930012016-08-19 04:21:48 +00006033 }
6034
Kate Stoneb9c1b512016-09-06 20:57:50 +00006035 range_end = region_info->GetRange().GetRangeEnd();
6036 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6037 region_list.push_back(region_info);
6038 }
6039 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00006040
Kate Stoneb9c1b512016-09-06 20:57:50 +00006041 return error;
6042}
6043
Zachary Turner97206d52017-05-12 04:51:55 +00006044Status
6045Process::ConfigureStructuredData(const ConstString &type_name,
6046 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00006047 // If you get this, the Process-derived class needs to implement a method to
6048 // enable an already-reported asynchronous structured data feature. See
6049 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00006050 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00006051}
6052
6053void Process::MapSupportedStructuredDataPlugins(
6054 const StructuredData::Array &supported_type_names) {
6055 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6056
6057 // Bail out early if there are no type names to map.
6058 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00006059 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006060 log->Printf("Process::%s(): no structured data types supported",
6061 __FUNCTION__);
6062 return;
6063 }
Todd Fiala75930012016-08-19 04:21:48 +00006064
Kate Stoneb9c1b512016-09-06 20:57:50 +00006065 // Convert StructuredData type names to ConstString instances.
6066 std::set<ConstString> const_type_names;
6067
6068 if (log)
6069 log->Printf("Process::%s(): the process supports the following async "
6070 "structured data types:",
6071 __FUNCTION__);
6072
6073 supported_type_names.ForEach(
6074 [&const_type_names, &log](StructuredData::Object *object) {
6075 if (!object) {
6076 // Invalid - shouldn't be null objects in the array.
6077 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006078 }
6079
6080 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006081 if (!type_name) {
6082 // Invalid format - all type names should be strings.
6083 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006084 }
6085
6086 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00006087 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00006088 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006089 });
Todd Fiala75930012016-08-19 04:21:48 +00006090
Adrian Prantl05097242018-04-30 16:49:04 +00006091 // For each StructuredDataPlugin, if the plugin handles any of the types in
6092 // the supported_type_names, map that type name to that plugin. Stop when
6093 // we've consumed all the type names.
Jim Ingham93979f62018-04-27 01:57:40 +00006094 // FIXME: should we return an error if there are type names nobody
6095 // supports?
6096 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
6097 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00006098 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6099 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00006100 if (!create_instance)
6101 break;
6102
Kate Stoneb9c1b512016-09-06 20:57:50 +00006103 // Create the plugin.
6104 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6105 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00006106 // This plugin doesn't think it can work with the process. Move on to the
6107 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006108 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006109 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006110
Adrian Prantl05097242018-04-30 16:49:04 +00006111 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006112 std::vector<ConstString> names_to_remove;
6113 for (auto &type_name : const_type_names) {
6114 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6115 m_structured_data_plugin_map.insert(
6116 std::make_pair(type_name, plugin_sp));
6117 names_to_remove.push_back(type_name);
6118 if (log)
6119 log->Printf("Process::%s(): using plugin %s for type name "
6120 "%s",
6121 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6122 type_name.GetCString());
6123 }
6124 }
6125
6126 // Remove the type names that were consumed by this plugin.
6127 for (auto &type_name : names_to_remove)
6128 const_type_names.erase(type_name);
6129 }
Todd Fiala75930012016-08-19 04:21:48 +00006130}
6131
Kate Stoneb9c1b512016-09-06 20:57:50 +00006132bool Process::RouteAsyncStructuredData(
6133 const StructuredData::ObjectSP object_sp) {
6134 // Nothing to do if there's no data.
6135 if (!object_sp)
6136 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006137
Adrian Prantl05097242018-04-30 16:49:04 +00006138 // The contract is this must be a dictionary, so we can look up the routing
6139 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006140 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6141 if (!dictionary)
6142 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006143
Kate Stoneb9c1b512016-09-06 20:57:50 +00006144 // Grab the async structured type name (i.e. the feature/plugin name).
6145 ConstString type_name;
6146 if (!dictionary->GetValueForKeyAsString("type", type_name))
6147 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006148
Kate Stoneb9c1b512016-09-06 20:57:50 +00006149 // Check if there's a plugin registered for this type name.
6150 auto find_it = m_structured_data_plugin_map.find(type_name);
6151 if (find_it == m_structured_data_plugin_map.end()) {
6152 // We don't have a mapping for this structured data type.
6153 return false;
6154 }
Todd Fiala75930012016-08-19 04:21:48 +00006155
Kate Stoneb9c1b512016-09-06 20:57:50 +00006156 // Route the structured data to the plugin.
6157 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6158 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006159}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006160
Zachary Turner97206d52017-05-12 04:51:55 +00006161Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006162 // Default implementation does nothign.
6163 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00006164 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006165}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006166
Frederic Rissd10d3792018-05-11 18:21:11 +00006167UtilityFunction *Process::GetLoadImageUtilityFunction(
6168 Platform *platform,
6169 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006170 if (platform != GetTarget().GetPlatform().get())
6171 return nullptr;
Frederic Rissd10d3792018-05-11 18:21:11 +00006172 std::call_once(m_dlopen_utility_func_flag_once,
6173 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006174 return m_dlopen_utility_func_up.get();
6175}