blob: c72662e4e343f44c7565eb6ed2c8abffba3a4f48 [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"
Eugene Zelenko8f30a652015-10-23 18:39:37 +000017// Project includes
Sean Callanan579e70c2016-03-19 00:03:59 +000018#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include "lldb/Breakpoint/BreakpointLocation.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000020#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include "lldb/Core/Debugger.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000022#include "lldb/Core/Event.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000024#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000025#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Core/PluginManager.h"
27#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000028#include "lldb/Core/StreamFile.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000029#include "lldb/Expression/DiagnosticManager.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000030#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000031#include "lldb/Expression/UserExpression.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000032#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000033#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000035#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000036#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000037#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000038#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000039#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000040#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000041#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000042#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Target/ABI.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000044#include "lldb/Target/CPPLanguageRuntime.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000045#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000046#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000047#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000048#include "lldb/Target/JITLoaderList.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000049#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000050#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000051#include "lldb/Target/MemoryRegionInfo.h"
Jim Ingham22777012010-09-23 02:01:19 +000052#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000053#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000054#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000055#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000057#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000058#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000059#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000060#include "lldb/Target/Target.h"
61#include "lldb/Target/TargetList.h"
62#include "lldb/Target/Thread.h"
63#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000064#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000065#include "lldb/Target/UnixSignals.h"
Zachary Turner50232572015-03-18 21:31:45 +000066#include "lldb/Utility/NameMatches.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000067#include "lldb/Utility/SelectHelper.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068
69using namespace lldb;
70using namespace lldb_private;
Pavel Labathe3e21cf2016-11-30 11:56:32 +000071using namespace std::chrono;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000072
Kate Stoneb9c1b512016-09-06 20:57:50 +000073// Comment out line below to disable memory caching, overriding the process
Pavel Labath43d35412016-12-06 11:24:51 +000074// setting target.process.disable-memory-cache
Greg Clayton67cc0632012-08-22 17:17:09 +000075#define ENABLE_MEMORY_CACHING
76
77#ifdef ENABLE_MEMORY_CACHING
78#define DISABLE_MEM_CACHE_DEFAULT false
79#else
80#define DISABLE_MEM_CACHE_DEFAULT true
81#endif
82
Kate Stoneb9c1b512016-09-06 20:57:50 +000083class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000084public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000085 ProcessOptionValueProperties(const ConstString &name)
86 : OptionValueProperties(name) {}
87
88 // This constructor is used when creating ProcessOptionValueProperties when it
89 // is part of a new lldb_private::Process instance. It will copy all current
90 // global property values as needed
91 ProcessOptionValueProperties(ProcessProperties *global_properties)
92 : OptionValueProperties(*global_properties->GetValueProperties()) {}
93
94 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
95 bool will_modify,
96 uint32_t idx) const override {
97 // When getting the value for a key from the process options, we will always
98 // try and grab the setting from the current process if there is one. Else
99 // we just
100 // use the one from this instance.
101 if (exe_ctx) {
102 Process *process = exe_ctx->GetProcessPtr();
103 if (process) {
104 ProcessOptionValueProperties *instance_properties =
105 static_cast<ProcessOptionValueProperties *>(
106 process->GetValueProperties().get());
107 if (this != instance_properties)
108 return instance_properties->ProtectedGetPropertyAtIndex(idx);
109 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000110 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111 return ProtectedGetPropertyAtIndex(idx);
112 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000113};
114
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115static PropertyDefinition g_properties[] = {
116 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
117 DISABLE_MEM_CACHE_DEFAULT, nullptr, nullptr,
118 "Disable reading and caching of memory in fixed-size units."},
119 {"extra-startup-command", OptionValue::eTypeArray, false,
120 OptionValue::eTypeString, nullptr, nullptr,
121 "A list containing extra commands understood by the particular process "
122 "plugin used. "
123 "For instance, to turn on debugserver logging set this to "
124 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
125 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
126 nullptr, nullptr,
127 "If true, breakpoints will be ignored during expression evaluation."},
128 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
129 nullptr, nullptr, "If true, errors in expression evaluation will unwind "
130 "the stack back to the state before the call."},
131 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
132 nullptr, "A path to a python OS plug-in module file that contains a "
133 "OperatingSystemPlugIn class."},
134 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
135 nullptr, nullptr,
136 "If true, stop when a shared library is loaded or unloaded."},
137 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
138 nullptr, "If true, detach will attempt to keep the process stopped."},
139 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
140 nullptr, "The memory cache line size"},
141 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
142 nullptr, "If true, warn when stopped in code that is optimized where "
143 "stepping and variable availability may not behave as expected."},
144 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000145
146enum {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147 ePropertyDisableMemCache,
148 ePropertyExtraStartCommand,
149 ePropertyIgnoreBreakpointsInExpressions,
150 ePropertyUnwindOnErrorInExpressions,
151 ePropertyPythonOSPluginPath,
152 ePropertyStopOnSharedLibraryEvents,
153 ePropertyDetachKeepsStopped,
154 ePropertyMemCacheLineSize,
155 ePropertyWarningOptimization
Greg Clayton67cc0632012-08-22 17:17:09 +0000156};
157
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158ProcessProperties::ProcessProperties(lldb_private::Process *process)
159 : Properties(),
160 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000161{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 if (process == nullptr) {
163 // Global process properties, set them up one time
164 m_collection_sp.reset(
165 new ProcessOptionValueProperties(ConstString("process")));
166 m_collection_sp->Initialize(g_properties);
167 m_collection_sp->AppendProperty(
168 ConstString("thread"), ConstString("Settings specific to threads."),
169 true, Thread::GetGlobalProperties()->GetValueProperties());
170 } else {
171 m_collection_sp.reset(
172 new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
173 m_collection_sp->SetValueChangedCallback(
174 ePropertyPythonOSPluginPath,
175 ProcessProperties::OptionValueChangedCallback, this);
176 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000177}
178
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000179ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181void ProcessProperties::OptionValueChangedCallback(void *baton,
182 OptionValue *option_value) {
183 ProcessProperties *properties = (ProcessProperties *)baton;
184 if (properties->m_process)
185 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000186}
187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188bool ProcessProperties::GetDisableMemoryCache() const {
189 const uint32_t idx = ePropertyDisableMemCache;
190 return m_collection_sp->GetPropertyAtIndexAsBoolean(
191 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000192}
193
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
195 const uint32_t idx = ePropertyMemCacheLineSize;
196 return m_collection_sp->GetPropertyAtIndexAsUInt64(
197 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000198}
199
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200Args ProcessProperties::GetExtraStartupCommands() const {
201 Args args;
202 const uint32_t idx = ePropertyExtraStartCommand;
203 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
204 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000205}
206
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207void ProcessProperties::SetExtraStartupCommands(const Args &args) {
208 const uint32_t idx = ePropertyExtraStartCommand;
209 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000210}
211
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212FileSpec ProcessProperties::GetPythonOSPluginPath() const {
213 const uint32_t idx = ePropertyPythonOSPluginPath;
214 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000215}
216
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
218 const uint32_t idx = ePropertyPythonOSPluginPath;
219 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000220}
221
Kate Stoneb9c1b512016-09-06 20:57:50 +0000222bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
223 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
224 return m_collection_sp->GetPropertyAtIndexAsBoolean(
225 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000226}
227
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
229 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
230 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000231}
232
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
234 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
235 return m_collection_sp->GetPropertyAtIndexAsBoolean(
236 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000237}
238
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
240 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
241 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000242}
243
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
245 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
246 return m_collection_sp->GetPropertyAtIndexAsBoolean(
247 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000248}
249
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
251 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
252 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
253}
254
255bool ProcessProperties::GetDetachKeepsStopped() const {
256 const uint32_t idx = ePropertyDetachKeepsStopped;
257 return m_collection_sp->GetPropertyAtIndexAsBoolean(
258 nullptr, idx, g_properties[idx].default_uint_value != 0);
259}
260
261void ProcessProperties::SetDetachKeepsStopped(bool stop) {
262 const uint32_t idx = ePropertyDetachKeepsStopped;
263 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
264}
265
266bool ProcessProperties::GetWarningsOptimization() const {
267 const uint32_t idx = ePropertyWarningOptimization;
268 return m_collection_sp->GetPropertyAtIndexAsBoolean(
269 nullptr, idx, g_properties[idx].default_uint_value != 0);
270}
271
272void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const {
273 const char *cstr;
274 if (m_pid != LLDB_INVALID_PROCESS_ID)
275 s.Printf(" pid = %" PRIu64 "\n", m_pid);
276
277 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
278 s.Printf(" parent = %" PRIu64 "\n", m_parent_pid);
279
280 if (m_executable) {
281 s.Printf(" name = %s\n", m_executable.GetFilename().GetCString());
282 s.PutCString(" file = ");
283 m_executable.Dump(&s);
284 s.EOL();
285 }
286 const uint32_t argc = m_arguments.GetArgumentCount();
287 if (argc > 0) {
288 for (uint32_t i = 0; i < argc; i++) {
289 const char *arg = m_arguments.GetArgumentAtIndex(i);
290 if (i < 10)
291 s.Printf(" arg[%u] = %s\n", i, arg);
292 else
293 s.Printf("arg[%u] = %s\n", i, arg);
294 }
295 }
296
297 const uint32_t envc = m_environment.GetArgumentCount();
298 if (envc > 0) {
299 for (uint32_t i = 0; i < envc; i++) {
300 const char *env = m_environment.GetArgumentAtIndex(i);
301 if (i < 10)
302 s.Printf(" env[%u] = %s\n", i, env);
303 else
304 s.Printf("env[%u] = %s\n", i, env);
305 }
306 }
307
308 if (m_arch.IsValid()) {
309 s.Printf(" arch = ");
310 m_arch.DumpTriple(s);
311 s.EOL();
312 }
313
314 if (m_uid != UINT32_MAX) {
315 cstr = platform->GetUserName(m_uid);
316 s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
317 }
318 if (m_gid != UINT32_MAX) {
319 cstr = platform->GetGroupName(m_gid);
320 s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
321 }
322 if (m_euid != UINT32_MAX) {
323 cstr = platform->GetUserName(m_euid);
324 s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
325 }
326 if (m_egid != UINT32_MAX) {
327 cstr = platform->GetGroupName(m_egid);
328 s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
329 }
330}
331
332void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform,
333 bool show_args, bool verbose) {
334 const char *label;
335 if (show_args || verbose)
336 label = "ARGUMENTS";
337 else
338 label = "NAME";
339
340 if (verbose) {
341 s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE "
342 " %s\n",
343 label);
344 s.PutCString("====== ====== ========== ========== ========== ========== "
345 "======================== ============================\n");
346 } else {
347 s.Printf("PID PARENT USER TRIPLE %s\n", label);
348 s.PutCString("====== ====== ========== ======================== "
349 "============================\n");
350 }
351}
352
353void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform,
354 bool show_args, bool verbose) const {
355 if (m_pid != LLDB_INVALID_PROCESS_ID) {
Greg Clayton32e0a752011-03-30 18:16:51 +0000356 const char *cstr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000357 s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000358
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 StreamString arch_strm;
Todd Fiala7df337f2015-10-13 23:41:19 +0000360 if (m_arch.IsValid())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 m_arch.DumpTriple(arch_strm);
362
363 if (verbose) {
364 cstr = platform->GetUserName(m_uid);
365 if (cstr &&
366 cstr[0]) // Watch for empty string that indicates lookup failed
367 s.Printf("%-10s ", cstr);
368 else
369 s.Printf("%-10u ", m_uid);
370
371 cstr = platform->GetGroupName(m_gid);
372 if (cstr &&
373 cstr[0]) // Watch for empty string that indicates lookup failed
374 s.Printf("%-10s ", cstr);
375 else
376 s.Printf("%-10u ", m_gid);
377
378 cstr = platform->GetUserName(m_euid);
379 if (cstr &&
380 cstr[0]) // Watch for empty string that indicates lookup failed
381 s.Printf("%-10s ", cstr);
382 else
383 s.Printf("%-10u ", m_euid);
384
385 cstr = platform->GetGroupName(m_egid);
386 if (cstr &&
387 cstr[0]) // Watch for empty string that indicates lookup failed
388 s.Printf("%-10s ", cstr);
389 else
390 s.Printf("%-10u ", m_egid);
391
Zachary Turnerc1564272016-11-16 21:15:24 +0000392 s.Printf("%-24s ", arch_strm.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 } else {
394 s.Printf("%-10s %-24s ", platform->GetUserName(m_euid),
Zachary Turnerc1564272016-11-16 21:15:24 +0000395 arch_strm.GetData());
Todd Fiala7df337f2015-10-13 23:41:19 +0000396 }
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 if (verbose || show_args) {
399 const uint32_t argc = m_arguments.GetArgumentCount();
400 if (argc > 0) {
401 for (uint32_t i = 0; i < argc; i++) {
402 if (i > 0)
403 s.PutChar(' ');
404 s.PutCString(m_arguments.GetArgumentAtIndex(i));
405 }
406 }
407 } else {
408 s.PutCString(GetName());
Greg Clayton32e0a752011-03-30 18:16:51 +0000409 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410
411 s.EOL();
412 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000413}
414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415Error ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000416 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417 ExecutionContext *execution_context) {
418 Error error;
419 const int short_option = m_getopt_table[option_idx].val;
420
421 switch (short_option) {
422 case 's': // Stop at program entry point
423 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
424 break;
425
426 case 'i': // STDIN for read only
427 {
428 FileAction action;
429 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
430 launch_info.AppendFileAction(action);
431 break;
432 }
433
434 case 'o': // Open STDOUT for write only
435 {
436 FileAction action;
437 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
438 launch_info.AppendFileAction(action);
439 break;
440 }
441
442 case 'e': // STDERR for write only
443 {
444 FileAction action;
445 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
446 launch_info.AppendFileAction(action);
447 break;
448 }
449
450 case 'p': // Process plug-in name
451 launch_info.SetProcessPluginName(option_arg);
452 break;
453
454 case 'n': // Disable STDIO
455 {
456 FileAction action;
457 const FileSpec dev_null{FileSystem::DEV_NULL, false};
458 if (action.Open(STDIN_FILENO, dev_null, true, false))
459 launch_info.AppendFileAction(action);
460 if (action.Open(STDOUT_FILENO, dev_null, false, true))
461 launch_info.AppendFileAction(action);
462 if (action.Open(STDERR_FILENO, dev_null, false, true))
463 launch_info.AppendFileAction(action);
464 break;
465 }
466
467 case 'w':
468 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
469 break;
470
471 case 't': // Open process in new terminal window
472 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
473 break;
474
475 case 'a': {
476 TargetSP target_sp =
477 execution_context ? execution_context->GetTargetSP() : TargetSP();
478 PlatformSP platform_sp =
479 target_sp ? target_sp->GetPlatform() : PlatformSP();
480 if (!launch_info.GetArchitecture().SetTriple(option_arg, platform_sp.get()))
481 launch_info.GetArchitecture().SetTriple(option_arg);
482 } break;
483
484 case 'A': // Disable ASLR.
485 {
486 bool success;
487 const bool disable_aslr_arg =
Zachary Turnerfe114832016-11-12 16:56:47 +0000488 Args::StringToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 if (success)
490 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000491 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 error.SetErrorStringWithFormat(
493 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000494 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495 break;
496 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000497
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498 case 'X': // shell expand args.
499 {
500 bool success;
Zachary Turnerfe114832016-11-12 16:56:47 +0000501 const bool expand_args = Args::StringToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000502 if (success)
503 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000504 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 error.SetErrorStringWithFormat(
506 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000507 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 break;
509 }
510
511 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000512 if (!option_arg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513 launch_info.SetShell(FileSpec(option_arg, false));
514 else
515 launch_info.SetShell(HostInfo::GetDefaultShell());
516 break;
517
518 case 'v':
Zachary Turnerfe114832016-11-12 16:56:47 +0000519 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 break;
521
522 default:
523 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
524 short_option);
525 break;
526 }
527 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000528}
529
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000530static OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
532 nullptr, nullptr, 0, eArgTypeNone,
533 "Stop at the entry point of the program when launching a process."},
534 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
535 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
536 "Set whether to disable address space layout randomization when launching "
537 "a process."},
538 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
539 nullptr, nullptr, 0, eArgTypePlugin,
540 "Name of the process plugin you want to use."},
541 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
542 OptionParser::eRequiredArgument, nullptr, nullptr, 0,
543 eArgTypeDirectoryName,
544 "Set the current working directory to <path> when running the inferior."},
545 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
546 nullptr, nullptr, 0, eArgTypeArchitecture,
547 "Set the architecture for the process to launch when ambiguous."},
548 {LLDB_OPT_SET_ALL, false, "environment", 'v',
549 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone,
550 "Specify an environment variable name/value string (--environment "
551 "NAME=VALUE). Can be specified multiple times for subsequent environment "
552 "entries."},
553 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
554 OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeFilename,
555 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000556
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
558 nullptr, nullptr, 0, eArgTypeFilename,
559 "Redirect stdin for the process to <filename>."},
560 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
561 nullptr, nullptr, 0, eArgTypeFilename,
562 "Redirect stdout for the process to <filename>."},
563 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
564 nullptr, nullptr, 0, eArgTypeFilename,
565 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000566
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
568 nullptr, 0, eArgTypeNone,
569 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
572 nullptr, 0, eArgTypeNone,
573 "Do not set up for terminal I/O to go to running process."},
574 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
575 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
576 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000577};
578
579llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000580 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000581}
Greg Clayton32e0a752011-03-30 18:16:51 +0000582
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
584 if (m_name_match_type == eNameMatchIgnore || process_name == nullptr)
Greg Clayton32e0a752011-03-30 18:16:51 +0000585 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586 const char *match_name = m_match_info.GetName();
587 if (!match_name)
Greg Clayton32e0a752011-03-30 18:16:51 +0000588 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589
590 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
Greg Clayton32e0a752011-03-30 18:16:51 +0000591}
592
Kate Stoneb9c1b512016-09-06 20:57:50 +0000593bool ProcessInstanceInfoMatch::Matches(
594 const ProcessInstanceInfo &proc_info) const {
595 if (!NameMatches(proc_info.GetName()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000596 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597
598 if (m_match_info.ProcessIDIsValid() &&
599 m_match_info.GetProcessID() != proc_info.GetProcessID())
600 return false;
601
602 if (m_match_info.ParentProcessIDIsValid() &&
603 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
604 return false;
605
606 if (m_match_info.UserIDIsValid() &&
607 m_match_info.GetUserID() != proc_info.GetUserID())
608 return false;
609
610 if (m_match_info.GroupIDIsValid() &&
611 m_match_info.GetGroupID() != proc_info.GetGroupID())
612 return false;
613
614 if (m_match_info.EffectiveUserIDIsValid() &&
615 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
616 return false;
617
618 if (m_match_info.EffectiveGroupIDIsValid() &&
619 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
620 return false;
621
622 if (m_match_info.GetArchitecture().IsValid() &&
623 !m_match_info.GetArchitecture().IsCompatibleMatch(
624 proc_info.GetArchitecture()))
625 return false;
626 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000627}
628
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
630 if (m_name_match_type != eNameMatchIgnore)
631 return false;
632
633 if (m_match_info.ProcessIDIsValid())
634 return false;
635
636 if (m_match_info.ParentProcessIDIsValid())
637 return false;
638
639 if (m_match_info.UserIDIsValid())
640 return false;
641
642 if (m_match_info.GroupIDIsValid())
643 return false;
644
645 if (m_match_info.EffectiveUserIDIsValid())
646 return false;
647
648 if (m_match_info.EffectiveGroupIDIsValid())
649 return false;
650
651 if (m_match_info.GetArchitecture().IsValid())
652 return false;
653
654 if (m_match_all_users)
655 return false;
656
657 return true;
658}
659
660void ProcessInstanceInfoMatch::Clear() {
661 m_match_info.Clear();
662 m_name_match_type = eNameMatchIgnore;
663 m_match_all_users = false;
664}
665
Zachary Turner31659452016-11-17 21:15:14 +0000666ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
667 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 ListenerSP listener_sp,
669 const FileSpec *crash_file_path) {
670 static uint32_t g_process_unique_id = 0;
671
672 ProcessSP process_sp;
673 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000674 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 ConstString const_plugin_name(plugin_name);
676 create_callback =
677 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
678 if (create_callback) {
679 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
680 if (process_sp) {
681 if (process_sp->CanDebug(target_sp, true)) {
682 process_sp->m_process_unique_id = ++g_process_unique_id;
683 } else
684 process_sp.reset();
685 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000686 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 } else {
688 for (uint32_t idx = 0;
689 (create_callback =
690 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
691 ++idx) {
692 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
693 if (process_sp) {
694 if (process_sp->CanDebug(target_sp, false)) {
695 process_sp->m_process_unique_id = ++g_process_unique_id;
696 break;
697 } else
698 process_sp.reset();
699 }
700 }
701 }
702 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000703}
704
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705ConstString &Process::GetStaticBroadcasterClass() {
706 static ConstString class_name("lldb.process");
707 return class_name;
708}
709
710Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
711 : Process(target_sp, listener_sp,
712 UnixSignals::Create(HostInfo::GetArchitecture())) {
713 // This constructor just delegates to the full Process constructor,
714 // defaulting to using the Host's UnixSignals.
715}
716
717Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
718 const UnixSignalsSP &unix_signals_sp)
719 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
720 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
721 Process::GetStaticBroadcasterClass().AsCString()),
722 m_target_sp(target_sp), m_public_state(eStateUnloaded),
723 m_private_state(eStateUnloaded),
724 m_private_state_broadcaster(nullptr,
725 "lldb.process.internal_state_broadcaster"),
726 m_private_state_control_broadcaster(
727 nullptr, "lldb.process.internal_state_control_broadcaster"),
728 m_private_state_listener_sp(
729 Listener::MakeListener("lldb.process.internal_state_listener")),
730 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
731 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
732 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
733 m_thread_list(this), m_extended_thread_list(this),
734 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
735 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
736 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
737 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
738 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
739 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
740 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
741 m_memory_cache(*this), m_allocated_memory_cache(*this),
742 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
743 m_private_run_lock(), m_stop_info_override_callback(nullptr),
744 m_finalizing(false), m_finalize_called(false),
745 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
746 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
747 m_can_interpret_function_calls(false), m_warnings_issued(),
748 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
749 CheckInWithManager();
750
751 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
752 if (log)
753 log->Printf("%p Process::Process()", static_cast<void *>(this));
754
755 if (!m_unix_signals_sp)
756 m_unix_signals_sp = std::make_shared<UnixSignals>();
757
758 SetEventName(eBroadcastBitStateChanged, "state-changed");
759 SetEventName(eBroadcastBitInterrupt, "interrupt");
760 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
761 SetEventName(eBroadcastBitSTDERR, "stderr-available");
762 SetEventName(eBroadcastBitProfileData, "profile-data-available");
763 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
764
765 m_private_state_control_broadcaster.SetEventName(
766 eBroadcastInternalStateControlStop, "control-stop");
767 m_private_state_control_broadcaster.SetEventName(
768 eBroadcastInternalStateControlPause, "control-pause");
769 m_private_state_control_broadcaster.SetEventName(
770 eBroadcastInternalStateControlResume, "control-resume");
771
772 m_listener_sp->StartListeningForEvents(
773 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
774 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
775 eBroadcastBitProfileData | eBroadcastBitStructuredData);
776
777 m_private_state_listener_sp->StartListeningForEvents(
778 &m_private_state_broadcaster,
779 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
780
781 m_private_state_listener_sp->StartListeningForEvents(
782 &m_private_state_control_broadcaster,
783 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
784 eBroadcastInternalStateControlResume);
785 // We need something valid here, even if just the default UnixSignalsSP.
786 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
787
788 // Allow the platform to override the default cache line size
789 OptionValueSP value_sp =
790 m_collection_sp
791 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
792 ->GetValue();
793 uint32_t platform_cache_line_size =
794 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
795 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
796 value_sp->SetUInt64Value(platform_cache_line_size);
797}
798
799Process::~Process() {
800 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
801 if (log)
802 log->Printf("%p Process::~Process()", static_cast<void *>(this));
803 StopPrivateStateThread();
804
805 // ThreadList::Clear() will try to acquire this process's mutex, so
806 // explicitly clear the thread list here to ensure that the mutex
807 // is not destroyed before the thread list.
808 m_thread_list.Clear();
809}
810
811const ProcessPropertiesSP &Process::GetGlobalProperties() {
812 // NOTE: intentional leak so we don't crash if global destructor chain gets
813 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000814 static ProcessPropertiesSP *g_settings_sp_ptr =
815 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 return *g_settings_sp_ptr;
817}
818
819void Process::Finalize() {
820 m_finalizing = true;
821
822 // Destroy this process if needed
823 switch (GetPrivateState()) {
824 case eStateConnected:
825 case eStateAttaching:
826 case eStateLaunching:
827 case eStateStopped:
828 case eStateRunning:
829 case eStateStepping:
830 case eStateCrashed:
831 case eStateSuspended:
832 Destroy(false);
833 break;
834
835 case eStateInvalid:
836 case eStateUnloaded:
837 case eStateDetached:
838 case eStateExited:
839 break;
840 }
841
842 // Clear our broadcaster before we proceed with destroying
843 Broadcaster::Clear();
844
845 // Do any cleanup needed prior to being destructed... Subclasses
846 // that override this method should call this superclass method as well.
847
848 // We need to destroy the loader before the derived Process class gets
849 // destroyed
850 // since it is very likely that undoing the loader will require access to the
851 // real process.
852 m_dynamic_checkers_ap.reset();
853 m_abi_sp.reset();
854 m_os_ap.reset();
855 m_system_runtime_ap.reset();
856 m_dyld_ap.reset();
857 m_jit_loaders_ap.reset();
858 m_thread_list_real.Destroy();
859 m_thread_list.Destroy();
860 m_extended_thread_list.Destroy();
861 m_queue_list.Clear();
862 m_queue_list_stop_id = 0;
863 std::vector<Notifications> empty_notifications;
864 m_notifications.swap(empty_notifications);
865 m_image_tokens.clear();
866 m_memory_cache.Clear();
867 m_allocated_memory_cache.Clear();
868 m_language_runtimes.clear();
869 m_instrumentation_runtimes.clear();
870 m_next_event_action_ap.reset();
871 m_stop_info_override_callback = nullptr;
872 // Clear the last natural stop ID since it has a strong
873 // reference to this process
874 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
875 //#ifdef LLDB_CONFIGURATION_DEBUG
876 // StreamFile s(stdout, false);
877 // EventSP event_sp;
878 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
879 // {
880 // event_sp->Dump (&s);
881 // s.EOL();
882 // }
883 //#endif
884 // We have to be very careful here as the m_private_state_listener might
885 // contain events that have ProcessSP values in them which can keep this
886 // process around forever. These events need to be cleared out.
887 m_private_state_listener_sp->Clear();
888 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
889 m_public_run_lock.SetStopped();
890 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
891 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000892 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893 m_finalize_called = true;
894}
895
896void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
897 m_notifications.push_back(callbacks);
898 if (callbacks.initialize != nullptr)
899 callbacks.initialize(callbacks.baton, this);
900}
901
902bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
903 std::vector<Notifications>::iterator pos, end = m_notifications.end();
904 for (pos = m_notifications.begin(); pos != end; ++pos) {
905 if (pos->baton == callbacks.baton &&
906 pos->initialize == callbacks.initialize &&
907 pos->process_state_changed == callbacks.process_state_changed) {
908 m_notifications.erase(pos);
909 return true;
910 }
911 }
912 return false;
913}
914
915void Process::SynchronouslyNotifyStateChanged(StateType state) {
916 std::vector<Notifications>::iterator notification_pos,
917 notification_end = m_notifications.end();
918 for (notification_pos = m_notifications.begin();
919 notification_pos != notification_end; ++notification_pos) {
920 if (notification_pos->process_state_changed)
921 notification_pos->process_state_changed(notification_pos->baton, this,
922 state);
923 }
924}
925
926// FIXME: We need to do some work on events before the general Listener sees
927// them.
928// For instance if we are continuing from a breakpoint, we need to ensure that
929// we do
930// the little "insert real insn, step & stop" trick. But we can't do that when
931// the
932// event is delivered by the broadcaster - since that is done on the thread that
933// is
934// waiting for new events, so if we needed more than one event for our handling,
935// we would
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000936// stall. So instead we do it when we fetch the event off of the queue.
937//
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
950void Process::SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec) {
951 // don't sync (potentially context switch) in case where there is no process
952 // IO
953 if (!m_process_input_reader)
954 return;
955
956 uint32_t new_iohandler_id = 0;
957 m_iohandler_sync.WaitForValueNotEqualTo(
958 iohandler_id, new_iohandler_id, std::chrono::milliseconds(timeout_msec));
959
960 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
961 if (log)
962 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, "
963 "new value is %u",
964 __FUNCTION__, iohandler_id, new_iohandler_id);
965}
966
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000967StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
968 EventSP *event_sp_ptr, bool wait_always,
969 ListenerSP hijack_listener_sp,
970 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 // We can't just wait for a "stopped" event, because the stopped event may
972 // have restarted the target.
973 // We have to actually check each event, and in the case of a stopped event
974 // check the restarted flag
975 // on the event.
976 if (event_sp_ptr)
977 event_sp_ptr->reset();
978 StateType state = GetState();
979 // If we are exited or detached, we won't ever get back to any
980 // other valid state...
981 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000982 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000983
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
985 if (log)
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000986 log->Printf(
987 "Process::%s (timeout = %llu)", __FUNCTION__,
988 static_cast<unsigned long long>(timeout ? timeout->count() : -1));
Todd Fialaa3b89e22014-08-12 14:33:19 +0000989
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 if (!wait_always && StateIsStoppedState(state, true) &&
991 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000992 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 log->Printf("Process::%s returning without waiting for events; process "
994 "private and public states are already 'stopped'.",
995 __FUNCTION__);
996 // We need to toggle the run lock as this won't get done in
997 // SetPublicState() if the process is hijacked.
998 if (hijack_listener_sp && use_run_lock)
999 m_public_run_lock.SetStopped();
1000 return state;
1001 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 while (state != eStateInvalid) {
1004 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001005 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 if (event_sp_ptr && event_sp)
1007 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001008
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1010 Process::HandleProcessStateChangedEvent(event_sp, stream,
1011 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +00001012
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013 switch (state) {
1014 case eStateCrashed:
1015 case eStateDetached:
1016 case eStateExited:
1017 case eStateUnloaded:
1018 // We need to toggle the run lock as this won't get done in
1019 // SetPublicState() if the process is hijacked.
1020 if (hijack_listener_sp && use_run_lock)
1021 m_public_run_lock.SetStopped();
1022 return state;
1023 case eStateStopped:
1024 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1025 continue;
1026 else {
Pavel Labath78521ef2015-03-06 10:52:47 +00001027 // We need to toggle the run lock as this won't get done in
1028 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001029 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 m_public_run_lock.SetStopped();
1031 return state;
1032 }
1033 default:
1034 continue;
1035 }
1036 }
1037 return state;
1038}
1039
1040bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1041 Stream *stream,
1042 bool &pop_process_io_handler) {
1043 const bool handle_pop = pop_process_io_handler;
1044
1045 pop_process_io_handler = false;
1046 ProcessSP process_sp =
1047 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1048
1049 if (!process_sp)
1050 return false;
1051
1052 StateType event_state =
1053 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1054 if (event_state == eStateInvalid)
1055 return false;
1056
1057 switch (event_state) {
1058 case eStateInvalid:
1059 case eStateUnloaded:
1060 case eStateAttaching:
1061 case eStateLaunching:
1062 case eStateStepping:
1063 case eStateDetached:
1064 if (stream)
1065 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1066 StateAsCString(event_state));
1067 if (event_state == eStateDetached)
1068 pop_process_io_handler = true;
1069 break;
1070
1071 case eStateConnected:
1072 case eStateRunning:
1073 // Don't be chatty when we run...
1074 break;
1075
1076 case eStateExited:
1077 if (stream)
1078 process_sp->GetStatus(*stream);
1079 pop_process_io_handler = true;
1080 break;
1081
1082 case eStateStopped:
1083 case eStateCrashed:
1084 case eStateSuspended:
1085 // Make sure the program hasn't been auto-restarted:
1086 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1087 if (stream) {
1088 size_t num_reasons =
1089 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1090 if (num_reasons > 0) {
1091 // FIXME: Do we want to report this, or would that just be annoyingly
1092 // chatty?
1093 if (num_reasons == 1) {
1094 const char *reason =
1095 Process::ProcessEventData::GetRestartedReasonAtIndex(
1096 event_sp.get(), 0);
1097 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1098 process_sp->GetID(),
1099 reason ? reason : "<UNKNOWN REASON>");
1100 } else {
1101 stream->Printf("Process %" PRIu64
1102 " stopped and restarted, reasons:\n",
1103 process_sp->GetID());
1104
1105 for (size_t i = 0; i < num_reasons; i++) {
1106 const char *reason =
1107 Process::ProcessEventData::GetRestartedReasonAtIndex(
1108 event_sp.get(), i);
1109 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1110 }
1111 }
1112 }
1113 }
1114 } else {
1115 StopInfoSP curr_thread_stop_info_sp;
1116 // Lock the thread list so it doesn't change on us, this is the scope for
1117 // the locker:
1118 {
1119 ThreadList &thread_list = process_sp->GetThreadList();
1120 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1121
1122 ThreadSP curr_thread(thread_list.GetSelectedThread());
1123 ThreadSP thread;
1124 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1125 if (curr_thread) {
1126 curr_thread_stop_reason = curr_thread->GetStopReason();
1127 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1128 }
1129 if (!curr_thread || !curr_thread->IsValid() ||
1130 curr_thread_stop_reason == eStopReasonInvalid ||
1131 curr_thread_stop_reason == eStopReasonNone) {
1132 // Prefer a thread that has just completed its plan over another
1133 // thread as current thread.
1134 ThreadSP plan_thread;
1135 ThreadSP other_thread;
1136
1137 const size_t num_threads = thread_list.GetSize();
1138 size_t i;
1139 for (i = 0; i < num_threads; ++i) {
1140 thread = thread_list.GetThreadAtIndex(i);
1141 StopReason thread_stop_reason = thread->GetStopReason();
1142 switch (thread_stop_reason) {
1143 case eStopReasonInvalid:
1144 case eStopReasonNone:
1145 break;
1146
1147 case eStopReasonSignal: {
1148 // Don't select a signal thread if we weren't going to stop at
1149 // that
1150 // signal. We have to have had another reason for stopping here,
1151 // and
1152 // the user doesn't want to see this thread.
1153 uint64_t signo = thread->GetStopInfo()->GetValue();
1154 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1155 if (!other_thread)
1156 other_thread = thread;
1157 }
1158 break;
1159 }
1160 case eStopReasonTrace:
1161 case eStopReasonBreakpoint:
1162 case eStopReasonWatchpoint:
1163 case eStopReasonException:
1164 case eStopReasonExec:
1165 case eStopReasonThreadExiting:
1166 case eStopReasonInstrumentation:
1167 if (!other_thread)
1168 other_thread = thread;
1169 break;
1170 case eStopReasonPlanComplete:
1171 if (!plan_thread)
1172 plan_thread = thread;
1173 break;
1174 }
1175 }
1176 if (plan_thread)
1177 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1178 else if (other_thread)
1179 thread_list.SetSelectedThreadByID(other_thread->GetID());
1180 else {
1181 if (curr_thread && curr_thread->IsValid())
1182 thread = curr_thread;
1183 else
1184 thread = thread_list.GetThreadAtIndex(0);
1185
1186 if (thread)
1187 thread_list.SetSelectedThreadByID(thread->GetID());
1188 }
1189 }
1190 }
1191 // Drop the ThreadList mutex by here, since GetThreadStatus below might
1192 // have to run code,
1193 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the
1194 // process is going to
1195 // have a hard time restarting the process.
1196 if (stream) {
1197 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1198 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1199 &process_sp->GetTarget()) {
1200 const bool only_threads_with_stop_reason = true;
1201 const uint32_t start_frame = 0;
1202 const uint32_t num_frames = 1;
1203 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001204 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 process_sp->GetStatus(*stream);
1206 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1207 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001208 num_frames_with_source,
1209 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 if (curr_thread_stop_info_sp) {
1211 lldb::addr_t crashing_address;
1212 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1213 curr_thread_stop_info_sp, &crashing_address);
1214 if (valobj_sp) {
1215 const bool qualify_cxx_base_classes = false;
1216
1217 const ValueObject::GetExpressionPathFormat format =
1218 ValueObject::GetExpressionPathFormat::
1219 eGetExpressionPathFormatHonorPointers;
1220 stream->PutCString("Likely cause: ");
1221 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1222 format);
1223 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1224 }
1225 }
1226 } else {
1227 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1228 process_sp->GetTarget().shared_from_this());
1229 if (target_idx != UINT32_MAX)
1230 stream->Printf("Target %d: (", target_idx);
1231 else
1232 stream->Printf("Target <unknown index>: (");
1233 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1234 stream->Printf(") stopped.\n");
1235 }
1236 }
1237
1238 // Pop the process IO handler
1239 pop_process_io_handler = true;
1240 }
1241 break;
1242 }
1243
1244 if (handle_pop && pop_process_io_handler)
1245 process_sp->PopProcessIOHandler();
1246
1247 return true;
1248}
1249
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1251 if (listener_sp) {
1252 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1253 eBroadcastBitInterrupt);
1254 } else
1255 return false;
1256}
Greg Claytondc6224e2014-10-21 01:00:42 +00001257
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001259
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001260StateType Process::GetStateChangedEvents(EventSP &event_sp,
1261 const Timeout<std::micro> &timeout,
1262 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001264
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 if (log)
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001266 log->Printf(
1267 "Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1268 static_cast<unsigned long long>(timeout ? timeout->count() : -1));
Greg Claytondc6224e2014-10-21 01:00:42 +00001269
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 ListenerSP listener_sp = hijack_listener_sp;
1271 if (!listener_sp)
1272 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001273
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001275 if (listener_sp->GetEventForBroadcasterWithType(
1276 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001277 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1279 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1280 else if (log)
1281 log->Printf("Process::%s got no event or was interrupted.", __FUNCTION__);
1282 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001283
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 if (log)
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001285 log->Printf(
1286 "Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1287 static_cast<unsigned long long>(timeout ? timeout->count() : -1),
1288 StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001289 return state;
1290}
Greg Claytondc6224e2014-10-21 01:00:42 +00001291
Kate Stoneb9c1b512016-09-06 20:57:50 +00001292Event *Process::PeekAtStateChangedEvents() {
1293 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001294
Kate Stoneb9c1b512016-09-06 20:57:50 +00001295 if (log)
1296 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001297
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298 Event *event_ptr;
1299 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1300 this, eBroadcastBitStateChanged);
1301 if (log) {
1302 if (event_ptr) {
1303 log->Printf(
1304 "Process::%s (event_ptr) => %s", __FUNCTION__,
1305 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1306 } else {
1307 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001308 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309 }
1310 return event_ptr;
1311}
Greg Claytondc6224e2014-10-21 01:00:42 +00001312
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001313StateType
1314Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1315 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001317
Kate Stoneb9c1b512016-09-06 20:57:50 +00001318 if (log)
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001319 log->Printf(
1320 "Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1321 static_cast<unsigned long long>(timeout ? timeout->count() : -1));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001322
1323 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001324 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1325 &m_private_state_broadcaster,
1326 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001327 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1329 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1330
1331 // This is a bit of a hack, but when we wait here we could very well return
1332 // to the command-line, and that could disable the log, which would render the
1333 // log we got above invalid.
1334 if (log)
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001335 log->Printf(
1336 "Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1337 static_cast<unsigned long long>(timeout ? timeout->count() : -1),
1338 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001339 return state;
1340}
1341
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001342bool Process::GetEventsPrivate(EventSP &event_sp,
1343 const Timeout<std::micro> &timeout,
1344 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001345 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1346
1347 if (log)
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001348 log->Printf(
1349 "Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1350 static_cast<unsigned long long>(timeout ? timeout->count() : -1));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001351
1352 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001353 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001354 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001355 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001356 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001357}
1358
1359bool Process::IsRunning() const {
1360 return StateIsRunningState(m_public_state.GetValue());
1361}
1362
1363int Process::GetExitStatus() {
1364 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1365
1366 if (m_public_state.GetValue() == eStateExited)
1367 return m_exit_status;
1368 return -1;
1369}
1370
1371const char *Process::GetExitDescription() {
1372 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1373
1374 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1375 return m_exit_string.c_str();
1376 return nullptr;
1377}
1378
1379bool Process::SetExitStatus(int status, const char *cstr) {
1380 // Use a mutex to protect setting the exit status.
1381 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1382
1383 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1384 LIBLLDB_LOG_PROCESS));
1385 if (log)
1386 log->Printf(
1387 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1388 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1389 cstr ? "\"" : "");
1390
1391 // We were already in the exited state
1392 if (m_private_state.GetValue() == eStateExited) {
1393 if (log)
1394 log->Printf("Process::SetExitStatus () ignoring exit status because "
1395 "state was already set to eStateExited");
1396 return false;
1397 }
1398
1399 m_exit_status = status;
1400 if (cstr)
1401 m_exit_string = cstr;
1402 else
1403 m_exit_string.clear();
1404
1405 // Clear the last natural stop ID since it has a strong
1406 // reference to this process
1407 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1408
1409 SetPrivateState(eStateExited);
1410
1411 // Allow subclasses to do some cleanup
1412 DidExit();
1413
1414 return true;
1415}
1416
1417bool Process::IsAlive() {
1418 switch (m_private_state.GetValue()) {
1419 case eStateConnected:
1420 case eStateAttaching:
1421 case eStateLaunching:
1422 case eStateStopped:
1423 case eStateRunning:
1424 case eStateStepping:
1425 case eStateCrashed:
1426 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001427 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001428 default:
1429 return false;
1430 }
Jason Molendaa814f702015-11-05 23:03:44 +00001431}
1432
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001433// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001434// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001435// found in the global target list (we want to be completely sure that the
1436// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437bool Process::SetProcessExitStatus(
1438 lldb::pid_t pid, bool exited,
1439 int signo, // Zero for no signal
1440 int exit_status // Exit value of process if signal is zero
1441 ) {
1442 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1443 if (log)
1444 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1445 ", exited=%i, signal=%i, exit_status=%i)\n",
1446 pid, exited, signo, exit_status);
1447
1448 if (exited) {
1449 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1450 if (target_sp) {
1451 ProcessSP process_sp(target_sp->GetProcessSP());
1452 if (process_sp) {
1453 const char *signal_cstr = nullptr;
1454 if (signo)
1455 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1456
1457 process_sp->SetExitStatus(exit_status, signal_cstr);
1458 }
1459 }
1460 return true;
1461 }
1462 return false;
1463}
1464
1465void Process::UpdateThreadListIfNeeded() {
1466 const uint32_t stop_id = GetStopID();
1467 if (m_thread_list.GetSize(false) == 0 ||
1468 stop_id != m_thread_list.GetStopID()) {
1469 const StateType state = GetPrivateState();
1470 if (StateIsStoppedState(state, true)) {
1471 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1472 // m_thread_list does have its own mutex, but we need to
1473 // hold onto the mutex between the call to UpdateThreadList(...)
1474 // and the os->UpdateThreadList(...) so it doesn't change on us
1475 ThreadList &old_thread_list = m_thread_list;
1476 ThreadList real_thread_list(this);
1477 ThreadList new_thread_list(this);
1478 // Always update the thread list with the protocol specific
1479 // thread list, but only update if "true" is returned
1480 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1481 // Don't call into the OperatingSystem to update the thread list if we
1482 // are shutting down, since
1483 // that may call back into the SBAPI's, requiring the API lock which is
1484 // already held by whoever is
1485 // shutting us down, causing a deadlock.
1486 OperatingSystem *os = GetOperatingSystem();
1487 if (os && !m_destroy_in_process) {
1488 // Clear any old backing threads where memory threads might have been
1489 // backed by actual threads from the lldb_private::Process subclass
1490 size_t num_old_threads = old_thread_list.GetSize(false);
1491 for (size_t i = 0; i < num_old_threads; ++i)
1492 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1493
1494 // Turn off dynamic types to ensure we don't run any expressions.
1495 // Objective C
1496 // can run an expression to determine if a SBValue is a dynamic type
1497 // or not
1498 // and we need to avoid this. OperatingSystem plug-ins can't run
1499 // expressions
1500 // that require running code...
1501
1502 Target &target = GetTarget();
1503 const lldb::DynamicValueType saved_prefer_dynamic =
1504 target.GetPreferDynamicValue();
1505 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1506 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1507
1508 // Now let the OperatingSystem plug-in update the thread list
1509
1510 os->UpdateThreadList(
1511 old_thread_list, // Old list full of threads created by OS plug-in
1512 real_thread_list, // The actual thread list full of threads
1513 // created by each lldb_private::Process
1514 // subclass
1515 new_thread_list); // The new thread list that we will show to the
1516 // user that gets filled in
1517
1518 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1519 target.SetPreferDynamicValue(saved_prefer_dynamic);
1520 } else {
1521 // No OS plug-in, the new thread list is the same as the real thread
1522 // list
1523 new_thread_list = real_thread_list;
1524 }
1525
1526 m_thread_list_real.Update(real_thread_list);
1527 m_thread_list.Update(new_thread_list);
1528 m_thread_list.SetStopID(stop_id);
1529
1530 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1531 // Clear any extended threads that we may have accumulated previously
1532 m_extended_thread_list.Clear();
1533 m_extended_thread_stop_id = GetLastNaturalStopID();
1534
1535 m_queue_list.Clear();
1536 m_queue_list_stop_id = GetLastNaturalStopID();
1537 }
1538 }
1539 }
1540 }
1541}
1542
1543void Process::UpdateQueueListIfNeeded() {
1544 if (m_system_runtime_ap) {
1545 if (m_queue_list.GetSize() == 0 ||
1546 m_queue_list_stop_id != GetLastNaturalStopID()) {
1547 const StateType state = GetPrivateState();
1548 if (StateIsStoppedState(state, true)) {
1549 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1550 m_queue_list_stop_id = GetLastNaturalStopID();
1551 }
1552 }
1553 }
1554}
1555
1556ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1557 OperatingSystem *os = GetOperatingSystem();
1558 if (os)
1559 return os->CreateThread(tid, context);
1560 return ThreadSP();
1561}
1562
1563uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1564 return AssignIndexIDToThread(thread_id);
1565}
1566
1567bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1568 return (m_thread_id_to_index_id_map.find(thread_id) !=
1569 m_thread_id_to_index_id_map.end());
1570}
1571
1572uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1573 uint32_t result = 0;
1574 std::map<uint64_t, uint32_t>::iterator iterator =
1575 m_thread_id_to_index_id_map.find(thread_id);
1576 if (iterator == m_thread_id_to_index_id_map.end()) {
1577 result = ++m_thread_index_id;
1578 m_thread_id_to_index_id_map[thread_id] = result;
1579 } else {
1580 result = iterator->second;
1581 }
1582
1583 return result;
1584}
1585
1586StateType Process::GetState() {
1587 // If any other threads access this we will need a mutex for it
1588 return m_public_state.GetValue();
1589}
1590
1591bool Process::StateChangedIsExternallyHijacked() {
1592 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1593 const char *hijacking_name = GetHijackingListenerName();
1594 if (hijacking_name &&
1595 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1596 return true;
1597 }
1598 return false;
1599}
1600
1601void Process::SetPublicState(StateType new_state, bool restarted) {
1602 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1603 LIBLLDB_LOG_PROCESS));
1604 if (log)
1605 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1606 StateAsCString(new_state), restarted);
1607 const StateType old_state = m_public_state.GetValue();
1608 m_public_state.SetValue(new_state);
1609
1610 // On the transition from Run to Stopped, we unlock the writer end of the
1611 // run lock. The lock gets locked in Resume, which is the public API
1612 // to tell the program to run.
1613 if (!StateChangedIsExternallyHijacked()) {
1614 if (new_state == eStateDetached) {
1615 if (log)
1616 log->Printf(
1617 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1618 StateAsCString(new_state));
1619 m_public_run_lock.SetStopped();
1620 } else {
1621 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1622 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1623 if ((old_state_is_stopped != new_state_is_stopped)) {
1624 if (new_state_is_stopped && !restarted) {
1625 if (log)
1626 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1627 StateAsCString(new_state));
1628 m_public_run_lock.SetStopped();
1629 }
1630 }
1631 }
1632 }
1633}
1634
1635Error Process::Resume() {
1636 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1637 LIBLLDB_LOG_PROCESS));
1638 if (log)
1639 log->Printf("Process::Resume -- locking run lock");
1640 if (!m_public_run_lock.TrySetRunning()) {
1641 Error error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001642 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001644 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001645 }
1646 return PrivateResume();
Greg Claytondc6224e2014-10-21 01:00:42 +00001647}
1648
Kate Stoneb9c1b512016-09-06 20:57:50 +00001649Error Process::ResumeSynchronous(Stream *stream) {
1650 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1651 LIBLLDB_LOG_PROCESS));
1652 if (log)
1653 log->Printf("Process::ResumeSynchronous -- locking run lock");
1654 if (!m_public_run_lock.TrySetRunning()) {
1655 Error error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001656 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1658 return error;
1659 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001660
Kate Stoneb9c1b512016-09-06 20:57:50 +00001661 ListenerSP listener_sp(
1662 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1663 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001664
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665 Error error = PrivateResume();
1666 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001667 StateType state =
1668 WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001669 const bool must_be_alive =
1670 false; // eStateExited is ok, so this must be false
1671 if (!StateIsStoppedState(state, must_be_alive))
1672 error.SetErrorStringWithFormat(
1673 "process not in stopped state after synchronous resume: %s",
1674 StateAsCString(state));
1675 }
Ed Mastec29693f2013-07-02 16:35:47 +00001676
Kate Stoneb9c1b512016-09-06 20:57:50 +00001677 // Undo the hijacking of process events...
1678 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001679
Kate Stoneb9c1b512016-09-06 20:57:50 +00001680 return error;
1681}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001682
Kate Stoneb9c1b512016-09-06 20:57:50 +00001683StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001684
Kate Stoneb9c1b512016-09-06 20:57:50 +00001685void Process::SetPrivateState(StateType new_state) {
1686 if (m_finalize_called)
1687 return;
1688
1689 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1690 LIBLLDB_LOG_PROCESS));
1691 bool state_changed = false;
1692
1693 if (log)
1694 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1695
1696 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1697 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1698
1699 const StateType old_state = m_private_state.GetValueNoLock();
1700 state_changed = old_state != new_state;
1701
1702 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1703 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1704 if (old_state_is_stopped != new_state_is_stopped) {
1705 if (new_state_is_stopped)
1706 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001707 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001708 m_private_run_lock.SetRunning();
1709 }
1710
1711 if (state_changed) {
1712 m_private_state.SetValueNoLock(new_state);
1713 EventSP event_sp(
1714 new Event(eBroadcastBitStateChanged,
1715 new ProcessEventData(shared_from_this(), new_state)));
1716 if (StateIsStoppedState(new_state, false)) {
1717 // Note, this currently assumes that all threads in the list
1718 // stop when the process stops. In the future we will want to
1719 // support a debugging model where some threads continue to run
1720 // while others are stopped. When that happens we will either need
1721 // a way for the thread list to identify which threads are stopping
1722 // or create a special thread list containing only threads which
1723 // actually stopped.
1724 //
1725 // The process plugin is responsible for managing the actual
1726 // behavior of the threads and should have stopped any threads
1727 // that are going to stop before we get here.
1728 m_thread_list.DidStop();
1729
1730 m_mod_id.BumpStopID();
1731 if (!m_mod_id.IsLastResumeForUserExpression())
1732 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1733 m_memory_cache.Clear();
1734 if (log)
1735 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1736 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001737 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001738
Kate Stoneb9c1b512016-09-06 20:57:50 +00001739 // Use our target to get a shared pointer to ourselves...
1740 if (m_finalize_called && !PrivateStateThreadIsValid())
1741 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001742 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001743 m_private_state_broadcaster.BroadcastEvent(event_sp);
1744 } else {
1745 if (log)
1746 log->Printf(
1747 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1748 StateAsCString(new_state));
1749 }
Jim Ingham22777012010-09-23 02:01:19 +00001750}
1751
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752void Process::SetRunningUserExpression(bool on) {
1753 m_mod_id.SetRunningUserExpression(on);
1754}
1755
1756addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1757
1758const lldb::ABISP &Process::GetABI() {
1759 if (!m_abi_sp)
1760 m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture());
1761 return m_abi_sp;
1762}
1763
1764LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1765 bool retry_if_null) {
1766 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001767 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001768
1769 LanguageRuntimeCollection::iterator pos;
1770 pos = m_language_runtimes.find(language);
1771 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1772 lldb::LanguageRuntimeSP runtime_sp(
1773 LanguageRuntime::FindPlugin(this, language));
1774
1775 m_language_runtimes[language] = runtime_sp;
1776 return runtime_sp.get();
1777 } else
1778 return (*pos).second.get();
Jim Ingham22777012010-09-23 02:01:19 +00001779}
1780
Kate Stoneb9c1b512016-09-06 20:57:50 +00001781CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1782 LanguageRuntime *runtime =
1783 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1784 if (runtime != nullptr &&
1785 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1786 return static_cast<CPPLanguageRuntime *>(runtime);
1787 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001788}
1789
Kate Stoneb9c1b512016-09-06 20:57:50 +00001790ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1791 LanguageRuntime *runtime =
1792 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1793 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1794 return static_cast<ObjCLanguageRuntime *>(runtime);
1795 return nullptr;
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001796}
1797
Kate Stoneb9c1b512016-09-06 20:57:50 +00001798bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1799 if (m_finalizing)
1800 return false;
1801
1802 if (in_value.IsDynamic())
1803 return false;
1804 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1805
1806 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1807 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1808 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1809 }
1810
1811 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1812 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1813 return true;
1814
1815 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1816 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001817}
1818
Kate Stoneb9c1b512016-09-06 20:57:50 +00001819void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1820 m_dynamic_checkers_ap.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001821}
1822
Kate Stoneb9c1b512016-09-06 20:57:50 +00001823BreakpointSiteList &Process::GetBreakpointSiteList() {
1824 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001825}
1826
Kate Stoneb9c1b512016-09-06 20:57:50 +00001827const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1828 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001829}
1830
Kate Stoneb9c1b512016-09-06 20:57:50 +00001831void Process::DisableAllBreakpointSites() {
1832 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1833 // bp_site->SetEnabled(true);
1834 DisableBreakpointSite(bp_site);
1835 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001836}
1837
Kate Stoneb9c1b512016-09-06 20:57:50 +00001838Error Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1839 Error error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001840
Kate Stoneb9c1b512016-09-06 20:57:50 +00001841 if (error.Success())
1842 m_breakpoint_site_list.Remove(break_id);
1843
1844 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001845}
1846
Kate Stoneb9c1b512016-09-06 20:57:50 +00001847Error Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1848 Error error;
1849 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1850 if (bp_site_sp) {
1851 if (bp_site_sp->IsEnabled())
1852 error = DisableBreakpointSite(bp_site_sp.get());
1853 } else {
1854 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1855 break_id);
1856 }
1857
1858 return error;
1859}
1860
1861Error Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1862 Error error;
1863 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1864 if (bp_site_sp) {
1865 if (!bp_site_sp->IsEnabled())
1866 error = EnableBreakpointSite(bp_site_sp.get());
1867 } else {
1868 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1869 break_id);
1870 }
1871 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001872}
1873
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001874lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001875Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1876 bool use_hardware) {
1877 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001878
Kate Stoneb9c1b512016-09-06 20:57:50 +00001879 bool show_error = true;
1880 switch (GetState()) {
1881 case eStateInvalid:
1882 case eStateUnloaded:
1883 case eStateConnected:
1884 case eStateAttaching:
1885 case eStateLaunching:
1886 case eStateDetached:
1887 case eStateExited:
1888 show_error = false;
1889 break;
1890
1891 case eStateStopped:
1892 case eStateRunning:
1893 case eStateStepping:
1894 case eStateCrashed:
1895 case eStateSuspended:
1896 show_error = IsAlive();
1897 break;
1898 }
1899
1900 // Reset the IsIndirect flag here, in case the location changes from
1901 // pointing to a indirect symbol to a regular symbol.
1902 owner->SetIsIndirect(false);
1903
1904 if (owner->ShouldResolveIndirectFunctions()) {
1905 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1906 if (symbol && symbol->IsIndirect()) {
1907 Error error;
1908 Address symbol_address = symbol->GetAddress();
1909 load_addr = ResolveIndirectFunction(&symbol_address, error);
1910 if (!error.Success() && show_error) {
1911 GetTarget().GetDebugger().GetErrorFile()->Printf(
1912 "warning: failed to resolve indirect function at 0x%" PRIx64
1913 " for breakpoint %i.%i: %s\n",
1914 symbol->GetLoadAddress(&GetTarget()),
1915 owner->GetBreakpoint().GetID(), owner->GetID(),
1916 error.AsCString() ? error.AsCString() : "unknown error");
1917 return LLDB_INVALID_BREAK_ID;
1918 }
1919 Address resolved_address(load_addr);
1920 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1921 owner->SetIsIndirect(true);
1922 } else
1923 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1924 } else
1925 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1926
1927 if (load_addr != LLDB_INVALID_ADDRESS) {
1928 BreakpointSiteSP bp_site_sp;
1929
1930 // Look up this breakpoint site. If it exists, then add this new owner,
1931 // otherwise
1932 // create a new breakpoint site and add it.
1933
1934 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1935
1936 if (bp_site_sp) {
1937 bp_site_sp->AddOwner(owner);
1938 owner->SetBreakpointSite(bp_site_sp);
1939 return bp_site_sp->GetID();
1940 } else {
1941 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1942 load_addr, use_hardware));
1943 if (bp_site_sp) {
1944 Error error = EnableBreakpointSite(bp_site_sp.get());
1945 if (error.Success()) {
1946 owner->SetBreakpointSite(bp_site_sp);
1947 return m_breakpoint_site_list.Add(bp_site_sp);
1948 } else {
1949 if (show_error) {
1950 // Report error for setting breakpoint...
1951 GetTarget().GetDebugger().GetErrorFile()->Printf(
1952 "warning: failed to set breakpoint site at 0x%" PRIx64
1953 " for breakpoint %i.%i: %s\n",
1954 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1955 error.AsCString() ? error.AsCString() : "unknown error");
1956 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001957 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001958 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001959 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001960 }
1961 // We failed to enable the breakpoint
1962 return LLDB_INVALID_BREAK_ID;
1963}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001964
Kate Stoneb9c1b512016-09-06 20:57:50 +00001965void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1966 lldb::user_id_t owner_loc_id,
1967 BreakpointSiteSP &bp_site_sp) {
1968 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1969 if (num_owners == 0) {
1970 // Don't try to disable the site if we don't have a live process anymore.
1971 if (IsAlive())
1972 DisableBreakpointSite(bp_site_sp.get());
1973 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1974 }
1975}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001976
Kate Stoneb9c1b512016-09-06 20:57:50 +00001977size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1978 uint8_t *buf) const {
1979 size_t bytes_removed = 0;
1980 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001981
Kate Stoneb9c1b512016-09-06 20:57:50 +00001982 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1983 bp_sites_in_range)) {
1984 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](
1985 BreakpointSite *bp_site) -> void {
1986 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1987 addr_t intersect_addr;
1988 size_t intersect_size;
1989 size_t opcode_offset;
1990 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1991 &intersect_size, &opcode_offset)) {
1992 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1993 assert(bp_addr < intersect_addr + intersect_size &&
1994 intersect_addr + intersect_size <= bp_addr + size);
1995 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1996 size_t buf_offset = intersect_addr - bp_addr;
1997 ::memcpy(buf + buf_offset,
1998 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1999 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002000 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002001 }
2002 });
2003 }
2004 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002005}
2006
Kate Stoneb9c1b512016-09-06 20:57:50 +00002007size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
2008 PlatformSP platform_sp(GetTarget().GetPlatform());
2009 if (platform_sp)
2010 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
2011 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012}
2013
Kate Stoneb9c1b512016-09-06 20:57:50 +00002014Error Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
2015 Error error;
2016 assert(bp_site != nullptr);
2017 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2018 const addr_t bp_addr = bp_site->GetLoadAddress();
2019 if (log)
2020 log->Printf(
2021 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
2022 bp_site->GetID(), (uint64_t)bp_addr);
2023 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002024 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002025 log->Printf(
2026 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2027 " -- already enabled",
2028 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002029 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002030 }
2031
2032 if (bp_addr == LLDB_INVALID_ADDRESS) {
2033 error.SetErrorString("BreakpointSite contains an invalid load address.");
2034 return error;
2035 }
2036 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2037 // trap for the breakpoint site
2038 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2039
2040 if (bp_opcode_size == 0) {
2041 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2042 "returned zero, unable to get breakpoint "
2043 "trap for address 0x%" PRIx64,
2044 bp_addr);
2045 } else {
2046 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2047
2048 if (bp_opcode_bytes == nullptr) {
2049 error.SetErrorString(
2050 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2051 return error;
2052 }
2053
2054 // Save the original opcode by reading it
2055 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2056 error) == bp_opcode_size) {
2057 // Write a software breakpoint in place of the original opcode
2058 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2059 bp_opcode_size) {
2060 uint8_t verify_bp_opcode_bytes[64];
2061 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2062 error) == bp_opcode_size) {
2063 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2064 bp_opcode_size) == 0) {
2065 bp_site->SetEnabled(true);
2066 bp_site->SetType(BreakpointSite::eSoftware);
2067 if (log)
2068 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2069 "addr = 0x%" PRIx64 " -- SUCCESS",
2070 bp_site->GetID(), (uint64_t)bp_addr);
2071 } else
2072 error.SetErrorString(
2073 "failed to verify the breakpoint trap in memory.");
2074 } else
2075 error.SetErrorString(
2076 "Unable to read memory to verify breakpoint trap.");
2077 } else
2078 error.SetErrorString("Unable to write breakpoint trap to memory.");
2079 } else
2080 error.SetErrorString("Unable to read memory at breakpoint address.");
2081 }
2082 if (log && error.Fail())
2083 log->Printf(
2084 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2085 " -- FAILED: %s",
2086 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2087 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002088}
2089
Kate Stoneb9c1b512016-09-06 20:57:50 +00002090Error Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2091 Error error;
2092 assert(bp_site != nullptr);
2093 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2094 addr_t bp_addr = bp_site->GetLoadAddress();
2095 lldb::user_id_t breakID = bp_site->GetID();
2096 if (log)
2097 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2098 ") addr = 0x%" PRIx64,
2099 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002100
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101 if (bp_site->IsHardware()) {
2102 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2103 } else if (bp_site->IsEnabled()) {
2104 const size_t break_op_size = bp_site->GetByteSize();
2105 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2106 if (break_op_size > 0) {
2107 // Clear a software breakpoint instruction
2108 uint8_t curr_break_op[8];
2109 assert(break_op_size <= sizeof(curr_break_op));
2110 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111
Kate Stoneb9c1b512016-09-06 20:57:50 +00002112 // Read the breakpoint opcode
2113 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2114 break_op_size) {
2115 bool verify = false;
2116 // Make sure the breakpoint opcode exists at this address
2117 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2118 break_op_found = true;
2119 // We found a valid breakpoint opcode at this address, now restore
2120 // the saved opcode.
2121 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2122 break_op_size, error) == break_op_size) {
2123 verify = true;
2124 } else
2125 error.SetErrorString(
2126 "Memory write failed when restoring original opcode.");
2127 } else {
2128 error.SetErrorString(
2129 "Original breakpoint trap is no longer in memory.");
2130 // Set verify to true and so we can check if the original opcode has
2131 // already been restored
2132 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002133 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002134
Kate Stoneb9c1b512016-09-06 20:57:50 +00002135 if (verify) {
2136 uint8_t verify_opcode[8];
2137 assert(break_op_size < sizeof(verify_opcode));
2138 // Verify that our original opcode made it back to the inferior
2139 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2140 break_op_size) {
2141 // compare the memory we just read with the original opcode
2142 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2143 break_op_size) == 0) {
2144 // SUCCESS
2145 bp_site->SetEnabled(false);
2146 if (log)
2147 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2148 "addr = 0x%" PRIx64 " -- SUCCESS",
2149 bp_site->GetID(), (uint64_t)bp_addr);
2150 return error;
2151 } else {
2152 if (break_op_found)
2153 error.SetErrorString("Failed to restore original opcode.");
2154 }
2155 } else
2156 error.SetErrorString("Failed to read memory to verify that "
2157 "breakpoint trap was restored.");
2158 }
2159 } else
2160 error.SetErrorString(
2161 "Unable to read memory that should contain the breakpoint trap.");
2162 }
2163 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002164 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002165 log->Printf(
2166 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2167 " -- already disabled",
2168 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002169 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002170 }
2171
2172 if (log)
2173 log->Printf(
2174 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2175 " -- FAILED: %s",
2176 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2177 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002178}
2179
Greg Clayton58be07b2011-01-07 06:08:19 +00002180// Uncomment to verify memory caching works after making changes to caching code
2181//#define VERIFY_MEMORY_READS
2182
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Error &error) {
2184 error.Clear();
2185 if (!GetDisableMemoryCache()) {
2186#if defined(VERIFY_MEMORY_READS)
2187 // Memory caching is enabled, with debug verification
2188
2189 if (buf && size) {
2190 // Uncomment the line below to make sure memory caching is working.
2191 // I ran this through the test suite and got no assertions, so I am
2192 // pretty confident this is working well. If any changes are made to
2193 // memory caching, uncomment the line below and test your changes!
2194
2195 // Verify all memory reads by using the cache first, then redundantly
2196 // reading the same memory from the inferior and comparing to make sure
2197 // everything is exactly the same.
2198 std::string verify_buf(size, '\0');
2199 assert(verify_buf.size() == size);
2200 const size_t cache_bytes_read =
2201 m_memory_cache.Read(this, addr, buf, size, error);
2202 Error verify_error;
2203 const size_t verify_bytes_read =
2204 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2205 verify_buf.size(), verify_error);
2206 assert(cache_bytes_read == verify_bytes_read);
2207 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2208 assert(verify_error.Success() == error.Success());
2209 return cache_bytes_read;
2210 }
2211 return 0;
2212#else // !defined(VERIFY_MEMORY_READS)
2213 // Memory caching is enabled, without debug verification
2214
2215 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002216#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002217 } else {
2218 // Memory caching is disabled
2219
2220 return ReadMemoryFromInferior(addr, buf, size, error);
2221 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002222}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002223
2224size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2225 Error &error) {
2226 char buf[256];
2227 out_str.clear();
2228 addr_t curr_addr = addr;
2229 while (true) {
2230 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2231 if (length == 0)
2232 break;
2233 out_str.append(buf, length);
2234 // If we got "length - 1" bytes, we didn't get the whole C string, we
2235 // need to read some more characters
2236 if (length == sizeof(buf) - 1)
2237 curr_addr += length;
2238 else
2239 break;
2240 }
2241 return out_str.size();
2242}
2243
2244size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
2245 Error &error, size_t type_width) {
2246 size_t total_bytes_read = 0;
2247 if (dst && max_bytes && type_width && max_bytes >= type_width) {
2248 // Ensure a null terminator independent of the number of bytes that is read.
2249 memset(dst, 0, max_bytes);
2250 size_t bytes_left = max_bytes - type_width;
2251
2252 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2253 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2254 "string with more than 4 bytes "
2255 "per character!");
2256
Greg Clayton4c82d422012-05-18 23:20:01 +00002257 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002258 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2259 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002260
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261 error.Clear();
2262 while (bytes_left > 0 && error.Success()) {
2263 addr_t cache_line_bytes_left =
2264 cache_line_size - (curr_addr % cache_line_size);
2265 addr_t bytes_to_read =
2266 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2267 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002268
Kate Stoneb9c1b512016-09-06 20:57:50 +00002269 if (bytes_read == 0)
2270 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002271
Kate Stoneb9c1b512016-09-06 20:57:50 +00002272 // Search for a null terminator of correct size and alignment in
2273 // bytes_read
2274 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2275 for (size_t i = aligned_start;
2276 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2277 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2278 error.Clear();
2279 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002280 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002281
2282 total_bytes_read += bytes_read;
2283 curr_dst += bytes_read;
2284 curr_addr += bytes_read;
2285 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002286 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002287 } else {
2288 if (max_bytes)
2289 error.SetErrorString("invalid arguments");
2290 }
2291 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002292}
2293
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294// Deprecated in favor of ReadStringFromMemory which has wchar support and
2295// correct code to find
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002296// null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002297size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
2298 size_t dst_max_len, Error &result_error) {
2299 size_t total_cstr_len = 0;
2300 if (dst && dst_max_len) {
2301 result_error.Clear();
2302 // NULL out everything just to be safe
2303 memset(dst, 0, dst_max_len);
2304 Error error;
2305 addr_t curr_addr = addr;
2306 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2307 size_t bytes_left = dst_max_len - 1;
2308 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002309
Kate Stoneb9c1b512016-09-06 20:57:50 +00002310 while (bytes_left > 0) {
2311 addr_t cache_line_bytes_left =
2312 cache_line_size - (curr_addr % cache_line_size);
2313 addr_t bytes_to_read =
2314 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2315 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002316
Kate Stoneb9c1b512016-09-06 20:57:50 +00002317 if (bytes_read == 0) {
2318 result_error = error;
2319 dst[total_cstr_len] = '\0';
2320 break;
2321 }
2322 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002323
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324 total_cstr_len += len;
2325
2326 if (len < bytes_to_read)
2327 break;
2328
2329 curr_dst += bytes_read;
2330 curr_addr += bytes_read;
2331 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002332 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002333 } else {
2334 if (dst == nullptr)
2335 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002336 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002337 result_error.Clear();
2338 }
2339 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002340}
2341
Kate Stoneb9c1b512016-09-06 20:57:50 +00002342size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2343 Error &error) {
2344 if (buf == nullptr || size == 0)
2345 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002346
Kate Stoneb9c1b512016-09-06 20:57:50 +00002347 size_t bytes_read = 0;
2348 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002349
Kate Stoneb9c1b512016-09-06 20:57:50 +00002350 while (bytes_read < size) {
2351 const size_t curr_size = size - bytes_read;
2352 const size_t curr_bytes_read =
2353 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2354 bytes_read += curr_bytes_read;
2355 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2356 break;
2357 }
2358
2359 // Replace any software breakpoint opcodes that fall into this range back
2360 // into "buf" before we return
2361 if (bytes_read > 0)
2362 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2363 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002364}
2365
Kate Stoneb9c1b512016-09-06 20:57:50 +00002366uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2367 size_t integer_byte_size,
2368 uint64_t fail_value,
2369 Error &error) {
2370 Scalar scalar;
2371 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2372 error))
2373 return scalar.ULongLong(fail_value);
2374 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002375}
2376
Kate Stoneb9c1b512016-09-06 20:57:50 +00002377int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2378 size_t integer_byte_size,
2379 int64_t fail_value, Error &error) {
2380 Scalar scalar;
2381 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2382 error))
2383 return scalar.SLongLong(fail_value);
2384 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002385}
2386
Kate Stoneb9c1b512016-09-06 20:57:50 +00002387addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error) {
2388 Scalar scalar;
2389 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2390 error))
2391 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2392 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002393}
2394
Kate Stoneb9c1b512016-09-06 20:57:50 +00002395bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
2396 Error &error) {
2397 Scalar scalar;
2398 const uint32_t addr_byte_size = GetAddressByteSize();
2399 if (addr_byte_size <= 4)
2400 scalar = (uint32_t)ptr_value;
2401 else
2402 scalar = ptr_value;
2403 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2404 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002405}
2406
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2408 Error &error) {
2409 size_t bytes_written = 0;
2410 const uint8_t *bytes = (const uint8_t *)buf;
2411
2412 while (bytes_written < size) {
2413 const size_t curr_size = size - bytes_written;
2414 const size_t curr_bytes_written = DoWriteMemory(
2415 addr + bytes_written, bytes + bytes_written, curr_size, error);
2416 bytes_written += curr_bytes_written;
2417 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2418 break;
2419 }
2420 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002421}
2422
Kate Stoneb9c1b512016-09-06 20:57:50 +00002423size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2424 Error &error) {
2425#if defined(ENABLE_MEMORY_CACHING)
2426 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002427#endif
2428
Kate Stoneb9c1b512016-09-06 20:57:50 +00002429 if (buf == nullptr || size == 0)
2430 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002431
Kate Stoneb9c1b512016-09-06 20:57:50 +00002432 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002433
Kate Stoneb9c1b512016-09-06 20:57:50 +00002434 // We need to write any data that would go where any current software traps
2435 // (enabled software breakpoints) any software traps (breakpoints) that we
2436 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002437
Kate Stoneb9c1b512016-09-06 20:57:50 +00002438 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002439
Kate Stoneb9c1b512016-09-06 20:57:50 +00002440 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2441 bp_sites_in_range)) {
2442 // No breakpoint sites overlap
2443 if (bp_sites_in_range.IsEmpty())
2444 return WriteMemoryPrivate(addr, buf, size, error);
2445 else {
2446 const uint8_t *ubuf = (const uint8_t *)buf;
2447 uint64_t bytes_written = 0;
2448
2449 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2450 &error](BreakpointSite *bp) -> void {
2451
2452 if (error.Success()) {
2453 addr_t intersect_addr;
2454 size_t intersect_size;
2455 size_t opcode_offset;
2456 const bool intersects = bp->IntersectsRange(
2457 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2458 UNUSED_IF_ASSERT_DISABLED(intersects);
2459 assert(intersects);
2460 assert(addr <= intersect_addr && intersect_addr < addr + size);
2461 assert(addr < intersect_addr + intersect_size &&
2462 intersect_addr + intersect_size <= addr + size);
2463 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2464
2465 // Check for bytes before this breakpoint
2466 const addr_t curr_addr = addr + bytes_written;
2467 if (intersect_addr > curr_addr) {
2468 // There are some bytes before this breakpoint that we need to
2469 // just write to memory
2470 size_t curr_size = intersect_addr - curr_addr;
2471 size_t curr_bytes_written = WriteMemoryPrivate(
2472 curr_addr, ubuf + bytes_written, curr_size, error);
2473 bytes_written += curr_bytes_written;
2474 if (curr_bytes_written != curr_size) {
2475 // We weren't able to write all of the requested bytes, we
2476 // are done looping and will return the number of bytes that
2477 // we have written so far.
2478 if (error.Success())
2479 error.SetErrorToGenericError();
2480 }
2481 }
2482 // Now write any bytes that would cover up any software breakpoints
2483 // directly into the breakpoint opcode buffer
2484 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2485 ubuf + bytes_written, intersect_size);
2486 bytes_written += intersect_size;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002487 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002488 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002489
Kate Stoneb9c1b512016-09-06 20:57:50 +00002490 if (bytes_written < size)
2491 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2492 size - bytes_written, error);
2493 }
2494 } else {
2495 return WriteMemoryPrivate(addr, buf, size, error);
2496 }
2497
2498 // Write any remaining bytes after the last breakpoint if we have any left
2499 return 0; // bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002500}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002501
Kate Stoneb9c1b512016-09-06 20:57:50 +00002502size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2503 size_t byte_size, Error &error) {
2504 if (byte_size == UINT32_MAX)
2505 byte_size = scalar.GetByteSize();
2506 if (byte_size > 0) {
2507 uint8_t buf[32];
2508 const size_t mem_size =
2509 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2510 if (mem_size > 0)
2511 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002512 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002513 error.SetErrorString("failed to get scalar as memory data");
2514 } else {
2515 error.SetErrorString("invalid scalar value");
2516 }
2517 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002518}
2519
Kate Stoneb9c1b512016-09-06 20:57:50 +00002520size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2521 bool is_signed, Scalar &scalar,
2522 Error &error) {
2523 uint64_t uval = 0;
2524 if (byte_size == 0) {
2525 error.SetErrorString("byte size is zero");
2526 } else if (byte_size & (byte_size - 1)) {
2527 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2528 byte_size);
2529 } else if (byte_size <= sizeof(uval)) {
2530 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2531 if (bytes_read == byte_size) {
2532 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2533 GetAddressByteSize());
2534 lldb::offset_t offset = 0;
2535 if (byte_size <= 4)
2536 scalar = data.GetMaxU32(&offset, byte_size);
2537 else
2538 scalar = data.GetMaxU64(&offset, byte_size);
2539 if (is_signed)
2540 scalar.SignExtend(byte_size * 8);
2541 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002542 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002543 } else {
2544 error.SetErrorStringWithFormat(
2545 "byte size of %u is too large for integer scalar type", byte_size);
2546 }
2547 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002548}
2549
Greg Claytond495c532011-05-17 03:37:42 +00002550#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002551addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2552 Error &error) {
2553 if (GetPrivateState() != eStateStopped)
2554 return LLDB_INVALID_ADDRESS;
2555
2556#if defined(USE_ALLOCATE_MEMORY_CACHE)
2557 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002558#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002559 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2560 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2561 if (log)
2562 log->Printf("Process::AllocateMemory(size=%" PRIu64
2563 ", permissions=%s) => 0x%16.16" PRIx64
2564 " (m_stop_id = %u m_memory_id = %u)",
2565 (uint64_t)size, GetPermissionsAsCString(permissions),
2566 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2567 m_mod_id.GetMemoryID());
2568 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002569#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002570}
2571
Kate Stoneb9c1b512016-09-06 20:57:50 +00002572addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2573 Error &error) {
2574 addr_t return_addr = AllocateMemory(size, permissions, error);
2575 if (error.Success()) {
2576 std::string buffer(size, 0);
2577 WriteMemory(return_addr, buffer.c_str(), size, error);
2578 }
2579 return return_addr;
2580}
2581
2582bool Process::CanJIT() {
2583 if (m_can_jit == eCanJITDontKnow) {
2584 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2585 Error err;
2586
2587 uint64_t allocated_memory = AllocateMemory(
2588 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2589 err);
2590
2591 if (err.Success()) {
2592 m_can_jit = eCanJITYes;
2593 if (log)
2594 log->Printf("Process::%s pid %" PRIu64
2595 " allocation test passed, CanJIT () is true",
2596 __FUNCTION__, GetID());
2597 } else {
2598 m_can_jit = eCanJITNo;
2599 if (log)
2600 log->Printf("Process::%s pid %" PRIu64
2601 " allocation test failed, CanJIT () is false: %s",
2602 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002603 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002604
2605 DeallocateMemory(allocated_memory);
2606 }
2607
2608 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002609}
2610
Kate Stoneb9c1b512016-09-06 20:57:50 +00002611void Process::SetCanJIT(bool can_jit) {
2612 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002613}
2614
Kate Stoneb9c1b512016-09-06 20:57:50 +00002615void Process::SetCanRunCode(bool can_run_code) {
2616 SetCanJIT(can_run_code);
2617 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002618}
2619
Kate Stoneb9c1b512016-09-06 20:57:50 +00002620Error Process::DeallocateMemory(addr_t ptr) {
2621 Error error;
2622#if defined(USE_ALLOCATE_MEMORY_CACHE)
2623 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2624 error.SetErrorStringWithFormat(
2625 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2626 }
Greg Claytond495c532011-05-17 03:37:42 +00002627#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002628 error = DoDeallocateMemory(ptr);
2629
2630 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2631 if (log)
2632 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2633 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2634 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2635 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002636#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002637 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002638}
2639
Kate Stoneb9c1b512016-09-06 20:57:50 +00002640ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2641 lldb::addr_t header_addr,
2642 size_t size_to_read) {
2643 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2644 if (log) {
2645 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2646 file_spec.GetPath().c_str());
2647 }
2648 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2649 if (module_sp) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002650 Error error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002651 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2652 shared_from_this(), header_addr, error, size_to_read);
2653 if (objfile)
2654 return module_sp;
2655 }
2656 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002657}
2658
Kate Stoneb9c1b512016-09-06 20:57:50 +00002659bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2660 uint32_t &permissions) {
2661 MemoryRegionInfo range_info;
2662 permissions = 0;
2663 Error error(GetMemoryRegionInfo(load_addr, range_info));
2664 if (!error.Success())
2665 return false;
2666 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2667 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2668 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2669 return false;
2670 }
2671
2672 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2673 permissions |= lldb::ePermissionsReadable;
2674
2675 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2676 permissions |= lldb::ePermissionsWritable;
2677
2678 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2679 permissions |= lldb::ePermissionsExecutable;
2680
2681 return true;
2682}
2683
2684Error Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2685 Error error;
2686 error.SetErrorString("watchpoints are not supported");
2687 return error;
2688}
2689
2690Error Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2691 Error error;
2692 error.SetErrorString("watchpoints are not supported");
2693 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694}
2695
2696StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002697Process::WaitForProcessStopPrivate(EventSP &event_sp,
2698 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002699 StateType state;
2700 // Now wait for the process to launch and return control to us, and then
2701 // call DidLaunch:
2702 while (true) {
2703 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002704 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002705
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706 if (StateIsStoppedState(state, false))
2707 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002708
Kate Stoneb9c1b512016-09-06 20:57:50 +00002709 // If state is invalid, then we timed out
2710 if (state == eStateInvalid)
2711 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002712
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713 if (event_sp)
2714 HandlePrivateEvent(event_sp);
2715 }
2716 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717}
2718
Kate Stoneb9c1b512016-09-06 20:57:50 +00002719void Process::LoadOperatingSystemPlugin(bool flush) {
2720 if (flush)
2721 m_thread_list.Clear();
2722 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2723 if (flush)
2724 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002725}
2726
Kate Stoneb9c1b512016-09-06 20:57:50 +00002727Error Process::Launch(ProcessLaunchInfo &launch_info) {
2728 Error error;
2729 m_abi_sp.reset();
2730 m_dyld_ap.reset();
2731 m_jit_loaders_ap.reset();
2732 m_system_runtime_ap.reset();
2733 m_os_ap.reset();
2734 m_process_input_reader.reset();
2735 m_stop_info_override_callback = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736
Kate Stoneb9c1b512016-09-06 20:57:50 +00002737 Module *exe_module = GetTarget().GetExecutableModulePointer();
2738 if (exe_module) {
2739 char local_exec_file_path[PATH_MAX];
2740 char platform_exec_file_path[PATH_MAX];
2741 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2742 sizeof(local_exec_file_path));
2743 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2744 sizeof(platform_exec_file_path));
2745 if (exe_module->GetFileSpec().Exists()) {
2746 // Install anything that might need to be installed prior to launching.
2747 // For host systems, this will do nothing, but if we are connected to a
2748 // remote platform it will install any needed binaries
2749 error = GetTarget().Install(&launch_info);
2750 if (error.Fail())
2751 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002752
Kate Stoneb9c1b512016-09-06 20:57:50 +00002753 if (PrivateStateThreadIsValid())
2754 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002755
Kate Stoneb9c1b512016-09-06 20:57:50 +00002756 error = WillLaunch(exe_module);
2757 if (error.Success()) {
2758 const bool restarted = false;
2759 SetPublicState(eStateLaunching, restarted);
2760 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002761
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762 if (m_public_run_lock.TrySetRunning()) {
2763 // Now launch using these arguments.
2764 error = DoLaunch(exe_module, launch_info);
2765 } else {
2766 // This shouldn't happen
2767 error.SetErrorString("failed to acquire process run lock");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002768 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002769
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770 if (error.Fail()) {
2771 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2772 SetID(LLDB_INVALID_PROCESS_ID);
2773 const char *error_string = error.AsCString();
2774 if (error_string == nullptr)
2775 error_string = "launch failed";
2776 SetExitStatus(-1, error_string);
2777 }
2778 } else {
2779 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002780 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Greg Clayton35824e32015-02-20 20:59:47 +00002781
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782 if (state == eStateInvalid || !event_sp) {
2783 // We were able to launch the process, but we failed to
2784 // catch the initial stop.
2785 error.SetErrorString("failed to catch stop after launch");
2786 SetExitStatus(0, "failed to catch stop after launch");
2787 Destroy(false);
2788 } else if (state == eStateStopped || state == eStateCrashed) {
2789 DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002790
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791 DynamicLoader *dyld = GetDynamicLoader();
2792 if (dyld)
2793 dyld->DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002794
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 GetJITLoaders().DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002796
Kate Stoneb9c1b512016-09-06 20:57:50 +00002797 SystemRuntime *system_runtime = GetSystemRuntime();
2798 if (system_runtime)
2799 system_runtime->DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002800
Kate Stoneb9c1b512016-09-06 20:57:50 +00002801 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002802
Kate Stoneb9c1b512016-09-06 20:57:50 +00002803 // Note, the stop event was consumed above, but not handled. This
2804 // was done
2805 // to give DidLaunch a chance to run. The target is either stopped
2806 // or crashed.
2807 // Directly set the state. This is done to prevent a stop message
2808 // with a bunch
2809 // of spurious output on thread status, as well as not pop a
2810 // ProcessIOHandler.
2811 SetPublicState(state, false);
Greg Claytonc3776bf2012-02-09 06:16:32 +00002812
Kate Stoneb9c1b512016-09-06 20:57:50 +00002813 if (PrivateStateThreadIsValid())
2814 ResumePrivateStateThread();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002815 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002816 StartPrivateStateThread();
Todd Fiala76e0fc92014-08-27 22:58:26 +00002817
Kate Stoneb9c1b512016-09-06 20:57:50 +00002818 m_stop_info_override_callback =
2819 GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002820
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 // Target was stopped at entry as was intended. Need to notify the
2822 // listeners
2823 // about it.
2824 if (state == eStateStopped &&
2825 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2826 HandlePrivateEvent(event_sp);
2827 } else if (state == eStateExited) {
2828 // We exited while trying to launch somehow. Don't call DidLaunch
2829 // as that's
2830 // not likely to work, and return an invalid pid.
2831 HandlePrivateEvent(event_sp);
2832 }
2833 }
2834 }
2835 } else {
2836 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2837 local_exec_file_path);
Jim Inghambb3a2832011-01-29 01:49:25 +00002838 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002839 }
2840 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002841}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002842
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843Error Process::LoadCore() {
2844 Error error = DoLoadCore();
2845 if (error.Success()) {
2846 ListenerSP listener_sp(
2847 Listener::MakeListener("lldb.process.load_core_listener"));
2848 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002849
Kate Stoneb9c1b512016-09-06 20:57:50 +00002850 if (PrivateStateThreadIsValid())
2851 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002852 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002853 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002854
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002856 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002857 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002858
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002859 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002860
Kate Stoneb9c1b512016-09-06 20:57:50 +00002861 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002862 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002863 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002864
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002865 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866 // We successfully loaded a core file, now pretend we stopped so we can
2867 // show all of the threads in the core file and explore the crashed
2868 // state.
2869 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002870
Kate Stoneb9c1b512016-09-06 20:57:50 +00002871 // Wait indefinitely for a stopped event since we just posted one above...
2872 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00002873 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002874 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2875
2876 if (!StateIsStoppedState(state, false)) {
2877 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2878 if (log)
2879 log->Printf("Process::Halt() failed to stop, state is: %s",
2880 StateAsCString(state));
2881 error.SetErrorString(
2882 "Did not get stopped event after loading the core file.");
2883 }
2884 RestoreProcessEvents();
2885 }
2886 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002887}
2888
Kate Stoneb9c1b512016-09-06 20:57:50 +00002889DynamicLoader *Process::GetDynamicLoader() {
2890 if (!m_dyld_ap)
2891 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2892 return m_dyld_ap.get();
2893}
2894
2895const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2896
2897JITLoaderList &Process::GetJITLoaders() {
2898 if (!m_jit_loaders_ap) {
2899 m_jit_loaders_ap.reset(new JITLoaderList());
2900 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2901 }
2902 return *m_jit_loaders_ap;
2903}
2904
2905SystemRuntime *Process::GetSystemRuntime() {
2906 if (!m_system_runtime_ap)
2907 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2908 return m_system_runtime_ap.get();
2909}
2910
2911Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2912 uint32_t exec_count)
2913 : NextEventAction(process), m_exec_count(exec_count) {
2914 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2915 if (log)
2916 log->Printf(
2917 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2918 __FUNCTION__, static_cast<void *>(process), exec_count);
2919}
2920
2921Process::NextEventAction::EventActionResult
2922Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2923 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2924
2925 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2926 if (log)
2927 log->Printf(
2928 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2929 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2930
2931 switch (state) {
2932 case eStateAttaching:
2933 return eEventActionSuccess;
2934
2935 case eStateRunning:
2936 case eStateConnected:
2937 return eEventActionRetry;
2938
2939 case eStateStopped:
2940 case eStateCrashed:
2941 // During attach, prior to sending the eStateStopped event,
2942 // lldb_private::Process subclasses must set the new process ID.
2943 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2944 // We don't want these events to be reported, so go set the ShouldReportStop
2945 // here:
2946 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2947
2948 if (m_exec_count > 0) {
2949 --m_exec_count;
2950
2951 if (log)
2952 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2953 "remaining exec count to %" PRIu32 ", requesting resume",
2954 __FUNCTION__, StateAsCString(state), m_exec_count);
2955
2956 RequestResume();
2957 return eEventActionRetry;
2958 } else {
2959 if (log)
2960 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2961 "execs expected to start, continuing with attach",
2962 __FUNCTION__, StateAsCString(state));
2963
2964 m_process->CompleteAttach();
2965 return eEventActionSuccess;
2966 }
2967 break;
2968
2969 default:
2970 case eStateExited:
2971 case eStateInvalid:
2972 break;
2973 }
2974
2975 m_exit_string.assign("No valid Process");
2976 return eEventActionExit;
2977}
2978
2979Process::NextEventAction::EventActionResult
2980Process::AttachCompletionHandler::HandleBeingInterrupted() {
2981 return eEventActionSuccess;
2982}
2983
2984const char *Process::AttachCompletionHandler::GetExitString() {
2985 return m_exit_string.c_str();
2986}
2987
2988ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2989 if (m_listener_sp)
2990 return m_listener_sp;
2991 else
2992 return debugger.GetListener();
2993}
2994
2995Error Process::Attach(ProcessAttachInfo &attach_info) {
2996 m_abi_sp.reset();
2997 m_process_input_reader.reset();
2998 m_dyld_ap.reset();
2999 m_jit_loaders_ap.reset();
3000 m_system_runtime_ap.reset();
3001 m_os_ap.reset();
3002 m_stop_info_override_callback = nullptr;
3003
3004 lldb::pid_t attach_pid = attach_info.GetProcessID();
3005 Error error;
3006 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
3007 char process_name[PATH_MAX];
3008
3009 if (attach_info.GetExecutableFile().GetPath(process_name,
3010 sizeof(process_name))) {
3011 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3012
3013 if (wait_for_launch) {
3014 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3015 if (error.Success()) {
3016 if (m_public_run_lock.TrySetRunning()) {
3017 m_should_detach = true;
3018 const bool restarted = false;
3019 SetPublicState(eStateAttaching, restarted);
3020 // Now attach using these arguments.
3021 error = DoAttachToProcessWithName(process_name, attach_info);
3022 } else {
3023 // This shouldn't happen
3024 error.SetErrorString("failed to acquire process run lock");
3025 }
3026
3027 if (error.Fail()) {
3028 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3029 SetID(LLDB_INVALID_PROCESS_ID);
3030 if (error.AsCString() == nullptr)
3031 error.SetErrorString("attach failed");
3032
3033 SetExitStatus(-1, error.AsCString());
3034 }
3035 } else {
3036 SetNextEventAction(new Process::AttachCompletionHandler(
3037 this, attach_info.GetResumeCount()));
3038 StartPrivateStateThread();
3039 }
3040 return error;
3041 }
3042 } else {
3043 ProcessInstanceInfoList process_infos;
3044 PlatformSP platform_sp(GetTarget().GetPlatform());
3045
3046 if (platform_sp) {
3047 ProcessInstanceInfoMatch match_info;
3048 match_info.GetProcessInfo() = attach_info;
3049 match_info.SetNameMatchType(eNameMatchEquals);
3050 platform_sp->FindProcesses(match_info, process_infos);
3051 const uint32_t num_matches = process_infos.GetSize();
3052 if (num_matches == 1) {
3053 attach_pid = process_infos.GetProcessIDAtIndex(0);
3054 // Fall through and attach using the above process ID
3055 } else {
3056 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3057 process_name, sizeof(process_name));
3058 if (num_matches > 1) {
3059 StreamString s;
3060 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3061 false);
3062 for (size_t i = 0; i < num_matches; i++) {
3063 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3064 s, platform_sp.get(), true, false);
3065 }
3066 error.SetErrorStringWithFormat(
3067 "more than one process named %s:\n%s", process_name,
3068 s.GetData());
3069 } else
3070 error.SetErrorStringWithFormat(
3071 "could not find a process named %s", process_name);
3072 }
3073 } else {
3074 error.SetErrorString(
3075 "invalid platform, can't find processes by name");
3076 return error;
3077 }
3078 }
3079 } else {
3080 error.SetErrorString("invalid process name");
3081 }
3082 }
3083
3084 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3085 error = WillAttachToProcessWithID(attach_pid);
3086 if (error.Success()) {
3087
3088 if (m_public_run_lock.TrySetRunning()) {
3089 // Now attach using these arguments.
3090 m_should_detach = true;
3091 const bool restarted = false;
3092 SetPublicState(eStateAttaching, restarted);
3093 error = DoAttachToProcessWithID(attach_pid, attach_info);
3094 } else {
3095 // This shouldn't happen
3096 error.SetErrorString("failed to acquire process run lock");
3097 }
3098
3099 if (error.Success()) {
3100 SetNextEventAction(new Process::AttachCompletionHandler(
3101 this, attach_info.GetResumeCount()));
3102 StartPrivateStateThread();
3103 } else {
Greg Clayton71337622011-02-24 22:24:29 +00003104 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003105 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003106
Kate Stoneb9c1b512016-09-06 20:57:50 +00003107 const char *error_string = error.AsCString();
3108 if (error_string == nullptr)
3109 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00003110
Kate Stoneb9c1b512016-09-06 20:57:50 +00003111 SetExitStatus(-1, error_string);
3112 }
Greg Claytonb766a732011-02-04 01:58:07 +00003113 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003114 }
3115 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00003116}
3117
Kate Stoneb9c1b512016-09-06 20:57:50 +00003118void Process::CompleteAttach() {
3119 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3120 LIBLLDB_LOG_TARGET));
3121 if (log)
3122 log->Printf("Process::%s()", __FUNCTION__);
3123
3124 // Let the process subclass figure out at much as it can about the process
3125 // before we go looking for a dynamic loader plug-in.
3126 ArchSpec process_arch;
3127 DidAttach(process_arch);
3128
3129 if (process_arch.IsValid()) {
3130 GetTarget().SetArchitecture(process_arch);
3131 if (log) {
3132 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3133 log->Printf("Process::%s replacing process architecture with DidAttach() "
3134 "architecture: %s",
3135 __FUNCTION__, triple_str ? triple_str : "<null>");
3136 }
3137 }
3138
3139 // We just attached. If we have a platform, ask it for the process
3140 // architecture, and if it isn't
3141 // the same as the one we've already set, switch architectures.
3142 PlatformSP platform_sp(GetTarget().GetPlatform());
3143 assert(platform_sp);
3144 if (platform_sp) {
3145 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3146 if (target_arch.IsValid() &&
3147 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3148 ArchSpec platform_arch;
3149 platform_sp =
3150 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3151 if (platform_sp) {
3152 GetTarget().SetPlatform(platform_sp);
3153 GetTarget().SetArchitecture(platform_arch);
3154 if (log)
3155 log->Printf("Process::%s switching platform to %s and architecture "
3156 "to %s based on info from attach",
3157 __FUNCTION__, platform_sp->GetName().AsCString(""),
3158 platform_arch.GetTriple().getTriple().c_str());
3159 }
3160 } else if (!process_arch.IsValid()) {
3161 ProcessInstanceInfo process_info;
3162 GetProcessInfo(process_info);
3163 const ArchSpec &process_arch = process_info.GetArchitecture();
3164 if (process_arch.IsValid() &&
3165 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3166 GetTarget().SetArchitecture(process_arch);
3167 if (log)
3168 log->Printf("Process::%s switching architecture to %s based on info "
3169 "the platform retrieved for pid %" PRIu64,
3170 __FUNCTION__,
3171 process_arch.GetTriple().getTriple().c_str(), GetID());
3172 }
3173 }
3174 }
3175
3176 // We have completed the attach, now it is time to find the dynamic loader
3177 // plug-in
3178 DynamicLoader *dyld = GetDynamicLoader();
3179 if (dyld) {
3180 dyld->DidAttach();
3181 if (log) {
3182 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3183 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3184 "executable is %s (using %s plugin)",
3185 __FUNCTION__,
3186 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3187 : "<none>",
3188 dyld->GetPluginName().AsCString("<unnamed>"));
3189 }
3190 }
3191
3192 GetJITLoaders().DidAttach();
3193
3194 SystemRuntime *system_runtime = GetSystemRuntime();
3195 if (system_runtime) {
3196 system_runtime->DidAttach();
3197 if (log) {
3198 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3199 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3200 "executable is %s (using %s plugin)",
3201 __FUNCTION__,
3202 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3203 : "<none>",
3204 system_runtime->GetPluginName().AsCString("<unnamed>"));
3205 }
3206 }
3207
3208 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
3209 // Figure out which one is the executable, and set that in our target:
3210 const ModuleList &target_modules = GetTarget().GetImages();
3211 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3212 size_t num_modules = target_modules.GetSize();
3213 ModuleSP new_executable_module_sp;
3214
3215 for (size_t i = 0; i < num_modules; i++) {
3216 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3217 if (module_sp && module_sp->IsExecutable()) {
3218 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3219 new_executable_module_sp = module_sp;
3220 break;
3221 }
3222 }
3223 if (new_executable_module_sp) {
3224 GetTarget().SetExecutableModule(new_executable_module_sp, false);
3225 if (log) {
3226 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3227 log->Printf(
3228 "Process::%s after looping through modules, target executable is %s",
3229 __FUNCTION__,
3230 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3231 : "<none>");
3232 }
3233 }
3234
3235 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
3236}
3237
Zachary Turner31659452016-11-17 21:15:14 +00003238Error Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003239 m_abi_sp.reset();
3240 m_process_input_reader.reset();
3241
3242 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003243 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003244
3245 Error error(DoConnectRemote(strm, remote_url));
3246 if (error.Success()) {
3247 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3248 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003249 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003250
3251 if (state == eStateStopped || state == eStateCrashed) {
3252 // If we attached and actually have a process on the other end, then
3253 // this ended up being the equivalent of an attach.
3254 CompleteAttach();
3255
3256 // This delays passing the stopped event to listeners till
3257 // CompleteAttach gets a chance to complete...
3258 HandlePrivateEvent(event_sp);
3259 }
3260 }
3261
3262 if (PrivateStateThreadIsValid())
3263 ResumePrivateStateThread();
3264 else
3265 StartPrivateStateThread();
3266 }
3267 return error;
3268}
3269
3270Error Process::PrivateResume() {
3271 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3272 LIBLLDB_LOG_STEP));
3273 if (log)
3274 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3275 "private state: %s",
3276 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3277 StateAsCString(m_private_state.GetValue()));
3278
3279 Error error(WillResume());
3280 // Tell the process it is about to resume before the thread list
3281 if (error.Success()) {
3282 // Now let the thread list know we are about to resume so it
3283 // can let all of our threads know that they are about to be
3284 // resumed. Threads will each be called with
3285 // Thread::WillResume(StateType) where StateType contains the state
3286 // that they are supposed to have when the process is resumed
3287 // (suspended/running/stepping). Threads should also check
3288 // their resume signal in lldb::Thread::GetResumeSignal()
3289 // to see if they are supposed to start back up with a signal.
3290 if (m_thread_list.WillResume()) {
3291 // Last thing, do the PreResumeActions.
3292 if (!RunPreResumeActions()) {
3293 error.SetErrorStringWithFormat(
3294 "Process::PrivateResume PreResumeActions failed, not resuming.");
3295 } else {
3296 m_mod_id.BumpResumeID();
3297 error = DoResume();
3298 if (error.Success()) {
3299 DidResume();
3300 m_thread_list.DidResume();
3301 if (log)
3302 log->Printf("Process thinks the process has resumed.");
3303 }
3304 }
3305 } else {
3306 // Somebody wanted to run without running (e.g. we were faking a step from
3307 // one frame of a set of inlined
3308 // frames that share the same PC to another.) So generate a continue & a
3309 // stopped event,
3310 // and let the world handle them.
3311 if (log)
3312 log->Printf(
3313 "Process::PrivateResume() asked to simulate a start & stop.");
3314
3315 SetPrivateState(eStateRunning);
3316 SetPrivateState(eStateStopped);
3317 }
3318 } else if (log)
3319 log->Printf("Process::PrivateResume() got an error \"%s\".",
3320 error.AsCString("<unknown error>"));
3321 return error;
3322}
3323
3324Error Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3325 if (!StateIsRunningState(m_public_state.GetValue()))
3326 return Error("Process is not running.");
3327
3328 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3329 // in case it was already set and some thread plan logic calls halt on its
3330 // own.
3331 m_clear_thread_plans_on_stop |= clear_thread_plans;
3332
3333 ListenerSP halt_listener_sp(
3334 Listener::MakeListener("lldb.process.halt_listener"));
3335 HijackProcessEvents(halt_listener_sp);
3336
3337 EventSP event_sp;
3338
3339 SendAsyncInterrupt();
3340
3341 if (m_public_state.GetValue() == eStateAttaching) {
3342 // Don't hijack and eat the eStateExited as the code that was doing
3343 // the attach will be waiting for this event...
3344 RestoreProcessEvents();
3345 SetExitStatus(SIGKILL, "Cancelled async attach.");
3346 Destroy(false);
Mehdi Aminic1edf562016-11-11 04:29:25 +00003347 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003348 }
3349
3350 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003351 StateType state = WaitForProcessToStop(
3352 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003353 RestoreProcessEvents();
3354
3355 if (state == eStateInvalid || !event_sp) {
3356 // We timed out and didn't get a stop event...
3357 return Error("Halt timed out. State = %s", StateAsCString(GetState()));
3358 }
3359
3360 BroadcastEvent(event_sp);
3361
Mehdi Aminic1edf562016-11-11 04:29:25 +00003362 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003363}
3364
3365Error Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3366 Error error;
3367
3368 // Check both the public & private states here. If we're hung evaluating an
3369 // expression, for instance, then
3370 // the public state will be stopped, but we still need to interrupt.
3371 if (m_public_state.GetValue() == eStateRunning ||
3372 m_private_state.GetValue() == eStateRunning) {
3373 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003374 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003375 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003376
Kate Stoneb9c1b512016-09-06 20:57:50 +00003377 ListenerSP listener_sp(
3378 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3379 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003380
Pavel Labath19da1f12015-12-07 12:36:52 +00003381 SendAsyncInterrupt();
3382
Kate Stoneb9c1b512016-09-06 20:57:50 +00003383 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003384 StateType state =
3385 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003386
Pavel Labath19da1f12015-12-07 12:36:52 +00003387 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003388
Kate Stoneb9c1b512016-09-06 20:57:50 +00003389 // If the process exited while we were waiting for it to stop, put the
3390 // exited event into
3391 // the shared pointer passed in and return. Our caller doesn't need to do
3392 // anything else, since
3393 // they don't have a process anymore...
3394
3395 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3396 if (log)
3397 log->Printf("Process::%s() Process exited while waiting to stop.",
3398 __FUNCTION__);
3399 return error;
3400 } else
3401 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3402
3403 if (state != eStateStopped) {
3404 if (log)
3405 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3406 StateAsCString(state));
3407 // If we really couldn't stop the process then we should just error out
3408 // here, but if the
3409 // lower levels just bobbled sending the event and we really are stopped,
3410 // then continue on.
3411 StateType private_state = m_private_state.GetValue();
3412 if (private_state != eStateStopped) {
3413 return Error("Attempt to stop the target in order to detach timed out. "
3414 "State = %s",
3415 StateAsCString(GetState()));
3416 }
3417 }
3418 }
3419 return error;
3420}
3421
3422Error Process::Detach(bool keep_stopped) {
3423 EventSP exit_event_sp;
3424 Error error;
3425 m_destroy_in_process = true;
3426
3427 error = WillDetach();
3428
3429 if (error.Success()) {
3430 if (DetachRequiresHalt()) {
3431 error = StopForDestroyOrDetach(exit_event_sp);
3432 if (!error.Success()) {
3433 m_destroy_in_process = false;
3434 return error;
3435 } else if (exit_event_sp) {
3436 // We shouldn't need to do anything else here. There's no process left
3437 // to detach from...
3438 StopPrivateStateThread();
3439 m_destroy_in_process = false;
3440 return error;
3441 }
3442 }
3443
3444 m_thread_list.DiscardThreadPlans();
3445 DisableAllBreakpointSites();
3446
3447 error = DoDetach(keep_stopped);
3448 if (error.Success()) {
3449 DidDetach();
3450 StopPrivateStateThread();
3451 } else {
3452 return error;
3453 }
3454 }
3455 m_destroy_in_process = false;
3456
3457 // If we exited when we were waiting for a process to stop, then
3458 // forward the event here so we don't lose the event
3459 if (exit_event_sp) {
3460 // Directly broadcast our exited event because we shut down our
3461 // private state thread above
3462 BroadcastEvent(exit_event_sp);
3463 }
3464
3465 // If we have been interrupted (to kill us) in the middle of running, we may
3466 // not end up propagating
3467 // the last events through the event system, in which case we might strand the
3468 // write lock. Unlock
3469 // it here so when we do to tear down the process we don't get an error
3470 // destroying the lock.
3471
3472 m_public_run_lock.SetStopped();
3473 return error;
3474}
3475
3476Error Process::Destroy(bool force_kill) {
3477
3478 // Tell ourselves we are in the process of destroying the process, so that we
3479 // don't do any unnecessary work
3480 // that might hinder the destruction. Remember to set this back to false when
3481 // we are done. That way if the attempt
3482 // failed and the process stays around for some reason it won't be in a
3483 // confused state.
3484
3485 if (force_kill)
3486 m_should_detach = false;
3487
3488 if (GetShouldDetach()) {
3489 // FIXME: This will have to be a process setting:
3490 bool keep_stopped = false;
3491 Detach(keep_stopped);
3492 }
3493
3494 m_destroy_in_process = true;
3495
3496 Error error(WillDestroy());
3497 if (error.Success()) {
3498 EventSP exit_event_sp;
3499 if (DestroyRequiresHalt()) {
3500 error = StopForDestroyOrDetach(exit_event_sp);
3501 }
3502
3503 if (m_public_state.GetValue() != eStateRunning) {
3504 // Ditch all thread plans, and remove all our breakpoints: in case we have
3505 // to restart the target to
3506 // kill it, we don't want it hitting a breakpoint...
3507 // Only do this if we've stopped, however, since if we didn't manage to
3508 // halt it above, then
3509 // we're not going to have much luck doing this now.
3510 m_thread_list.DiscardThreadPlans();
3511 DisableAllBreakpointSites();
3512 }
3513
3514 error = DoDestroy();
3515 if (error.Success()) {
3516 DidDestroy();
3517 StopPrivateStateThread();
3518 }
3519 m_stdio_communication.Disconnect();
3520 m_stdio_communication.StopReadThread();
3521 m_stdin_forward = false;
3522
3523 if (m_process_input_reader) {
3524 m_process_input_reader->SetIsDone(true);
3525 m_process_input_reader->Cancel();
3526 m_process_input_reader.reset();
3527 }
3528
3529 // If we exited when we were waiting for a process to stop, then
3530 // forward the event here so we don't lose the event
3531 if (exit_event_sp) {
3532 // Directly broadcast our exited event because we shut down our
3533 // private state thread above
3534 BroadcastEvent(exit_event_sp);
3535 }
3536
3537 // If we have been interrupted (to kill us) in the middle of running, we may
3538 // not end up propagating
3539 // the last events through the event system, in which case we might strand
3540 // the write lock. Unlock
3541 // it here so when we do to tear down the process we don't get an error
3542 // destroying the lock.
3543 m_public_run_lock.SetStopped();
3544 }
3545
3546 m_destroy_in_process = false;
3547
3548 return error;
3549}
3550
3551Error Process::Signal(int signal) {
3552 Error error(WillSignal());
3553 if (error.Success()) {
3554 error = DoSignal(signal);
3555 if (error.Success())
3556 DidSignal();
3557 }
3558 return error;
3559}
3560
3561void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3562 assert(signals_sp && "null signals_sp");
3563 m_unix_signals_sp = signals_sp;
3564}
3565
3566const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3567 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3568 return m_unix_signals_sp;
3569}
3570
3571lldb::ByteOrder Process::GetByteOrder() const {
3572 return GetTarget().GetArchitecture().GetByteOrder();
3573}
3574
3575uint32_t Process::GetAddressByteSize() const {
3576 return GetTarget().GetArchitecture().GetAddressByteSize();
3577}
3578
3579bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3580 const StateType state =
3581 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3582 bool return_value = true;
3583 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3584 LIBLLDB_LOG_PROCESS));
3585
3586 switch (state) {
3587 case eStateDetached:
3588 case eStateExited:
3589 case eStateUnloaded:
3590 m_stdio_communication.SynchronizeWithReadThread();
3591 m_stdio_communication.Disconnect();
3592 m_stdio_communication.StopReadThread();
3593 m_stdin_forward = false;
3594
3595 LLVM_FALLTHROUGH;
3596 case eStateConnected:
3597 case eStateAttaching:
3598 case eStateLaunching:
3599 // These events indicate changes in the state of the debugging session,
3600 // always report them.
3601 return_value = true;
3602 break;
3603 case eStateInvalid:
3604 // We stopped for no apparent reason, don't report it.
3605 return_value = false;
3606 break;
3607 case eStateRunning:
3608 case eStateStepping:
3609 // If we've started the target running, we handle the cases where we
3610 // are already running and where there is a transition from stopped to
3611 // running differently.
3612 // running -> running: Automatically suppress extra running events
3613 // stopped -> running: Report except when there is one or more no votes
3614 // and no yes votes.
3615 SynchronouslyNotifyStateChanged(state);
3616 if (m_force_next_event_delivery)
3617 return_value = true;
3618 else {
3619 switch (m_last_broadcast_state) {
3620 case eStateRunning:
3621 case eStateStepping:
3622 // We always suppress multiple runnings with no PUBLIC stop in between.
3623 return_value = false;
3624 break;
3625 default:
3626 // TODO: make this work correctly. For now always report
3627 // run if we aren't running so we don't miss any running
3628 // events. If I run the lldb/test/thread/a.out file and
3629 // break at main.cpp:58, run and hit the breakpoints on
3630 // multiple threads, then somehow during the stepping over
3631 // of all breakpoints no run gets reported.
3632
3633 // This is a transition from stop to run.
3634 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3635 case eVoteYes:
3636 case eVoteNoOpinion:
3637 return_value = true;
3638 break;
3639 case eVoteNo:
3640 return_value = false;
3641 break;
3642 }
3643 break;
3644 }
3645 }
3646 break;
3647 case eStateStopped:
3648 case eStateCrashed:
3649 case eStateSuspended:
3650 // We've stopped. First see if we're going to restart the target.
3651 // If we are going to stop, then we always broadcast the event.
3652 // If we aren't going to stop, let the thread plans decide if we're going to
3653 // report this event.
3654 // If no thread has an opinion, we don't report it.
3655
3656 m_stdio_communication.SynchronizeWithReadThread();
3657 RefreshStateAfterStop();
3658 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3659 if (log)
3660 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3661 "interrupt, state: %s",
3662 static_cast<void *>(event_ptr), StateAsCString(state));
3663 // Even though we know we are going to stop, we should let the threads
3664 // have a look at the stop,
3665 // so they can properly set their state.
3666 m_thread_list.ShouldStop(event_ptr);
3667 return_value = true;
3668 } else {
3669 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3670 bool should_resume = false;
3671
3672 // It makes no sense to ask "ShouldStop" if we've already been
3673 // restarted...
3674 // Asking the thread list is also not likely to go well, since we are
3675 // running again.
3676 // So in that case just report the event.
3677
3678 if (!was_restarted)
3679 should_resume = !m_thread_list.ShouldStop(event_ptr);
3680
3681 if (was_restarted || should_resume || m_resume_requested) {
3682 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3683 if (log)
3684 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3685 "%s was_restarted: %i stop_vote: %d.",
3686 should_resume, StateAsCString(state), was_restarted,
3687 stop_vote);
3688
3689 switch (stop_vote) {
3690 case eVoteYes:
3691 return_value = true;
3692 break;
3693 case eVoteNoOpinion:
3694 case eVoteNo:
3695 return_value = false;
3696 break;
3697 }
3698
3699 if (!was_restarted) {
3700 if (log)
3701 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3702 "from state: %s",
3703 static_cast<void *>(event_ptr), StateAsCString(state));
3704 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3705 PrivateResume();
3706 }
3707 } else {
3708 return_value = true;
3709 SynchronouslyNotifyStateChanged(state);
3710 }
3711 }
3712 break;
3713 }
3714
3715 // Forcing the next event delivery is a one shot deal. So reset it here.
3716 m_force_next_event_delivery = false;
3717
3718 // We do some coalescing of events (for instance two consecutive running
3719 // events get coalesced.)
3720 // But we only coalesce against events we actually broadcast. So we use
3721 // m_last_broadcast_state
3722 // to track that. NB - you can't use "m_public_state.GetValue()" for that
3723 // purpose, as was originally done,
3724 // because the PublicState reflects the last event pulled off the queue, and
3725 // there may be several
3726 // events stacked up on the queue unserviced. So the PublicState may not
3727 // reflect the last broadcasted event
3728 // yet. m_last_broadcast_state gets updated here.
3729
3730 if (return_value)
3731 m_last_broadcast_state = state;
3732
3733 if (log)
3734 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3735 "broadcast state: %s - %s",
3736 static_cast<void *>(event_ptr), StateAsCString(state),
3737 StateAsCString(m_last_broadcast_state),
3738 return_value ? "YES" : "NO");
3739 return return_value;
3740}
3741
3742bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3743 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3744
3745 bool already_running = PrivateStateThreadIsValid();
3746 if (log)
3747 log->Printf("Process::%s()%s ", __FUNCTION__,
3748 already_running ? " already running"
3749 : " starting private state thread");
3750
3751 if (!is_secondary_thread && already_running)
3752 return true;
3753
3754 // Create a thread that watches our internal state and controls which
3755 // events make it to clients (into the DCProcess event queue).
3756 char thread_name[1024];
3757
3758 if (HostInfo::GetMaxThreadNameLength() <= 30) {
3759 // On platforms with abbreviated thread name lengths, choose thread names
3760 // that fit within the limit.
3761 if (already_running)
3762 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3763 else
3764 snprintf(thread_name, sizeof(thread_name), "intern-state");
3765 } else {
3766 if (already_running)
3767 snprintf(thread_name, sizeof(thread_name),
3768 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3769 GetID());
3770 else
3771 snprintf(thread_name, sizeof(thread_name),
3772 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3773 }
3774
3775 // Create the private state thread, and start it running.
3776 PrivateStateThreadArgs *args_ptr =
3777 new PrivateStateThreadArgs(this, is_secondary_thread);
3778 m_private_state_thread =
3779 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3780 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3781 if (m_private_state_thread.IsJoinable()) {
3782 ResumePrivateStateThread();
3783 return true;
3784 } else
3785 return false;
3786}
3787
3788void Process::PausePrivateStateThread() {
3789 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3790}
3791
3792void Process::ResumePrivateStateThread() {
3793 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3794}
3795
3796void Process::StopPrivateStateThread() {
3797 if (m_private_state_thread.IsJoinable())
3798 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3799 else {
3800 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3801 if (log)
3802 log->Printf(
3803 "Went to stop the private state thread, but it was already invalid.");
3804 }
3805}
3806
3807void Process::ControlPrivateStateThread(uint32_t signal) {
3808 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3809
3810 assert(signal == eBroadcastInternalStateControlStop ||
3811 signal == eBroadcastInternalStateControlPause ||
3812 signal == eBroadcastInternalStateControlResume);
3813
3814 if (log)
3815 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3816
3817 // Signal the private state thread
3818 if (m_private_state_thread.IsJoinable()) {
3819 // Broadcast the event.
3820 // It is important to do this outside of the if below, because
3821 // it's possible that the thread state is invalid but that the
3822 // thread is waiting on a control event instead of simply being
3823 // on its way out (this should not happen, but it apparently can).
3824 if (log)
3825 log->Printf("Sending control event of type: %d.", signal);
3826 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3827 m_private_state_control_broadcaster.BroadcastEvent(signal,
3828 event_receipt_sp);
3829
3830 // Wait for the event receipt or for the private state thread to exit
3831 bool receipt_received = false;
3832 if (PrivateStateThreadIsValid()) {
3833 while (!receipt_received) {
3834 bool timed_out = false;
3835 // Check for a receipt for 2 seconds and then check if the private state
3836 // thread is still around.
3837 receipt_received = event_receipt_sp->WaitForEventReceived(
3838 std::chrono::seconds(2), &timed_out);
3839 if (!receipt_received) {
3840 // Check if the private state thread is still around. If it isn't then
3841 // we are done waiting
3842 if (!PrivateStateThreadIsValid())
3843 break; // Private state thread exited or is exiting, we are done
3844 }
3845 }
3846 }
3847
3848 if (signal == eBroadcastInternalStateControlStop) {
3849 thread_result_t result = NULL;
3850 m_private_state_thread.Join(&result);
3851 m_private_state_thread.Reset();
3852 }
3853 } else {
3854 if (log)
3855 log->Printf(
3856 "Private state thread already dead, no need to signal it to stop.");
3857 }
3858}
3859
3860void Process::SendAsyncInterrupt() {
3861 if (PrivateStateThreadIsValid())
3862 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3863 nullptr);
3864 else
3865 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3866}
3867
3868void Process::HandlePrivateEvent(EventSP &event_sp) {
3869 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3870 m_resume_requested = false;
3871
3872 const StateType new_state =
3873 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3874
3875 // First check to see if anybody wants a shot at this event:
3876 if (m_next_event_action_ap) {
3877 NextEventAction::EventActionResult action_result =
3878 m_next_event_action_ap->PerformAction(event_sp);
3879 if (log)
3880 log->Printf("Ran next event action, result was %d.", action_result);
3881
3882 switch (action_result) {
3883 case NextEventAction::eEventActionSuccess:
3884 SetNextEventAction(nullptr);
3885 break;
3886
3887 case NextEventAction::eEventActionRetry:
3888 break;
3889
3890 case NextEventAction::eEventActionExit:
3891 // Handle Exiting Here. If we already got an exited event,
3892 // we should just propagate it. Otherwise, swallow this event,
3893 // and set our state to exit so the next event will kill us.
3894 if (new_state != eStateExited) {
3895 // FIXME: should cons up an exited event, and discard this one.
3896 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3897 SetNextEventAction(nullptr);
3898 return;
3899 }
3900 SetNextEventAction(nullptr);
3901 break;
3902 }
3903 }
3904
3905 // See if we should broadcast this state to external clients?
3906 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3907
3908 if (should_broadcast) {
3909 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3910 if (log) {
3911 log->Printf("Process::%s (pid = %" PRIu64
3912 ") broadcasting new state %s (old state %s) to %s",
3913 __FUNCTION__, GetID(), StateAsCString(new_state),
3914 StateAsCString(GetState()),
3915 is_hijacked ? "hijacked" : "public");
3916 }
3917 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3918 if (StateIsRunningState(new_state)) {
3919 // Only push the input handler if we aren't fowarding events,
3920 // as this means the curses GUI is in use...
3921 // Or don't push it if we are launching since it will come up stopped.
3922 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3923 new_state != eStateLaunching && new_state != eStateAttaching) {
3924 PushProcessIOHandler();
3925 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3926 eBroadcastAlways);
3927 if (log)
3928 log->Printf("Process::%s updated m_iohandler_sync to %d",
3929 __FUNCTION__, m_iohandler_sync.GetValue());
3930 }
3931 } else if (StateIsStoppedState(new_state, false)) {
3932 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3933 // If the lldb_private::Debugger is handling the events, we don't
3934 // want to pop the process IOHandler here, we want to do it when
3935 // we receive the stopped event so we can carefully control when
3936 // the process IOHandler is popped because when we stop we want to
3937 // display some text stating how and why we stopped, then maybe some
3938 // process/thread/frame info, and then we want the "(lldb) " prompt
3939 // to show up. If we pop the process IOHandler here, then we will
3940 // cause the command interpreter to become the top IOHandler after
3941 // the process pops off and it will update its prompt right away...
3942 // See the Debugger.cpp file where it calls the function as
3943 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3944 // Otherwise we end up getting overlapping "(lldb) " prompts and
3945 // garbled output.
3946 //
3947 // If we aren't handling the events in the debugger (which is indicated
3948 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3949 // are hijacked, then we always pop the process IO handler manually.
3950 // Hijacking happens when the internal process state thread is running
3951 // thread plans, or when commands want to run in synchronous mode
3952 // and they call "process->WaitForProcessToStop()". An example of
3953 // something
3954 // that will hijack the events is a simple expression:
3955 //
3956 // (lldb) expr (int)puts("hello")
3957 //
3958 // This will cause the internal process state thread to resume and halt
3959 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3960 // events) and we do need the IO handler to be pushed and popped
3961 // correctly.
3962
3963 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3964 PopProcessIOHandler();
3965 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003966 }
3967
3968 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003969 } else {
3970 if (log) {
3971 log->Printf(
3972 "Process::%s (pid = %" PRIu64
3973 ") suppressing state %s (old state %s): should_broadcast == false",
3974 __FUNCTION__, GetID(), StateAsCString(new_state),
3975 StateAsCString(GetState()));
3976 }
3977 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003978}
3979
Kate Stoneb9c1b512016-09-06 20:57:50 +00003980Error Process::HaltPrivate() {
3981 EventSP event_sp;
3982 Error error(WillHalt());
3983 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003984 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003985
3986 // Ask the process subclass to actually halt our process
3987 bool caused_stop;
3988 error = DoHalt(caused_stop);
3989
3990 DidHalt();
3991 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003992}
3993
Kate Stoneb9c1b512016-09-06 20:57:50 +00003994thread_result_t Process::PrivateStateThread(void *arg) {
3995 std::unique_ptr<PrivateStateThreadArgs> args_up(
3996 static_cast<PrivateStateThreadArgs *>(arg));
3997 thread_result_t result =
3998 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3999 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004000}
4001
Kate Stoneb9c1b512016-09-06 20:57:50 +00004002thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
4003 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00004004
Kate Stoneb9c1b512016-09-06 20:57:50 +00004005 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4006 if (log)
4007 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4008 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00004009
Kate Stoneb9c1b512016-09-06 20:57:50 +00004010 bool exit_now = false;
4011 bool interrupt_requested = false;
4012 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00004013 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00004014 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004015 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4016 if (log)
4017 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4018 ") got a control event: %d",
4019 __FUNCTION__, static_cast<void *>(this), GetID(),
4020 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00004021
Kate Stoneb9c1b512016-09-06 20:57:50 +00004022 switch (event_sp->GetType()) {
4023 case eBroadcastInternalStateControlStop:
4024 exit_now = true;
4025 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00004026
Kate Stoneb9c1b512016-09-06 20:57:50 +00004027 case eBroadcastInternalStateControlPause:
4028 control_only = true;
4029 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004030
Kate Stoneb9c1b512016-09-06 20:57:50 +00004031 case eBroadcastInternalStateControlResume:
4032 control_only = false;
4033 break;
4034 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004035
Kate Stoneb9c1b512016-09-06 20:57:50 +00004036 continue;
4037 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4038 if (m_public_state.GetValue() == eStateAttaching) {
4039 if (log)
4040 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4041 ") woke up with an interrupt while attaching - "
4042 "forwarding interrupt.",
4043 __FUNCTION__, static_cast<void *>(this), GetID());
4044 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4045 } else if (StateIsRunningState(m_last_broadcast_state)) {
4046 if (log)
4047 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4048 ") woke up with an interrupt - Halting.",
4049 __FUNCTION__, static_cast<void *>(this), GetID());
4050 Error error = HaltPrivate();
4051 if (error.Fail() && log)
4052 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4053 ") failed to halt the process: %s",
4054 __FUNCTION__, static_cast<void *>(this), GetID(),
4055 error.AsCString());
4056 // Halt should generate a stopped event. Make a note of the fact that we
4057 // were
4058 // doing the interrupt, so we can set the interrupted flag after we
4059 // receive the
4060 // event. We deliberately set this to true even if HaltPrivate failed,
4061 // so that we
4062 // can interrupt on the next natural stop.
4063 interrupt_requested = true;
4064 } else {
4065 // This can happen when someone (e.g. Process::Halt) sees that we are
4066 // running and
4067 // sends an interrupt request, but the process actually stops before we
4068 // receive
4069 // it. In that case, we can just ignore the request. We use
4070 // m_last_broadcast_state, because the Stopped event may not have been
4071 // popped of
4072 // the event queue yet, which is when the public state gets updated.
4073 if (log)
4074 log->Printf(
4075 "Process::%s ignoring interrupt as we have already stopped.",
4076 __FUNCTION__);
4077 }
4078 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004079 }
4080
Kate Stoneb9c1b512016-09-06 20:57:50 +00004081 const StateType internal_state =
4082 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004083
Kate Stoneb9c1b512016-09-06 20:57:50 +00004084 if (internal_state != eStateInvalid) {
4085 if (m_clear_thread_plans_on_stop &&
4086 StateIsStoppedState(internal_state, true)) {
4087 m_clear_thread_plans_on_stop = false;
4088 m_thread_list.DiscardThreadPlans();
4089 }
4090
4091 if (interrupt_requested) {
4092 if (StateIsStoppedState(internal_state, true)) {
4093 // We requested the interrupt, so mark this as such in the stop event
4094 // so
4095 // clients can tell an interrupted process from a natural stop
4096 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4097 interrupt_requested = false;
4098 } else if (log) {
4099 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4100 "state '%s' received.",
4101 __FUNCTION__, StateAsCString(internal_state));
4102 }
4103 }
4104
4105 HandlePrivateEvent(event_sp);
4106 }
4107
4108 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4109 internal_state == eStateDetached) {
4110 if (log)
4111 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4112 ") about to exit with internal state %s...",
4113 __FUNCTION__, static_cast<void *>(this), GetID(),
4114 StateAsCString(internal_state));
4115
4116 break;
4117 }
4118 }
4119
4120 // Verify log is still enabled before attempting to write to it...
4121 if (log)
4122 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4123 __FUNCTION__, static_cast<void *>(this), GetID());
4124
4125 // If we are a secondary thread, then the primary thread we are working for
4126 // will have already
4127 // acquired the public_run_lock, and isn't done with what it was doing yet, so
4128 // don't
4129 // try to change it on the way out.
4130 if (!is_secondary_thread)
4131 m_public_run_lock.SetStopped();
4132 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004133}
4134
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004135//------------------------------------------------------------------
4136// Process Event Data
4137//------------------------------------------------------------------
4138
Kate Stoneb9c1b512016-09-06 20:57:50 +00004139Process::ProcessEventData::ProcessEventData()
4140 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4141 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004142
Kate Stoneb9c1b512016-09-06 20:57:50 +00004143Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4144 StateType state)
4145 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4146 m_update_state(0), m_interrupted(false) {
4147 if (process_sp)
4148 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004149}
4150
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004151Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004152
Kate Stoneb9c1b512016-09-06 20:57:50 +00004153const ConstString &Process::ProcessEventData::GetFlavorString() {
4154 static ConstString g_flavor("Process::ProcessEventData");
4155 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004156}
4157
Kate Stoneb9c1b512016-09-06 20:57:50 +00004158const ConstString &Process::ProcessEventData::GetFlavor() const {
4159 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004160}
4161
Kate Stoneb9c1b512016-09-06 20:57:50 +00004162void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4163 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004164
Kate Stoneb9c1b512016-09-06 20:57:50 +00004165 if (!process_sp)
4166 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004167
Kate Stoneb9c1b512016-09-06 20:57:50 +00004168 // This function gets called twice for each event, once when the event gets
4169 // pulled
4170 // off of the private process event queue, and then any number of times, first
4171 // when it gets pulled off of
4172 // the public event queue, then other times when we're pretending that this is
4173 // where we stopped at the
4174 // end of expression evaluation. m_update_state is used to distinguish these
4175 // three cases; it is 0 when we're just pulling it off for private handling,
4176 // and > 1 for expression evaluation, and we don't want to do the breakpoint
4177 // command handling then.
4178 if (m_update_state != 1)
4179 return;
4180
4181 process_sp->SetPublicState(
4182 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4183
Jason Molendab3a3cd12016-12-08 06:27:29 +00004184 if (m_state == eStateStopped && !m_restarted) {
4185 // Let process subclasses know we are about to do a public stop and
4186 // do anything they might need to in order to speed up register and
4187 // memory accesses.
4188 process_sp->WillPublicStop();
4189 }
4190
Kate Stoneb9c1b512016-09-06 20:57:50 +00004191 // If this is a halt event, even if the halt stopped with some reason other
4192 // than a plain interrupt (e.g. we had
4193 // already stopped for a breakpoint when the halt request came through) don't
4194 // do the StopInfo actions, as they may
4195 // end up restarting the process.
4196 if (m_interrupted)
4197 return;
4198
4199 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4200 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004201 ThreadList &curr_thread_list = process_sp->GetThreadList();
4202 uint32_t num_threads = curr_thread_list.GetSize();
4203 uint32_t idx;
4204
4205 // The actions might change one of the thread's stop_info's opinions about
4206 // whether we should
4207 // stop the process, so we need to query that as we go.
4208
4209 // One other complication here, is that we try to catch any case where the
4210 // target has run (except for expressions)
4211 // and immediately exit, but if we get that wrong (which is possible) then
4212 // the thread list might have changed, and
4213 // that would cause our iteration here to crash. We could make a copy of
4214 // the thread list, but we'd really like
4215 // to also know if it has changed at all, so we make up a vector of the
4216 // thread ID's and check what we get back
4217 // against this list & bag out if anything differs.
4218 std::vector<uint32_t> thread_index_array(num_threads);
4219 for (idx = 0; idx < num_threads; ++idx)
4220 thread_index_array[idx] =
4221 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4222
4223 // Use this to track whether we should continue from here. We will only
4224 // continue the target running if
4225 // no thread says we should stop. Of course if some thread's PerformAction
4226 // actually sets the target running,
4227 // then it doesn't matter what the other threads say...
4228
4229 bool still_should_stop = false;
4230
4231 // Sometimes - for instance if we have a bug in the stub we are talking to,
4232 // we stop but no thread has a
4233 // valid stop reason. In that case we should just stop, because we have no
4234 // way of telling what the right
4235 // thing to do is, and it's better to let the user decide than continue
4236 // behind their backs.
4237
4238 bool does_anybody_have_an_opinion = false;
4239
4240 for (idx = 0; idx < num_threads; ++idx) {
4241 curr_thread_list = process_sp->GetThreadList();
4242 if (curr_thread_list.GetSize() != num_threads) {
4243 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4244 LIBLLDB_LOG_PROCESS));
4245 if (log)
4246 log->Printf(
4247 "Number of threads changed from %u to %u while processing event.",
4248 num_threads, curr_thread_list.GetSize());
4249 break;
4250 }
4251
4252 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4253
4254 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4255 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4256 LIBLLDB_LOG_PROCESS));
4257 if (log)
4258 log->Printf("The thread at position %u changed from %u to %u while "
4259 "processing event.",
4260 idx, thread_index_array[idx], thread_sp->GetIndexID());
4261 break;
4262 }
4263
4264 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4265 if (stop_info_sp && stop_info_sp->IsValid()) {
4266 does_anybody_have_an_opinion = true;
4267 bool this_thread_wants_to_stop;
4268 if (stop_info_sp->GetOverrideShouldStop()) {
4269 this_thread_wants_to_stop =
4270 stop_info_sp->GetOverriddenShouldStopValue();
4271 } else {
4272 stop_info_sp->PerformAction(event_ptr);
4273 // The stop action might restart the target. If it does, then we want
4274 // to mark that in the
4275 // event so that whoever is receiving it will know to wait for the
4276 // running event and reflect
4277 // that state appropriately.
4278 // We also need to stop processing actions, since they aren't
4279 // expecting the target to be running.
4280
4281 // FIXME: we might have run.
4282 if (stop_info_sp->HasTargetRunSinceMe()) {
4283 SetRestarted(true);
4284 break;
4285 }
4286
4287 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004288 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004289
4290 if (!still_should_stop)
4291 still_should_stop = this_thread_wants_to_stop;
4292 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004293 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004294
4295 if (!GetRestarted()) {
4296 if (!still_should_stop && does_anybody_have_an_opinion) {
4297 // We've been asked to continue, so do that here.
4298 SetRestarted(true);
4299 // Use the public resume method here, since this is just
4300 // extending a public resume.
4301 process_sp->PrivateResume();
4302 } else {
4303 // If we didn't restart, run the Stop Hooks here:
4304 // They might also restart the target, so watch for that.
4305 process_sp->GetTarget().RunStopHooks();
4306 if (process_sp->GetPrivateState() == eStateRunning)
4307 SetRestarted(true);
4308 }
4309 }
4310 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004311}
4312
Kate Stoneb9c1b512016-09-06 20:57:50 +00004313void Process::ProcessEventData::Dump(Stream *s) const {
4314 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004315
Kate Stoneb9c1b512016-09-06 20:57:50 +00004316 if (process_sp)
4317 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4318 static_cast<void *>(process_sp.get()), process_sp->GetID());
4319 else
4320 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004321
Kate Stoneb9c1b512016-09-06 20:57:50 +00004322 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004323}
4324
4325const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004326Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4327 if (event_ptr) {
4328 const EventData *event_data = event_ptr->GetData();
4329 if (event_data &&
4330 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4331 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4332 }
4333 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004334}
4335
4336ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004337Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4338 ProcessSP process_sp;
4339 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4340 if (data)
4341 process_sp = data->GetProcessSP();
4342 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004343}
4344
Kate Stoneb9c1b512016-09-06 20:57:50 +00004345StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4346 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4347 if (data == nullptr)
4348 return eStateInvalid;
4349 else
4350 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004351}
4352
Kate Stoneb9c1b512016-09-06 20:57:50 +00004353bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4354 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4355 if (data == nullptr)
4356 return false;
4357 else
4358 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004359}
4360
Kate Stoneb9c1b512016-09-06 20:57:50 +00004361void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4362 bool new_value) {
4363 ProcessEventData *data =
4364 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4365 if (data != nullptr)
4366 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004367}
4368
Jim Ingham0161b492013-02-09 01:29:05 +00004369size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004370Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4371 ProcessEventData *data =
4372 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4373 if (data != nullptr)
4374 return data->GetNumRestartedReasons();
4375 else
4376 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004377}
4378
4379const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004380Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4381 size_t idx) {
4382 ProcessEventData *data =
4383 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4384 if (data != nullptr)
4385 return data->GetRestartedReasonAtIndex(idx);
4386 else
4387 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004388}
4389
Kate Stoneb9c1b512016-09-06 20:57:50 +00004390void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4391 const char *reason) {
4392 ProcessEventData *data =
4393 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4394 if (data != nullptr)
4395 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004396}
4397
Kate Stoneb9c1b512016-09-06 20:57:50 +00004398bool Process::ProcessEventData::GetInterruptedFromEvent(
4399 const Event *event_ptr) {
4400 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4401 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004402 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004403 else
4404 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004405}
4406
Kate Stoneb9c1b512016-09-06 20:57:50 +00004407void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4408 bool new_value) {
4409 ProcessEventData *data =
4410 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4411 if (data != nullptr)
4412 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004413}
4414
Kate Stoneb9c1b512016-09-06 20:57:50 +00004415bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4416 ProcessEventData *data =
4417 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4418 if (data) {
4419 data->SetUpdateStateOnRemoval();
4420 return true;
4421 }
4422 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004423}
4424
Kate Stoneb9c1b512016-09-06 20:57:50 +00004425lldb::TargetSP Process::CalculateTarget() { return m_target_sp.lock(); }
4426
4427void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4428 exe_ctx.SetTargetPtr(&GetTarget());
4429 exe_ctx.SetProcessPtr(this);
4430 exe_ctx.SetThreadPtr(nullptr);
4431 exe_ctx.SetFramePtr(nullptr);
4432}
4433
4434// uint32_t
4435// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4436// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004437//{
4438// return 0;
4439//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004440//
4441// ArchSpec
4442// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004443//{
4444// return Host::GetArchSpecForExistingProcess (pid);
4445//}
4446//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004447// ArchSpec
4448// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004449//{
4450// return Host::GetArchSpecForExistingProcess (process_name);
4451//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004452
Kate Stoneb9c1b512016-09-06 20:57:50 +00004453void Process::AppendSTDOUT(const char *s, size_t len) {
4454 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4455 m_stdout_data.append(s, len);
4456 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4457 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004458}
4459
Kate Stoneb9c1b512016-09-06 20:57:50 +00004460void Process::AppendSTDERR(const char *s, size_t len) {
4461 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4462 m_stderr_data.append(s, len);
4463 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4464 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004465}
4466
Kate Stoneb9c1b512016-09-06 20:57:50 +00004467void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4468 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4469 m_profile_data.push_back(one_profile_data);
4470 BroadcastEventIfUnique(eBroadcastBitProfileData,
4471 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004472}
4473
Kate Stoneb9c1b512016-09-06 20:57:50 +00004474void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4475 const StructuredDataPluginSP &plugin_sp) {
4476 BroadcastEvent(
4477 eBroadcastBitStructuredData,
4478 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004479}
4480
4481StructuredDataPluginSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004482Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4483 auto find_it = m_structured_data_plugin_map.find(type_name);
4484 if (find_it != m_structured_data_plugin_map.end())
4485 return find_it->second;
4486 else
4487 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004488}
4489
Kate Stoneb9c1b512016-09-06 20:57:50 +00004490size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Error &error) {
4491 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4492 if (m_profile_data.empty())
4493 return 0;
4494
4495 std::string &one_profile_data = m_profile_data.front();
4496 size_t bytes_available = one_profile_data.size();
4497 if (bytes_available > 0) {
4498 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4499 if (log)
4500 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4501 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4502 if (bytes_available > buf_size) {
4503 memcpy(buf, one_profile_data.c_str(), buf_size);
4504 one_profile_data.erase(0, buf_size);
4505 bytes_available = buf_size;
4506 } else {
4507 memcpy(buf, one_profile_data.c_str(), bytes_available);
4508 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004509 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004510 }
4511 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004512}
4513
Greg Clayton93e86192011-11-13 04:45:22 +00004514//------------------------------------------------------------------
4515// Process STDIO
4516//------------------------------------------------------------------
4517
Kate Stoneb9c1b512016-09-06 20:57:50 +00004518size_t Process::GetSTDOUT(char *buf, size_t buf_size, Error &error) {
4519 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4520 size_t bytes_available = m_stdout_data.size();
4521 if (bytes_available > 0) {
4522 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4523 if (log)
4524 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4525 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4526 if (bytes_available > buf_size) {
4527 memcpy(buf, m_stdout_data.c_str(), buf_size);
4528 m_stdout_data.erase(0, buf_size);
4529 bytes_available = buf_size;
4530 } else {
4531 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4532 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004533 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004534 }
4535 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004536}
4537
Kate Stoneb9c1b512016-09-06 20:57:50 +00004538size_t Process::GetSTDERR(char *buf, size_t buf_size, Error &error) {
4539 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4540 size_t bytes_available = m_stderr_data.size();
4541 if (bytes_available > 0) {
4542 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4543 if (log)
4544 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4545 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4546 if (bytes_available > buf_size) {
4547 memcpy(buf, m_stderr_data.c_str(), buf_size);
4548 m_stderr_data.erase(0, buf_size);
4549 bytes_available = buf_size;
4550 } else {
4551 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4552 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004553 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004554 }
4555 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004556}
4557
Kate Stoneb9c1b512016-09-06 20:57:50 +00004558void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4559 size_t src_len) {
4560 Process *process = (Process *)baton;
4561 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004562}
4563
Kate Stoneb9c1b512016-09-06 20:57:50 +00004564class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004565public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004566 IOHandlerProcessSTDIO(Process *process, int write_fd)
4567 : IOHandler(process->GetTarget().GetDebugger(),
4568 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004569 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004570 m_pipe.CreateNew(false);
4571 m_read_file.SetDescriptor(GetInputFD(), false);
4572 }
4573
4574 ~IOHandlerProcessSTDIO() override = default;
4575
4576 // Each IOHandler gets to run until it is done. It should read data
4577 // from the "in" and place output into "out" and "err and return
4578 // when done.
4579 void Run() override {
4580 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4581 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4582 SetIsDone(true);
4583 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004584 }
4585
Kate Stoneb9c1b512016-09-06 20:57:50 +00004586 SetIsDone(false);
4587 const int read_fd = m_read_file.GetDescriptor();
4588 TerminalState terminal_state;
4589 terminal_state.Save(read_fd, false);
4590 Terminal terminal(read_fd);
4591 terminal.SetCanonical(false);
4592 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004593// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004594#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004595 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4596 m_is_running = true;
4597 while (!GetIsDone()) {
4598 SelectHelper select_helper;
4599 select_helper.FDSetRead(read_fd);
4600 select_helper.FDSetRead(pipe_read_fd);
4601 Error error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004602
Kate Stoneb9c1b512016-09-06 20:57:50 +00004603 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004604 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004605 } else {
4606 char ch = 0;
4607 size_t n;
4608 if (select_helper.FDIsSetRead(read_fd)) {
4609 n = 1;
4610 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4611 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4612 SetIsDone(true);
4613 } else
4614 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004615 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004616 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4617 size_t bytes_read;
4618 // Consume the interrupt byte
4619 Error error = m_pipe.Read(&ch, 1, bytes_read);
4620 if (error.Success()) {
4621 switch (ch) {
4622 case 'q':
4623 SetIsDone(true);
4624 break;
4625 case 'i':
4626 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004627 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004628 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004629 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004630 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004631 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004632 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004633 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004634 m_is_running = false;
4635#endif
4636 terminal_state.Restore();
4637 }
4638
4639 void Cancel() override {
4640 SetIsDone(true);
4641 // Only write to our pipe to cancel if we are in
4642 // IOHandlerProcessSTDIO::Run().
4643 // We can end up with a python command that is being run from the command
4644 // interpreter:
4645 //
4646 // (lldb) step_process_thousands_of_times
4647 //
4648 // In this case the command interpreter will be in the middle of handling
4649 // the command and if the process pushes and pops the IOHandler thousands
4650 // of times, we can end up writing to m_pipe without ever consuming the
4651 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4652 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4653 if (m_is_running) {
4654 char ch = 'q'; // Send 'q' for quit
4655 size_t bytes_written = 0;
4656 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004657 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004658 }
4659
4660 bool Interrupt() override {
4661 // Do only things that are safe to do in an interrupt context (like in
4662 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4663 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4664 // that was written to the pipe and then call
4665 // m_process->SendAsyncInterrupt()
4666 // from a much safer location in code.
4667 if (m_active) {
4668 char ch = 'i'; // Send 'i' for interrupt
4669 size_t bytes_written = 0;
4670 Error result = m_pipe.Write(&ch, 1, bytes_written);
4671 return result.Success();
4672 } else {
4673 // This IOHandler might be pushed on the stack, but not being run
4674 // currently
4675 // so do the right thing if we aren't actively watching for STDIN by
4676 // sending
4677 // the interrupt to the process. Otherwise the write to the pipe above
4678 // would
4679 // do nothing. This can happen when the command interpreter is running and
4680 // gets a "expression ...". It will be on the IOHandler thread and sending
4681 // the input is complete to the delegate which will cause the expression
4682 // to
4683 // run, which will push the process IO handler, but not run it.
4684
4685 if (StateIsRunningState(m_process->GetState())) {
4686 m_process->SendAsyncInterrupt();
4687 return true;
4688 }
4689 }
4690 return false;
4691 }
4692
4693 void GotEOF() override {}
4694
Greg Clayton44d93782014-01-27 23:43:24 +00004695protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004696 Process *m_process;
4697 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4698 File m_write_file; // Write to this file (usually the master pty for getting
4699 // io to debuggee)
4700 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004701 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004702};
4703
Kate Stoneb9c1b512016-09-06 20:57:50 +00004704void Process::SetSTDIOFileDescriptor(int fd) {
4705 // First set up the Read Thread for reading/handling process I/O
4706
4707 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4708 new ConnectionFileDescriptor(fd, true));
4709
4710 if (conn_ap) {
4711 m_stdio_communication.SetConnection(conn_ap.release());
4712 if (m_stdio_communication.IsConnected()) {
4713 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4714 STDIOReadThreadBytesReceived, this);
4715 m_stdio_communication.StartReadThread();
4716
4717 // Now read thread is set up, set up input reader.
4718
4719 if (!m_process_input_reader)
4720 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004721 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004722 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004723}
4724
Kate Stoneb9c1b512016-09-06 20:57:50 +00004725bool Process::ProcessIOHandlerIsActive() {
4726 IOHandlerSP io_handler_sp(m_process_input_reader);
4727 if (io_handler_sp)
4728 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4729 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004730}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004731bool Process::PushProcessIOHandler() {
4732 IOHandlerSP io_handler_sp(m_process_input_reader);
4733 if (io_handler_sp) {
4734 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4735 if (log)
4736 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004737
Kate Stoneb9c1b512016-09-06 20:57:50 +00004738 io_handler_sp->SetIsDone(false);
4739 GetTarget().GetDebugger().PushIOHandler(io_handler_sp);
4740 return true;
4741 }
4742 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004743}
4744
Kate Stoneb9c1b512016-09-06 20:57:50 +00004745bool Process::PopProcessIOHandler() {
4746 IOHandlerSP io_handler_sp(m_process_input_reader);
4747 if (io_handler_sp)
4748 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4749 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004750}
4751
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004752// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004753void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004754
Kate Stoneb9c1b512016-09-06 20:57:50 +00004755void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004756
Kate Stoneb9c1b512016-09-06 20:57:50 +00004757namespace {
4758// RestorePlanState is used to record the "is private", "is master" and "okay to
4759// discard" fields of
4760// the plan we are running, and reset it on Clean or on destruction.
4761// It will only reset the state once, so you can call Clean and then monkey with
4762// the state and it
4763// won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004764
Kate Stoneb9c1b512016-09-06 20:57:50 +00004765class RestorePlanState {
4766public:
4767 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4768 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4769 if (m_thread_plan_sp) {
4770 m_private = m_thread_plan_sp->GetPrivate();
4771 m_is_master = m_thread_plan_sp->IsMasterPlan();
4772 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4773 }
4774 }
4775
4776 ~RestorePlanState() { Clean(); }
4777
4778 void Clean() {
4779 if (!m_already_reset && m_thread_plan_sp) {
4780 m_already_reset = true;
4781 m_thread_plan_sp->SetPrivate(m_private);
4782 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4783 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4784 }
4785 }
4786
4787private:
4788 lldb::ThreadPlanSP m_thread_plan_sp;
4789 bool m_already_reset;
4790 bool m_private;
4791 bool m_is_master;
4792 bool m_okay_to_discard;
4793};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004794} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004795
Pavel Labath2ce22162016-12-01 10:57:30 +00004796static microseconds
4797GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4798 const milliseconds default_one_thread_timeout(250);
4799
4800 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004801 if (!options.GetTimeout()) {
4802 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4803 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004804 }
4805
4806 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004807 if (options.GetOneThreadTimeout())
4808 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004809
4810 // Otherwise use half the total timeout, bounded by the
4811 // default_one_thread_timeout.
4812 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004813 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004814}
4815
4816static Timeout<std::micro>
4817GetExpressionTimeout(const EvaluateExpressionOptions &options,
4818 bool before_first_timeout) {
4819 // If we are going to run all threads the whole time, or if we are only
4820 // going to run one thread, we can just return the overall timeout.
4821 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004822 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004823
4824 if (before_first_timeout)
4825 return GetOneThreadExpressionTimeout(options);
4826
Pavel Labath43d35412016-12-06 11:24:51 +00004827 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004828 return llvm::None;
4829 else
Pavel Labath43d35412016-12-06 11:24:51 +00004830 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004831}
4832
Jim Ingham1624a2d2014-05-05 02:26:40 +00004833ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004834Process::RunThreadPlan(ExecutionContext &exe_ctx,
4835 lldb::ThreadPlanSP &thread_plan_sp,
4836 const EvaluateExpressionOptions &options,
4837 DiagnosticManager &diagnostic_manager) {
4838 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004839
Kate Stoneb9c1b512016-09-06 20:57:50 +00004840 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4841
4842 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004843 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004844 eDiagnosticSeverityError,
4845 "RunThreadPlan called with empty thread plan.");
4846 return eExpressionSetupError;
4847 }
4848
4849 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004850 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004851 eDiagnosticSeverityError,
4852 "RunThreadPlan called with an invalid thread plan.");
4853 return eExpressionSetupError;
4854 }
4855
4856 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004857 diagnostic_manager.PutString(eDiagnosticSeverityError,
4858 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004859 return eExpressionSetupError;
4860 }
4861
4862 Thread *thread = exe_ctx.GetThreadPtr();
4863 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004864 diagnostic_manager.PutString(eDiagnosticSeverityError,
4865 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004866 return eExpressionSetupError;
4867 }
4868
4869 // We need to change some of the thread plan attributes for the thread plan
4870 // runner. This will restore them
4871 // when we are done:
4872
4873 RestorePlanState thread_plan_restorer(thread_plan_sp);
4874
4875 // We rely on the thread plan we are running returning "PlanCompleted" if when
4876 // it successfully completes.
4877 // For that to be true the plan can't be private - since private plans
4878 // suppress themselves in the
4879 // GetCompletedPlan call.
4880
4881 thread_plan_sp->SetPrivate(false);
4882
4883 // The plans run with RunThreadPlan also need to be terminal master plans or
4884 // when they are done we will end
4885 // up asking the plan above us whether we should stop, which may give the
4886 // wrong answer.
4887
4888 thread_plan_sp->SetIsMasterPlan(true);
4889 thread_plan_sp->SetOkayToDiscard(false);
4890
4891 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004892 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004893 eDiagnosticSeverityError,
4894 "RunThreadPlan called while the private state was not stopped.");
4895 return eExpressionSetupError;
4896 }
4897
4898 // Save the thread & frame from the exe_ctx for restoration after we run
4899 const uint32_t thread_idx_id = thread->GetIndexID();
4900 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4901 if (!selected_frame_sp) {
4902 thread->SetSelectedFrame(nullptr);
4903 selected_frame_sp = thread->GetSelectedFrame();
4904 if (!selected_frame_sp) {
4905 diagnostic_manager.Printf(
4906 eDiagnosticSeverityError,
4907 "RunThreadPlan called without a selected frame on thread %d",
4908 thread_idx_id);
4909 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004910 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004911 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004912
Pavel Labath2ce22162016-12-01 10:57:30 +00004913 // Make sure the timeout values make sense. The one thread timeout needs to be
4914 // smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004915 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4916 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004917 diagnostic_manager.PutString(eDiagnosticSeverityError,
4918 "RunThreadPlan called with one thread "
4919 "timeout greater than total timeout");
4920 return eExpressionSetupError;
4921 }
4922
Kate Stoneb9c1b512016-09-06 20:57:50 +00004923 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004924
Kate Stoneb9c1b512016-09-06 20:57:50 +00004925 // N.B. Running the target may unset the currently selected thread and frame.
4926 // We don't want to do that either,
4927 // so we should arrange to reset them as well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004928
Kate Stoneb9c1b512016-09-06 20:57:50 +00004929 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004930
Kate Stoneb9c1b512016-09-06 20:57:50 +00004931 uint32_t selected_tid;
4932 StackID selected_stack_id;
4933 if (selected_thread_sp) {
4934 selected_tid = selected_thread_sp->GetIndexID();
4935 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4936 } else {
4937 selected_tid = LLDB_INVALID_THREAD_ID;
4938 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004939
Kate Stoneb9c1b512016-09-06 20:57:50 +00004940 HostThread backup_private_state_thread;
4941 lldb::StateType old_state = eStateInvalid;
4942 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004943
Kate Stoneb9c1b512016-09-06 20:57:50 +00004944 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4945 LIBLLDB_LOG_PROCESS));
4946 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4947 // Yikes, we are running on the private state thread! So we can't wait for
4948 // public events on this thread, since
4949 // we are the thread that is generating public events.
4950 // The simplest thing to do is to spin up a temporary thread to handle
4951 // private state thread events while
4952 // we are fielding public events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004953 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004954 log->Printf("Running thread plan on private state thread, spinning up "
4955 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004956
Kate Stoneb9c1b512016-09-06 20:57:50 +00004957 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004958
Kate Stoneb9c1b512016-09-06 20:57:50 +00004959 // One other bit of business: we want to run just this thread plan and
4960 // anything it pushes, and then stop,
4961 // returning control here.
4962 // But in the normal course of things, the plan above us on the stack would
4963 // be given a shot at the stop
4964 // event before deciding to stop, and we don't want that. So we insert a
4965 // "stopper" base plan on the stack
4966 // before the plan we want to run. Since base plans always stop and return
4967 // control to the user, that will
4968 // do just what we want.
4969 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4970 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4971 // Have to make sure our public state is stopped, since otherwise the
4972 // reporting logic below doesn't work correctly.
4973 old_state = m_public_state.GetValue();
4974 m_public_state.SetValueNoLock(eStateStopped);
4975
4976 // Now spin up the private state thread:
4977 StartPrivateStateThread(true);
4978 }
4979
4980 thread->QueueThreadPlan(
4981 thread_plan_sp, false); // This used to pass "true" does that make sense?
4982
4983 if (options.GetDebug()) {
4984 // In this case, we aren't actually going to run, we just want to stop right
4985 // away.
4986 // Flush this thread so we will refetch the stacks and show the correct
4987 // backtrace.
4988 // FIXME: To make this prettier we should invent some stop reason for this,
4989 // but that
4990 // is only cosmetic, and this functionality is only of use to lldb
4991 // developers who can
4992 // live with not pretty...
4993 thread->Flush();
4994 return eExpressionStoppedForDebug;
4995 }
4996
4997 ListenerSP listener_sp(
4998 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4999
5000 lldb::EventSP event_to_broadcast_sp;
5001
5002 {
5003 // This process event hijacker Hijacks the Public events and its destructor
5004 // makes sure that the process events get
5005 // restored on exit to the function.
5006 //
5007 // If the event needs to propagate beyond the hijacker (e.g., the process
5008 // exits during execution), then the event
5009 // is put into event_to_broadcast_sp for rebroadcasting.
5010
5011 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
5012
5013 if (log) {
5014 StreamString s;
5015 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5016 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5017 " to run thread plan \"%s\".",
5018 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00005019 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005020
5021 bool got_event;
5022 lldb::EventSP event_sp;
5023 lldb::StateType stop_state = lldb::eStateInvalid;
5024
5025 bool before_first_timeout = true; // This is set to false the first time
5026 // that we have to halt the target.
5027 bool do_resume = true;
5028 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005029
5030 // This is just for accounting:
5031 uint32_t num_resumes = 0;
5032
Kate Stoneb9c1b512016-09-06 20:57:50 +00005033 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00005034 // going to run one thread, then we don't need the first timeout. So we
5035 // pretend we are after the first timeout already.
5036 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00005037 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005038
Kate Stoneb9c1b512016-09-06 20:57:50 +00005039 if (log)
Pavel Labath2ce22162016-12-01 10:57:30 +00005040 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
5041 options.GetStopOthers(), options.GetTryAllThreads(),
5042 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005043
5044 // This isn't going to work if there are unfetched events on the queue.
5045 // Are there cases where we might want to run the remaining events here, and
5046 // then try to
5047 // call the function? That's probably being too tricky for our own good.
5048
5049 Event *other_events = listener_sp->PeekAtNextEvent();
5050 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00005051 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005052 eDiagnosticSeverityError,
5053 "RunThreadPlan called with pending events on the queue.");
5054 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00005055 }
5056
Kate Stoneb9c1b512016-09-06 20:57:50 +00005057 // We also need to make sure that the next event is delivered. We might be
5058 // calling a function as part of
5059 // a thread plan, in which case the last delivered event could be the
5060 // running event, and we don't want
5061 // event coalescing to cause us to lose OUR running event...
5062 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00005063
Kate Stoneb9c1b512016-09-06 20:57:50 +00005064// This while loop must exit out the bottom, there's cleanup that we need to do
5065// when we are done.
5066// So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00005067
Kate Stoneb9c1b512016-09-06 20:57:50 +00005068#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5069 // It's pretty much impossible to write test cases for things like:
5070 // One thread timeout expires, I go to halt, but the process already stopped
5071 // on the function call stop breakpoint. Turning on this define will make
5072 // us not
5073 // fetch the first event till after the halt. So if you run a quick
5074 // function, it will have
5075 // completed, and the completion event will be waiting, when you interrupt
5076 // for halt.
5077 // The expression evaluation should still succeed.
5078 bool miss_first_event = true;
5079#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00005080 while (true) {
5081 // We usually want to resume the process if we get to the top of the loop.
5082 // The only exception is if we get two running events with no intervening
5083 // stop, which can happen, we will just wait for then next stop event.
5084 if (log)
5085 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5086 "before_first_timeout: %i.",
5087 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00005088
Kate Stoneb9c1b512016-09-06 20:57:50 +00005089 if (do_resume || handle_running_event) {
5090 // Do the initial resume and wait for the running event before going
5091 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00005092
Kate Stoneb9c1b512016-09-06 20:57:50 +00005093 if (do_resume) {
5094 num_resumes++;
5095 Error resume_error = PrivateResume();
5096 if (!resume_error.Success()) {
5097 diagnostic_manager.Printf(
5098 eDiagnosticSeverityError,
5099 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5100 resume_error.AsCString());
5101 return_value = eExpressionSetupError;
5102 break;
5103 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005104 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005105
Pavel Labathd35031e12016-11-30 10:41:42 +00005106 got_event =
5107 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005108 if (!got_event) {
5109 if (log)
5110 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5111 "resume %" PRIu32 ", exiting.",
5112 num_resumes);
5113
5114 diagnostic_manager.Printf(eDiagnosticSeverityError,
5115 "didn't get any event after resume %" PRIu32
5116 ", exiting.",
5117 num_resumes);
5118 return_value = eExpressionSetupError;
5119 break;
5120 }
5121
5122 stop_state =
5123 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5124
5125 if (stop_state != eStateRunning) {
5126 bool restarted = false;
5127
5128 if (stop_state == eStateStopped) {
5129 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5130 event_sp.get());
5131 if (log)
5132 log->Printf(
5133 "Process::RunThreadPlan(): didn't get running event after "
5134 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5135 "handle_running_event: %i).",
5136 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5137 handle_running_event);
5138 }
5139
5140 if (restarted) {
5141 // This is probably an overabundance of caution, I don't think I
5142 // should ever get a stopped & restarted
5143 // event here. But if I do, the best thing is to Halt and then get
5144 // out of here.
5145 const bool clear_thread_plans = false;
5146 const bool use_run_lock = false;
5147 Halt(clear_thread_plans, use_run_lock);
5148 }
5149
5150 diagnostic_manager.Printf(
5151 eDiagnosticSeverityError,
5152 "didn't get running event after initial resume, got %s instead.",
5153 StateAsCString(stop_state));
5154 return_value = eExpressionSetupError;
5155 break;
5156 }
5157
5158 if (log)
5159 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5160 // We need to call the function synchronously, so spin waiting for it to
5161 // return.
5162 // If we get interrupted while executing, we're going to lose our
5163 // context, and
5164 // won't be able to gather the result at this point.
5165 // We set the timeout AFTER the resume, since the resume takes some time
5166 // and we
5167 // don't want to charge that to the timeout.
5168 } else {
5169 if (log)
5170 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5171 }
5172
Kate Stoneb9c1b512016-09-06 20:57:50 +00005173 do_resume = true;
5174 handle_running_event = true;
5175
5176 // Now wait for the process to stop again:
5177 event_sp.reset();
5178
Pavel Labath2ce22162016-12-01 10:57:30 +00005179 Timeout<std::micro> timeout =
5180 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005181 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005182 if (timeout) {
5183 auto now = system_clock::now();
5184 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
5185 "endpoint is %s",
5186 llvm::to_string(now).c_str(),
5187 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005188 } else {
5189 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005190 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005191 }
5192
5193#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5194 // See comment above...
5195 if (miss_first_event) {
5196 usleep(1000);
5197 miss_first_event = false;
5198 got_event = false;
5199 } else
5200#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005201 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005202
5203 if (got_event) {
5204 if (event_sp) {
5205 bool keep_going = false;
5206 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5207 const bool clear_thread_plans = false;
5208 const bool use_run_lock = false;
5209 Halt(clear_thread_plans, use_run_lock);
5210 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005211 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5212 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005213 if (log)
5214 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5215 "eBroadcastBitInterrupted, exiting.");
5216 break;
5217 } else {
5218 stop_state =
5219 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5220 if (log)
5221 log->Printf(
5222 "Process::RunThreadPlan(): in while loop, got event: %s.",
5223 StateAsCString(stop_state));
5224
5225 switch (stop_state) {
5226 case lldb::eStateStopped: {
5227 // We stopped, figure out what we are going to do now.
5228 ThreadSP thread_sp =
5229 GetThreadList().FindThreadByIndexID(thread_idx_id);
5230 if (!thread_sp) {
5231 // Ooh, our thread has vanished. Unlikely that this was
5232 // successful execution...
5233 if (log)
5234 log->Printf("Process::RunThreadPlan(): execution completed "
5235 "but our thread (index-id=%u) has vanished.",
5236 thread_idx_id);
5237 return_value = eExpressionInterrupted;
5238 } else {
5239 // If we were restarted, we just need to go back up to fetch
5240 // another event.
5241 if (Process::ProcessEventData::GetRestartedFromEvent(
5242 event_sp.get())) {
5243 if (log) {
5244 log->Printf("Process::RunThreadPlan(): Got a stop and "
5245 "restart, so we'll continue waiting.");
5246 }
5247 keep_going = true;
5248 do_resume = false;
5249 handle_running_event = true;
5250 } else {
5251 StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
5252 StopReason stop_reason = eStopReasonInvalid;
5253 if (stop_info_sp)
5254 stop_reason = stop_info_sp->GetStopReason();
5255
5256 // FIXME: We only check if the stop reason is plan complete,
5257 // should we make sure that
5258 // it is OUR plan that is complete?
5259 if (stop_reason == eStopReasonPlanComplete) {
5260 if (log)
5261 log->PutCString("Process::RunThreadPlan(): execution "
5262 "completed successfully.");
5263
5264 // Restore the plan state so it will get reported as
5265 // intended when we are done.
5266 thread_plan_restorer.Clean();
5267
5268 return_value = eExpressionCompleted;
5269 } else {
5270 // Something restarted the target, so just wait for it to
5271 // stop for real.
5272 if (stop_reason == eStopReasonBreakpoint) {
5273 if (log)
5274 log->Printf("Process::RunThreadPlan() stopped for "
5275 "breakpoint: %s.",
5276 stop_info_sp->GetDescription());
5277 return_value = eExpressionHitBreakpoint;
5278 if (!options.DoesIgnoreBreakpoints()) {
5279 // Restore the plan state and then force Private to
5280 // false. We are
5281 // going to stop because of this plan so we need it to
5282 // become a public
5283 // plan or it won't report correctly when we continue to
5284 // its termination
5285 // later on.
5286 thread_plan_restorer.Clean();
5287 if (thread_plan_sp)
5288 thread_plan_sp->SetPrivate(false);
5289 event_to_broadcast_sp = event_sp;
5290 }
5291 } else {
5292 if (log)
5293 log->PutCString("Process::RunThreadPlan(): thread plan "
5294 "didn't successfully complete.");
5295 if (!options.DoesUnwindOnError())
5296 event_to_broadcast_sp = event_sp;
5297 return_value = eExpressionInterrupted;
5298 }
5299 }
5300 }
5301 }
5302 } break;
5303
5304 case lldb::eStateRunning:
5305 // This shouldn't really happen, but sometimes we do get two
5306 // running events without an
5307 // intervening stop, and in that case we should just go back to
5308 // waiting for the stop.
5309 do_resume = false;
5310 keep_going = true;
5311 handle_running_event = false;
5312 break;
5313
5314 default:
5315 if (log)
5316 log->Printf("Process::RunThreadPlan(): execution stopped with "
5317 "unexpected state: %s.",
5318 StateAsCString(stop_state));
5319
5320 if (stop_state == eStateExited)
5321 event_to_broadcast_sp = event_sp;
5322
Zachary Turnere2411fa2016-11-12 19:12:56 +00005323 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005324 eDiagnosticSeverityError,
5325 "execution stopped with unexpected state.");
5326 return_value = eExpressionInterrupted;
5327 break;
5328 }
5329 }
5330
5331 if (keep_going)
5332 continue;
5333 else
5334 break;
5335 } else {
5336 if (log)
5337 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5338 "the event pointer was null. How odd...");
5339 return_value = eExpressionInterrupted;
5340 break;
5341 }
5342 } else {
5343 // If we didn't get an event that means we've timed out...
5344 // We will interrupt the process here. Depending on what we were asked
5345 // to do we will
5346 // either exit, or try with all threads running for the same timeout.
5347
5348 if (log) {
5349 if (options.GetTryAllThreads()) {
5350 if (before_first_timeout) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005351 log->Printf("Process::RunThreadPlan(): Running function with "
5352 "one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005353 } else
5354 log->Printf("Process::RunThreadPlan(): Restarting function with "
5355 "all threads enabled "
Pavel Labath2ce22162016-12-01 10:57:30 +00005356 "and timeout: %" PRIu64
5357 " timed out, abandoning execution.",
5358 timeout ? timeout->count() : -1);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005359 } else
5360 log->Printf("Process::RunThreadPlan(): Running function with "
Pavel Labath2ce22162016-12-01 10:57:30 +00005361 "timeout: %" PRIu64 " timed out, "
Kate Stoneb9c1b512016-09-06 20:57:50 +00005362 "abandoning execution.",
Pavel Labath2ce22162016-12-01 10:57:30 +00005363 timeout ? timeout->count() : -1);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005364 }
5365
5366 // It is possible that between the time we issued the Halt, and we get
5367 // around to calling Halt the target
5368 // could have stopped. That's fine, Halt will figure that out and send
5369 // the appropriate Stopped event.
5370 // BUT it is also possible that we stopped & restarted (e.g. hit a
5371 // signal with "stop" set to false.) In
5372 // that case, we'll get the stopped & restarted event, and we should go
5373 // back to waiting for the Halt's
5374 // stopped event. That's what this while loop does.
5375
5376 bool back_to_top = true;
5377 uint32_t try_halt_again = 0;
5378 bool do_halt = true;
5379 const uint32_t num_retries = 5;
5380 while (try_halt_again < num_retries) {
5381 Error halt_error;
5382 if (do_halt) {
5383 if (log)
5384 log->Printf("Process::RunThreadPlan(): Running Halt.");
5385 const bool clear_thread_plans = false;
5386 const bool use_run_lock = false;
5387 Halt(clear_thread_plans, use_run_lock);
5388 }
5389 if (halt_error.Success()) {
5390 if (log)
5391 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5392
Pavel Labathd35031e12016-11-30 10:41:42 +00005393 got_event =
5394 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005395
5396 if (got_event) {
5397 stop_state =
5398 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5399 if (log) {
5400 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5401 StateAsCString(stop_state));
5402 if (stop_state == lldb::eStateStopped &&
5403 Process::ProcessEventData::GetInterruptedFromEvent(
5404 event_sp.get()))
5405 log->PutCString(" Event was the Halt interruption event.");
5406 }
5407
5408 if (stop_state == lldb::eStateStopped) {
5409 // Between the time we initiated the Halt and the time we
5410 // delivered it, the process could have
5411 // already finished its job. Check that here:
5412
5413 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5414 if (log)
5415 log->PutCString("Process::RunThreadPlan(): Even though we "
5416 "timed out, the call plan was done. "
5417 "Exiting wait loop.");
5418 return_value = eExpressionCompleted;
5419 back_to_top = false;
5420 break;
5421 }
5422
5423 if (Process::ProcessEventData::GetRestartedFromEvent(
5424 event_sp.get())) {
5425 if (log)
5426 log->PutCString("Process::RunThreadPlan(): Went to halt "
5427 "but got a restarted event, there must be "
5428 "an un-restarted stopped event so try "
5429 "again... "
5430 "Exiting wait loop.");
5431 try_halt_again++;
5432 do_halt = false;
5433 continue;
5434 }
5435
5436 if (!options.GetTryAllThreads()) {
5437 if (log)
5438 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5439 "was false, we stopped so now we're "
5440 "quitting.");
5441 return_value = eExpressionInterrupted;
5442 back_to_top = false;
5443 break;
5444 }
5445
5446 if (before_first_timeout) {
5447 // Set all the other threads to run, and return to the top of
5448 // the loop, which will continue;
5449 before_first_timeout = false;
5450 thread_plan_sp->SetStopOthers(false);
5451 if (log)
5452 log->PutCString(
5453 "Process::RunThreadPlan(): about to resume.");
5454
5455 back_to_top = true;
5456 break;
5457 } else {
5458 // Running all threads failed, so return Interrupted.
5459 if (log)
5460 log->PutCString("Process::RunThreadPlan(): running all "
5461 "threads timed out.");
5462 return_value = eExpressionInterrupted;
5463 back_to_top = false;
5464 break;
5465 }
5466 }
5467 } else {
5468 if (log)
5469 log->PutCString("Process::RunThreadPlan(): halt said it "
5470 "succeeded, but I got no event. "
5471 "I'm getting out of here passing Interrupted.");
5472 return_value = eExpressionInterrupted;
5473 back_to_top = false;
5474 break;
5475 }
5476 } else {
5477 try_halt_again++;
5478 continue;
5479 }
5480 }
5481
5482 if (!back_to_top || try_halt_again > num_retries)
5483 break;
5484 else
5485 continue;
5486 }
5487 } // END WAIT LOOP
5488
5489 // If we had to start up a temporary private state thread to run this thread
5490 // plan, shut it down now.
5491 if (backup_private_state_thread.IsJoinable()) {
5492 StopPrivateStateThread();
5493 Error error;
5494 m_private_state_thread = backup_private_state_thread;
5495 if (stopper_base_plan_sp) {
5496 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5497 }
5498 if (old_state != eStateInvalid)
5499 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005500 }
5501
Kate Stoneb9c1b512016-09-06 20:57:50 +00005502 if (return_value != eExpressionCompleted && log) {
5503 // Print a backtrace into the log so we can figure out where we are:
5504 StreamString s;
5505 s.PutCString("Thread state after unsuccessful completion: \n");
5506 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005507 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005508 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005509 // Restore the thread state if we are going to discard the plan execution.
5510 // There are three cases where this
5511 // could happen:
5512 // 1) The execution successfully completed
5513 // 2) We hit a breakpoint, and ignore_breakpoints was true
5514 // 3) We got some other error, and discard_on_error was true
5515 bool should_unwind = (return_value == eExpressionInterrupted &&
5516 options.DoesUnwindOnError()) ||
5517 (return_value == eExpressionHitBreakpoint &&
5518 options.DoesIgnoreBreakpoints());
5519
5520 if (return_value == eExpressionCompleted || should_unwind) {
5521 thread_plan_sp->RestoreThreadState();
5522 }
5523
5524 // Now do some processing on the results of the run:
5525 if (return_value == eExpressionInterrupted ||
5526 return_value == eExpressionHitBreakpoint) {
5527 if (log) {
5528 StreamString s;
5529 if (event_sp)
5530 event_sp->Dump(&s);
5531 else {
5532 log->PutCString("Process::RunThreadPlan(): Stop event that "
5533 "interrupted us is NULL.");
5534 }
5535
5536 StreamString ts;
5537
5538 const char *event_explanation = nullptr;
5539
5540 do {
5541 if (!event_sp) {
5542 event_explanation = "<no event>";
5543 break;
5544 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5545 event_explanation = "<user interrupt>";
5546 break;
5547 } else {
5548 const Process::ProcessEventData *event_data =
5549 Process::ProcessEventData::GetEventDataFromEvent(
5550 event_sp.get());
5551
5552 if (!event_data) {
5553 event_explanation = "<no event data>";
5554 break;
5555 }
5556
5557 Process *process = event_data->GetProcessSP().get();
5558
5559 if (!process) {
5560 event_explanation = "<no process>";
5561 break;
5562 }
5563
5564 ThreadList &thread_list = process->GetThreadList();
5565
5566 uint32_t num_threads = thread_list.GetSize();
5567 uint32_t thread_index;
5568
5569 ts.Printf("<%u threads> ", num_threads);
5570
5571 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5572 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5573
5574 if (!thread) {
5575 ts.Printf("<?> ");
5576 continue;
5577 }
5578
5579 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5580 RegisterContext *register_context =
5581 thread->GetRegisterContext().get();
5582
5583 if (register_context)
5584 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5585 else
5586 ts.Printf("[ip unknown] ");
5587
5588 // Show the private stop info here, the public stop info will be
5589 // from the last natural stop.
5590 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5591 if (stop_info_sp) {
5592 const char *stop_desc = stop_info_sp->GetDescription();
5593 if (stop_desc)
5594 ts.PutCString(stop_desc);
5595 }
5596 ts.Printf(">");
5597 }
5598
5599 event_explanation = ts.GetData();
5600 }
5601 } while (0);
5602
5603 if (event_explanation)
5604 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5605 s.GetData(), event_explanation);
5606 else
5607 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5608 s.GetData());
5609 }
5610
5611 if (should_unwind) {
5612 if (log)
5613 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5614 "discarding thread plans up to %p.",
5615 static_cast<void *>(thread_plan_sp.get()));
5616 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5617 } else {
5618 if (log)
5619 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5620 "plan: %p not discarding.",
5621 static_cast<void *>(thread_plan_sp.get()));
5622 }
5623 } else if (return_value == eExpressionSetupError) {
5624 if (log)
5625 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5626
5627 if (options.DoesUnwindOnError()) {
5628 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5629 }
5630 } else {
5631 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5632 if (log)
5633 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5634 return_value = eExpressionCompleted;
5635 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5636 if (log)
5637 log->PutCString(
5638 "Process::RunThreadPlan(): thread plan was discarded");
5639 return_value = eExpressionDiscarded;
5640 } else {
5641 if (log)
5642 log->PutCString(
5643 "Process::RunThreadPlan(): thread plan stopped in mid course");
5644 if (options.DoesUnwindOnError() && thread_plan_sp) {
5645 if (log)
5646 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5647 "'cause unwind_on_error is set.");
5648 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5649 }
5650 }
5651 }
5652
5653 // Thread we ran the function in may have gone away because we ran the
5654 // target
5655 // Check that it's still there, and if it is put it back in the context.
5656 // Also restore the
5657 // frame in the context if it is still present.
5658 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5659 if (thread) {
5660 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5661 }
5662
5663 // Also restore the current process'es selected frame & thread, since this
5664 // function calling may
5665 // be done behind the user's back.
5666
5667 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5668 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5669 selected_stack_id.IsValid()) {
5670 // We were able to restore the selected thread, now restore the frame:
5671 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5672 StackFrameSP old_frame_sp =
5673 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5674 selected_stack_id);
5675 if (old_frame_sp)
5676 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5677 old_frame_sp.get());
5678 }
5679 }
5680 }
5681
5682 // If the process exited during the run of the thread plan, notify everyone.
5683
5684 if (event_to_broadcast_sp) {
5685 if (log)
5686 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5687 BroadcastEvent(event_to_broadcast_sp);
5688 }
5689
5690 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005691}
5692
Kate Stoneb9c1b512016-09-06 20:57:50 +00005693const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5694 const char *result_name;
5695
5696 switch (result) {
5697 case eExpressionCompleted:
5698 result_name = "eExpressionCompleted";
5699 break;
5700 case eExpressionDiscarded:
5701 result_name = "eExpressionDiscarded";
5702 break;
5703 case eExpressionInterrupted:
5704 result_name = "eExpressionInterrupted";
5705 break;
5706 case eExpressionHitBreakpoint:
5707 result_name = "eExpressionHitBreakpoint";
5708 break;
5709 case eExpressionSetupError:
5710 result_name = "eExpressionSetupError";
5711 break;
5712 case eExpressionParseError:
5713 result_name = "eExpressionParseError";
5714 break;
5715 case eExpressionResultUnavailable:
5716 result_name = "eExpressionResultUnavailable";
5717 break;
5718 case eExpressionTimedOut:
5719 result_name = "eExpressionTimedOut";
5720 break;
5721 case eExpressionStoppedForDebug:
5722 result_name = "eExpressionStoppedForDebug";
5723 break;
5724 }
5725 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005726}
5727
Kate Stoneb9c1b512016-09-06 20:57:50 +00005728void Process::GetStatus(Stream &strm) {
5729 const StateType state = GetState();
5730 if (StateIsStoppedState(state, false)) {
5731 if (state == eStateExited) {
5732 int exit_status = GetExitStatus();
5733 const char *exit_description = GetExitDescription();
5734 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5735 GetID(), exit_status, exit_status,
5736 exit_description ? exit_description : "");
5737 } else {
5738 if (state == eStateConnected)
5739 strm.Printf("Connected to remote target.\n");
5740 else
5741 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5742 }
5743 } else {
5744 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5745 }
Pavel Labatha933d512016-04-05 13:07:16 +00005746}
5747
Kate Stoneb9c1b512016-09-06 20:57:50 +00005748size_t Process::GetThreadStatus(Stream &strm,
5749 bool only_threads_with_stop_reason,
5750 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005751 uint32_t num_frames_with_source,
5752 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005753 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005754
Kate Stoneb9c1b512016-09-06 20:57:50 +00005755 // You can't hold the thread list lock while calling Thread::GetStatus. That
5756 // very well might run code (e.g. if we need it
5757 // to get return values or arguments.) For that to work the process has to be
5758 // able to acquire it. So instead copy the thread
5759 // ID's, and look them up one by one:
5760
5761 uint32_t num_threads;
5762 std::vector<lldb::tid_t> thread_id_array;
5763 // Scope for thread list locker;
5764 {
5765 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5766 ThreadList &curr_thread_list = GetThreadList();
5767 num_threads = curr_thread_list.GetSize();
5768 uint32_t idx;
5769 thread_id_array.resize(num_threads);
5770 for (idx = 0; idx < num_threads; ++idx)
5771 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5772 }
5773
5774 for (uint32_t i = 0; i < num_threads; i++) {
5775 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5776 if (thread_sp) {
5777 if (only_threads_with_stop_reason) {
5778 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5779 if (!stop_info_sp || !stop_info_sp->IsValid())
5780 continue;
5781 }
5782 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005783 num_frames_with_source,
5784 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005785 ++num_thread_infos_dumped;
5786 } else {
5787 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5788 if (log)
5789 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5790 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005791 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005792 }
5793 return num_thread_infos_dumped;
5794}
5795
5796void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5797 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5798}
5799
5800bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5801 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5802 region.GetByteSize());
5803}
5804
5805void Process::AddPreResumeAction(PreResumeActionCallback callback,
5806 void *baton) {
5807 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5808}
5809
5810bool Process::RunPreResumeActions() {
5811 bool result = true;
5812 while (!m_pre_resume_actions.empty()) {
5813 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5814 m_pre_resume_actions.pop_back();
5815 bool this_result = action.callback(action.baton);
5816 if (result)
5817 result = this_result;
5818 }
5819 return result;
5820}
5821
5822void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5823
Jim Inghamffd91752016-10-20 22:50:00 +00005824void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5825{
5826 PreResumeCallbackAndBaton element(callback, baton);
5827 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5828 if (found_iter != m_pre_resume_actions.end())
5829 {
5830 m_pre_resume_actions.erase(found_iter);
5831 }
5832}
5833
Kate Stoneb9c1b512016-09-06 20:57:50 +00005834ProcessRunLock &Process::GetRunLock() {
5835 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5836 return m_private_run_lock;
5837 else
5838 return m_public_run_lock;
5839}
5840
5841void Process::Flush() {
5842 m_thread_list.Flush();
5843 m_extended_thread_list.Flush();
5844 m_extended_thread_stop_id = 0;
5845 m_queue_list.Clear();
5846 m_queue_list_stop_id = 0;
5847}
5848
5849void Process::DidExec() {
5850 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5851 if (log)
5852 log->Printf("Process::%s()", __FUNCTION__);
5853
5854 Target &target = GetTarget();
5855 target.CleanupProcess();
5856 target.ClearModules(false);
5857 m_dynamic_checkers_ap.reset();
5858 m_abi_sp.reset();
5859 m_system_runtime_ap.reset();
5860 m_os_ap.reset();
5861 m_dyld_ap.reset();
5862 m_jit_loaders_ap.reset();
5863 m_image_tokens.clear();
5864 m_allocated_memory_cache.Clear();
5865 m_language_runtimes.clear();
5866 m_instrumentation_runtimes.clear();
5867 m_thread_list.DiscardThreadPlans();
5868 m_memory_cache.Clear(true);
5869 m_stop_info_override_callback = nullptr;
5870 DoDidExec();
5871 CompleteAttach();
5872 // Flush the process (threads and all stack frames) after running
5873 // CompleteAttach()
5874 // in case the dynamic loader loaded things in new locations.
5875 Flush();
5876
5877 // After we figure out what was loaded/unloaded in CompleteAttach,
5878 // we need to let the target know so it can do any cleanup it needs to.
5879 target.DidExec();
5880}
5881
5882addr_t Process::ResolveIndirectFunction(const Address *address, Error &error) {
5883 if (address == nullptr) {
5884 error.SetErrorString("Invalid address argument");
5885 return LLDB_INVALID_ADDRESS;
5886 }
5887
5888 addr_t function_addr = LLDB_INVALID_ADDRESS;
5889
5890 addr_t addr = address->GetLoadAddress(&GetTarget());
5891 std::map<addr_t, addr_t>::const_iterator iter =
5892 m_resolved_indirect_addresses.find(addr);
5893 if (iter != m_resolved_indirect_addresses.end()) {
5894 function_addr = (*iter).second;
5895 } else {
5896 if (!InferiorCall(this, address, function_addr)) {
5897 Symbol *symbol = address->CalculateSymbolContextSymbol();
5898 error.SetErrorStringWithFormat(
5899 "Unable to call resolver for indirect function %s",
5900 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5901 function_addr = LLDB_INVALID_ADDRESS;
5902 } else {
5903 m_resolved_indirect_addresses.insert(
5904 std::pair<addr_t, addr_t>(addr, function_addr));
5905 }
5906 }
5907 return function_addr;
5908}
5909
5910void Process::ModulesDidLoad(ModuleList &module_list) {
5911 SystemRuntime *sys_runtime = GetSystemRuntime();
5912 if (sys_runtime) {
5913 sys_runtime->ModulesDidLoad(module_list);
5914 }
5915
5916 GetJITLoaders().ModulesDidLoad(module_list);
5917
5918 // Give runtimes a chance to be created.
5919 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5920 m_instrumentation_runtimes);
5921
5922 // Tell runtimes about new modules.
5923 for (auto pos = m_instrumentation_runtimes.begin();
5924 pos != m_instrumentation_runtimes.end(); ++pos) {
5925 InstrumentationRuntimeSP runtime = pos->second;
5926 runtime->ModulesDidLoad(module_list);
5927 }
5928
5929 // Let any language runtimes we have already created know
5930 // about the modules that loaded.
5931
5932 // Iterate over a copy of this language runtime list in case
5933 // the language runtime ModulesDidLoad somehow causes the language
5934 // riuntime to be unloaded.
5935 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5936 for (const auto &pair : language_runtimes) {
5937 // We must check language_runtime_sp to make sure it is not
5938 // nullptr as we might cache the fact that we didn't have a
5939 // language runtime for a language.
5940 LanguageRuntimeSP language_runtime_sp = pair.second;
5941 if (language_runtime_sp)
5942 language_runtime_sp->ModulesDidLoad(module_list);
5943 }
5944
5945 // If we don't have an operating system plug-in, try to load one since
5946 // loading shared libraries might cause a new one to try and load
5947 if (!m_os_ap)
5948 LoadOperatingSystemPlugin(false);
5949
5950 // Give structured-data plugins a chance to see the modified modules.
5951 for (auto pair : m_structured_data_plugin_map) {
5952 if (pair.second)
5953 pair.second->ModulesDidLoad(*this, module_list);
5954 }
5955}
5956
5957void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5958 const char *fmt, ...) {
5959 bool print_warning = true;
5960
5961 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5962 if (!stream_sp)
5963 return;
5964 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5965 return;
5966 }
5967
5968 if (repeat_key != nullptr) {
5969 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5970 if (it == m_warnings_issued.end()) {
5971 m_warnings_issued[warning_type] = WarningsPointerSet();
5972 m_warnings_issued[warning_type].insert(repeat_key);
5973 } else {
5974 if (it->second.find(repeat_key) != it->second.end()) {
5975 print_warning = false;
5976 } else {
5977 it->second.insert(repeat_key);
5978 }
5979 }
5980 }
5981
5982 if (print_warning) {
5983 va_list args;
5984 va_start(args, fmt);
5985 stream_sp->PrintfVarArg(fmt, args);
5986 va_end(args);
5987 }
5988}
5989
5990void Process::PrintWarningOptimization(const SymbolContext &sc) {
5991 if (GetWarningsOptimization() && sc.module_sp &&
5992 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5993 sc.function->GetIsOptimized()) {
5994 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5995 "%s was compiled with optimization - stepping may behave "
5996 "oddly; variables may not be available.\n",
5997 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5998 }
5999}
6000
6001bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
6002 info.Clear();
6003
6004 PlatformSP platform_sp = GetTarget().GetPlatform();
6005 if (!platform_sp)
6006 return false;
6007
6008 return platform_sp->GetProcessInfo(GetID(), info);
6009}
6010
6011ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
6012 ThreadCollectionSP threads;
6013
6014 const MemoryHistorySP &memory_history =
6015 MemoryHistory::FindPlugin(shared_from_this());
6016
6017 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00006018 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006019 }
6020
6021 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6022
6023 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00006024}
Kuba Brecka63927542014-10-11 01:59:32 +00006025
6026InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00006027Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
6028 InstrumentationRuntimeCollection::iterator pos;
6029 pos = m_instrumentation_runtimes.find(type);
6030 if (pos == m_instrumentation_runtimes.end()) {
6031 return InstrumentationRuntimeSP();
6032 } else
6033 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00006034}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006035
Kate Stoneb9c1b512016-09-06 20:57:50 +00006036bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6037 const ArchSpec &arch, ModuleSpec &module_spec) {
6038 module_spec.Clear();
6039 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006040}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006041
Kate Stoneb9c1b512016-09-06 20:57:50 +00006042size_t Process::AddImageToken(lldb::addr_t image_ptr) {
6043 m_image_tokens.push_back(image_ptr);
6044 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006045}
6046
Kate Stoneb9c1b512016-09-06 20:57:50 +00006047lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
6048 if (token < m_image_tokens.size())
6049 return m_image_tokens[token];
6050 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006051}
6052
Kate Stoneb9c1b512016-09-06 20:57:50 +00006053void Process::ResetImageToken(size_t token) {
6054 if (token < m_image_tokens.size())
6055 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00006056}
Jason Molendafd4cea52016-01-08 21:40:11 +00006057
6058Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00006059Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
6060 AddressRange range_bounds) {
6061 Target &target = GetTarget();
6062 DisassemblerSP disassembler_sp;
6063 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006064
Kate Stoneb9c1b512016-09-06 20:57:50 +00006065 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006066
Kate Stoneb9c1b512016-09-06 20:57:50 +00006067 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00006068 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006069 if (!default_stop_addr.IsValid())
6070 return retval;
6071
6072 ExecutionContext exe_ctx(this);
6073 const char *plugin_name = nullptr;
6074 const char *flavor = nullptr;
6075 const bool prefer_file_cache = true;
6076 disassembler_sp = Disassembler::DisassembleRange(
6077 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6078 prefer_file_cache);
6079 if (disassembler_sp)
6080 insn_list = &disassembler_sp->GetInstructionList();
6081
6082 if (insn_list == nullptr) {
6083 return retval;
6084 }
6085
6086 size_t insn_offset =
6087 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6088 if (insn_offset == UINT32_MAX) {
6089 return retval;
6090 }
6091
6092 uint32_t branch_index =
6093 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6094 if (branch_index == UINT32_MAX) {
6095 return retval;
6096 }
6097
6098 if (branch_index > insn_offset) {
6099 Address next_branch_insn_address =
6100 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6101 if (next_branch_insn_address.IsValid() &&
6102 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6103 retval = next_branch_insn_address;
6104 }
6105 }
6106
6107 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00006108}
Howard Hellyerad007562016-07-07 08:21:28 +00006109
Kate Stoneb9c1b512016-09-06 20:57:50 +00006110Error Process::GetMemoryRegions(
6111 std::vector<lldb::MemoryRegionInfoSP> &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00006112
Kate Stoneb9c1b512016-09-06 20:57:50 +00006113 Error error;
Howard Hellyerad007562016-07-07 08:21:28 +00006114
Kate Stoneb9c1b512016-09-06 20:57:50 +00006115 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00006116
Kate Stoneb9c1b512016-09-06 20:57:50 +00006117 region_list.clear();
6118 do {
6119 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6120 error = GetMemoryRegionInfo(range_end, *region_info);
6121 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6122 if (error.Fail()) {
6123 region_list.clear();
6124 break;
Todd Fiala75930012016-08-19 04:21:48 +00006125 }
6126
Kate Stoneb9c1b512016-09-06 20:57:50 +00006127 range_end = region_info->GetRange().GetRangeEnd();
6128 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6129 region_list.push_back(region_info);
6130 }
6131 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00006132
Kate Stoneb9c1b512016-09-06 20:57:50 +00006133 return error;
6134}
6135
6136Error Process::ConfigureStructuredData(
6137 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
6138 // If you get this, the Process-derived class needs to implement a method
6139 // to enable an already-reported asynchronous structured data feature.
6140 // See ProcessGDBRemote for an example implementation over gdb-remote.
6141 return Error("unimplemented");
6142}
6143
6144void Process::MapSupportedStructuredDataPlugins(
6145 const StructuredData::Array &supported_type_names) {
6146 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6147
6148 // Bail out early if there are no type names to map.
6149 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00006150 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006151 log->Printf("Process::%s(): no structured data types supported",
6152 __FUNCTION__);
6153 return;
6154 }
Todd Fiala75930012016-08-19 04:21:48 +00006155
Kate Stoneb9c1b512016-09-06 20:57:50 +00006156 // Convert StructuredData type names to ConstString instances.
6157 std::set<ConstString> const_type_names;
6158
6159 if (log)
6160 log->Printf("Process::%s(): the process supports the following async "
6161 "structured data types:",
6162 __FUNCTION__);
6163
6164 supported_type_names.ForEach(
6165 [&const_type_names, &log](StructuredData::Object *object) {
6166 if (!object) {
6167 // Invalid - shouldn't be null objects in the array.
6168 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006169 }
6170
6171 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006172 if (!type_name) {
6173 // Invalid format - all type names should be strings.
6174 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006175 }
6176
6177 const_type_names.insert(ConstString(type_name->GetValue()));
6178 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006179 log->Printf("- %s", type_name->GetValue().c_str());
Todd Fiala75930012016-08-19 04:21:48 +00006180 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006181 });
Todd Fiala75930012016-08-19 04:21:48 +00006182
Kate Stoneb9c1b512016-09-06 20:57:50 +00006183 // For each StructuredDataPlugin, if the plugin handles any of the
6184 // types in the supported_type_names, map that type name to that plugin.
6185 uint32_t plugin_index = 0;
6186 for (auto create_instance =
6187 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6188 plugin_index);
6189 create_instance && !const_type_names.empty(); ++plugin_index) {
6190 // Create the plugin.
6191 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6192 if (!plugin_sp) {
6193 // This plugin doesn't think it can work with the process.
6194 // Move on to the next.
6195 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006196 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006197
6198 // For any of the remaining type names, map any that this plugin
6199 // supports.
6200 std::vector<ConstString> names_to_remove;
6201 for (auto &type_name : const_type_names) {
6202 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6203 m_structured_data_plugin_map.insert(
6204 std::make_pair(type_name, plugin_sp));
6205 names_to_remove.push_back(type_name);
6206 if (log)
6207 log->Printf("Process::%s(): using plugin %s for type name "
6208 "%s",
6209 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6210 type_name.GetCString());
6211 }
6212 }
6213
6214 // Remove the type names that were consumed by this plugin.
6215 for (auto &type_name : names_to_remove)
6216 const_type_names.erase(type_name);
6217 }
Todd Fiala75930012016-08-19 04:21:48 +00006218}
6219
Kate Stoneb9c1b512016-09-06 20:57:50 +00006220bool Process::RouteAsyncStructuredData(
6221 const StructuredData::ObjectSP object_sp) {
6222 // Nothing to do if there's no data.
6223 if (!object_sp)
6224 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006225
Kate Stoneb9c1b512016-09-06 20:57:50 +00006226 // The contract is this must be a dictionary, so we can look up the
6227 // routing key via the top-level 'type' string value within the dictionary.
6228 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6229 if (!dictionary)
6230 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006231
Kate Stoneb9c1b512016-09-06 20:57:50 +00006232 // Grab the async structured type name (i.e. the feature/plugin name).
6233 ConstString type_name;
6234 if (!dictionary->GetValueForKeyAsString("type", type_name))
6235 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006236
Kate Stoneb9c1b512016-09-06 20:57:50 +00006237 // Check if there's a plugin registered for this type name.
6238 auto find_it = m_structured_data_plugin_map.find(type_name);
6239 if (find_it == m_structured_data_plugin_map.end()) {
6240 // We don't have a mapping for this structured data type.
6241 return false;
6242 }
Todd Fiala75930012016-08-19 04:21:48 +00006243
Kate Stoneb9c1b512016-09-06 20:57:50 +00006244 // Route the structured data to the plugin.
6245 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6246 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006247}