blob: ffaa19da3539c4cc2b32a606df6b25643fc922ab [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
16// Project includes
Sean Callanan579e70c2016-03-19 00:03:59 +000017#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Breakpoint/BreakpointLocation.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000019#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Debugger.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000021#include "lldb/Core/Event.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000024#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Core/PluginManager.h"
26#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000027#include "lldb/Core/StreamFile.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000028#include "lldb/Expression/DiagnosticManager.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000029#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000030#include "lldb/Expression/UserExpression.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000031#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000032#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000034#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000035#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000036#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000037#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000038#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000039#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000040#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000041#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042#include "lldb/Target/ABI.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000043#include "lldb/Target/CPPLanguageRuntime.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000044#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000045#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000046#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000047#include "lldb/Target/JITLoaderList.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000048#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000049#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000050#include "lldb/Target/MemoryRegionInfo.h"
Jim Ingham22777012010-09-23 02:01:19 +000051#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000052#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000053#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000054#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000056#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000057#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000058#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000059#include "lldb/Target/Target.h"
60#include "lldb/Target/TargetList.h"
61#include "lldb/Target/Thread.h"
62#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000063#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000064#include "lldb/Target/UnixSignals.h"
Zachary Turner50232572015-03-18 21:31:45 +000065#include "lldb/Utility/NameMatches.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000066#include "lldb/Utility/SelectHelper.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067
68using namespace lldb;
69using namespace lldb_private;
70
Kate Stoneb9c1b512016-09-06 20:57:50 +000071// Comment out line below to disable memory caching, overriding the process
72// setting
Greg Clayton67cc0632012-08-22 17:17:09 +000073// target.process.disable-memory-cache
74#define ENABLE_MEMORY_CACHING
75
76#ifdef ENABLE_MEMORY_CACHING
77#define DISABLE_MEM_CACHE_DEFAULT false
78#else
79#define DISABLE_MEM_CACHE_DEFAULT true
80#endif
81
Kate Stoneb9c1b512016-09-06 20:57:50 +000082class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000083public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000084 ProcessOptionValueProperties(const ConstString &name)
85 : OptionValueProperties(name) {}
86
87 // This constructor is used when creating ProcessOptionValueProperties when it
88 // is part of a new lldb_private::Process instance. It will copy all current
89 // global property values as needed
90 ProcessOptionValueProperties(ProcessProperties *global_properties)
91 : OptionValueProperties(*global_properties->GetValueProperties()) {}
92
93 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
94 bool will_modify,
95 uint32_t idx) const override {
96 // When getting the value for a key from the process options, we will always
97 // try and grab the setting from the current process if there is one. Else
98 // we just
99 // use the one from this instance.
100 if (exe_ctx) {
101 Process *process = exe_ctx->GetProcessPtr();
102 if (process) {
103 ProcessOptionValueProperties *instance_properties =
104 static_cast<ProcessOptionValueProperties *>(
105 process->GetValueProperties().get());
106 if (this != instance_properties)
107 return instance_properties->ProtectedGetPropertyAtIndex(idx);
108 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000109 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110 return ProtectedGetPropertyAtIndex(idx);
111 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000112};
113
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114static PropertyDefinition g_properties[] = {
115 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
116 DISABLE_MEM_CACHE_DEFAULT, nullptr, nullptr,
117 "Disable reading and caching of memory in fixed-size units."},
118 {"extra-startup-command", OptionValue::eTypeArray, false,
119 OptionValue::eTypeString, nullptr, nullptr,
120 "A list containing extra commands understood by the particular process "
121 "plugin used. "
122 "For instance, to turn on debugserver logging set this to "
123 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
124 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
125 nullptr, nullptr,
126 "If true, breakpoints will be ignored during expression evaluation."},
127 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
128 nullptr, nullptr, "If true, errors in expression evaluation will unwind "
129 "the stack back to the state before the call."},
130 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
131 nullptr, "A path to a python OS plug-in module file that contains a "
132 "OperatingSystemPlugIn class."},
133 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
134 nullptr, nullptr,
135 "If true, stop when a shared library is loaded or unloaded."},
136 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
137 nullptr, "If true, detach will attempt to keep the process stopped."},
138 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
139 nullptr, "The memory cache line size"},
140 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
141 nullptr, "If true, warn when stopped in code that is optimized where "
142 "stepping and variable availability may not behave as expected."},
143 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000144
145enum {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146 ePropertyDisableMemCache,
147 ePropertyExtraStartCommand,
148 ePropertyIgnoreBreakpointsInExpressions,
149 ePropertyUnwindOnErrorInExpressions,
150 ePropertyPythonOSPluginPath,
151 ePropertyStopOnSharedLibraryEvents,
152 ePropertyDetachKeepsStopped,
153 ePropertyMemCacheLineSize,
154 ePropertyWarningOptimization
Greg Clayton67cc0632012-08-22 17:17:09 +0000155};
156
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157ProcessProperties::ProcessProperties(lldb_private::Process *process)
158 : Properties(),
159 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000160{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161 if (process == nullptr) {
162 // Global process properties, set them up one time
163 m_collection_sp.reset(
164 new ProcessOptionValueProperties(ConstString("process")));
165 m_collection_sp->Initialize(g_properties);
166 m_collection_sp->AppendProperty(
167 ConstString("thread"), ConstString("Settings specific to threads."),
168 true, Thread::GetGlobalProperties()->GetValueProperties());
169 } else {
170 m_collection_sp.reset(
171 new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
172 m_collection_sp->SetValueChangedCallback(
173 ePropertyPythonOSPluginPath,
174 ProcessProperties::OptionValueChangedCallback, this);
175 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000176}
177
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000178ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180void ProcessProperties::OptionValueChangedCallback(void *baton,
181 OptionValue *option_value) {
182 ProcessProperties *properties = (ProcessProperties *)baton;
183 if (properties->m_process)
184 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000185}
186
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187bool ProcessProperties::GetDisableMemoryCache() const {
188 const uint32_t idx = ePropertyDisableMemCache;
189 return m_collection_sp->GetPropertyAtIndexAsBoolean(
190 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000191}
192
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
194 const uint32_t idx = ePropertyMemCacheLineSize;
195 return m_collection_sp->GetPropertyAtIndexAsUInt64(
196 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000197}
198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199Args ProcessProperties::GetExtraStartupCommands() const {
200 Args args;
201 const uint32_t idx = ePropertyExtraStartCommand;
202 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
203 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000204}
205
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206void ProcessProperties::SetExtraStartupCommands(const Args &args) {
207 const uint32_t idx = ePropertyExtraStartCommand;
208 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000209}
210
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211FileSpec ProcessProperties::GetPythonOSPluginPath() const {
212 const uint32_t idx = ePropertyPythonOSPluginPath;
213 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000214}
215
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
217 const uint32_t idx = ePropertyPythonOSPluginPath;
218 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000219}
220
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
222 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
223 return m_collection_sp->GetPropertyAtIndexAsBoolean(
224 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000225}
226
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
228 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
229 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000230}
231
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
233 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
234 return m_collection_sp->GetPropertyAtIndexAsBoolean(
235 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000236}
237
Kate Stoneb9c1b512016-09-06 20:57:50 +0000238void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
239 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
240 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000241}
242
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
244 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
245 return m_collection_sp->GetPropertyAtIndexAsBoolean(
246 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000247}
248
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
250 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
251 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
252}
253
254bool ProcessProperties::GetDetachKeepsStopped() const {
255 const uint32_t idx = ePropertyDetachKeepsStopped;
256 return m_collection_sp->GetPropertyAtIndexAsBoolean(
257 nullptr, idx, g_properties[idx].default_uint_value != 0);
258}
259
260void ProcessProperties::SetDetachKeepsStopped(bool stop) {
261 const uint32_t idx = ePropertyDetachKeepsStopped;
262 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
263}
264
265bool ProcessProperties::GetWarningsOptimization() const {
266 const uint32_t idx = ePropertyWarningOptimization;
267 return m_collection_sp->GetPropertyAtIndexAsBoolean(
268 nullptr, idx, g_properties[idx].default_uint_value != 0);
269}
270
271void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const {
272 const char *cstr;
273 if (m_pid != LLDB_INVALID_PROCESS_ID)
274 s.Printf(" pid = %" PRIu64 "\n", m_pid);
275
276 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
277 s.Printf(" parent = %" PRIu64 "\n", m_parent_pid);
278
279 if (m_executable) {
280 s.Printf(" name = %s\n", m_executable.GetFilename().GetCString());
281 s.PutCString(" file = ");
282 m_executable.Dump(&s);
283 s.EOL();
284 }
285 const uint32_t argc = m_arguments.GetArgumentCount();
286 if (argc > 0) {
287 for (uint32_t i = 0; i < argc; i++) {
288 const char *arg = m_arguments.GetArgumentAtIndex(i);
289 if (i < 10)
290 s.Printf(" arg[%u] = %s\n", i, arg);
291 else
292 s.Printf("arg[%u] = %s\n", i, arg);
293 }
294 }
295
296 const uint32_t envc = m_environment.GetArgumentCount();
297 if (envc > 0) {
298 for (uint32_t i = 0; i < envc; i++) {
299 const char *env = m_environment.GetArgumentAtIndex(i);
300 if (i < 10)
301 s.Printf(" env[%u] = %s\n", i, env);
302 else
303 s.Printf("env[%u] = %s\n", i, env);
304 }
305 }
306
307 if (m_arch.IsValid()) {
308 s.Printf(" arch = ");
309 m_arch.DumpTriple(s);
310 s.EOL();
311 }
312
313 if (m_uid != UINT32_MAX) {
314 cstr = platform->GetUserName(m_uid);
315 s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
316 }
317 if (m_gid != UINT32_MAX) {
318 cstr = platform->GetGroupName(m_gid);
319 s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
320 }
321 if (m_euid != UINT32_MAX) {
322 cstr = platform->GetUserName(m_euid);
323 s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
324 }
325 if (m_egid != UINT32_MAX) {
326 cstr = platform->GetGroupName(m_egid);
327 s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
328 }
329}
330
331void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform,
332 bool show_args, bool verbose) {
333 const char *label;
334 if (show_args || verbose)
335 label = "ARGUMENTS";
336 else
337 label = "NAME";
338
339 if (verbose) {
340 s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE "
341 " %s\n",
342 label);
343 s.PutCString("====== ====== ========== ========== ========== ========== "
344 "======================== ============================\n");
345 } else {
346 s.Printf("PID PARENT USER TRIPLE %s\n", label);
347 s.PutCString("====== ====== ========== ======================== "
348 "============================\n");
349 }
350}
351
352void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform,
353 bool show_args, bool verbose) const {
354 if (m_pid != LLDB_INVALID_PROCESS_ID) {
Greg Clayton32e0a752011-03-30 18:16:51 +0000355 const char *cstr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000357
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 StreamString arch_strm;
Todd Fiala7df337f2015-10-13 23:41:19 +0000359 if (m_arch.IsValid())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 m_arch.DumpTriple(arch_strm);
361
362 if (verbose) {
363 cstr = platform->GetUserName(m_uid);
364 if (cstr &&
365 cstr[0]) // Watch for empty string that indicates lookup failed
366 s.Printf("%-10s ", cstr);
367 else
368 s.Printf("%-10u ", m_uid);
369
370 cstr = platform->GetGroupName(m_gid);
371 if (cstr &&
372 cstr[0]) // Watch for empty string that indicates lookup failed
373 s.Printf("%-10s ", cstr);
374 else
375 s.Printf("%-10u ", m_gid);
376
377 cstr = platform->GetUserName(m_euid);
378 if (cstr &&
379 cstr[0]) // Watch for empty string that indicates lookup failed
380 s.Printf("%-10s ", cstr);
381 else
382 s.Printf("%-10u ", m_euid);
383
384 cstr = platform->GetGroupName(m_egid);
385 if (cstr &&
386 cstr[0]) // Watch for empty string that indicates lookup failed
387 s.Printf("%-10s ", cstr);
388 else
389 s.Printf("%-10u ", m_egid);
390
391 s.Printf("%-24s ", arch_strm.GetString().c_str());
392 } else {
393 s.Printf("%-10s %-24s ", platform->GetUserName(m_euid),
394 arch_strm.GetString().c_str());
Todd Fiala7df337f2015-10-13 23:41:19 +0000395 }
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 if (verbose || show_args) {
398 const uint32_t argc = m_arguments.GetArgumentCount();
399 if (argc > 0) {
400 for (uint32_t i = 0; i < argc; i++) {
401 if (i > 0)
402 s.PutChar(' ');
403 s.PutCString(m_arguments.GetArgumentAtIndex(i));
404 }
405 }
406 } else {
407 s.PutCString(GetName());
Greg Clayton32e0a752011-03-30 18:16:51 +0000408 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409
410 s.EOL();
411 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000412}
413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414Error ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000415 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416 ExecutionContext *execution_context) {
417 Error error;
418 const int short_option = m_getopt_table[option_idx].val;
419
420 switch (short_option) {
421 case 's': // Stop at program entry point
422 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
423 break;
424
425 case 'i': // STDIN for read only
426 {
427 FileAction action;
428 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
429 launch_info.AppendFileAction(action);
430 break;
431 }
432
433 case 'o': // Open STDOUT for write only
434 {
435 FileAction action;
436 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
437 launch_info.AppendFileAction(action);
438 break;
439 }
440
441 case 'e': // STDERR for write only
442 {
443 FileAction action;
444 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
445 launch_info.AppendFileAction(action);
446 break;
447 }
448
449 case 'p': // Process plug-in name
450 launch_info.SetProcessPluginName(option_arg);
451 break;
452
453 case 'n': // Disable STDIO
454 {
455 FileAction action;
456 const FileSpec dev_null{FileSystem::DEV_NULL, false};
457 if (action.Open(STDIN_FILENO, dev_null, true, false))
458 launch_info.AppendFileAction(action);
459 if (action.Open(STDOUT_FILENO, dev_null, false, true))
460 launch_info.AppendFileAction(action);
461 if (action.Open(STDERR_FILENO, dev_null, false, true))
462 launch_info.AppendFileAction(action);
463 break;
464 }
465
466 case 'w':
467 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
468 break;
469
470 case 't': // Open process in new terminal window
471 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
472 break;
473
474 case 'a': {
475 TargetSP target_sp =
476 execution_context ? execution_context->GetTargetSP() : TargetSP();
477 PlatformSP platform_sp =
478 target_sp ? target_sp->GetPlatform() : PlatformSP();
479 if (!launch_info.GetArchitecture().SetTriple(option_arg, platform_sp.get()))
480 launch_info.GetArchitecture().SetTriple(option_arg);
481 } break;
482
483 case 'A': // Disable ASLR.
484 {
485 bool success;
486 const bool disable_aslr_arg =
Zachary Turnerfe114832016-11-12 16:56:47 +0000487 Args::StringToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 if (success)
489 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000490 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 error.SetErrorStringWithFormat(
492 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000493 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 break;
495 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000496
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 case 'X': // shell expand args.
498 {
499 bool success;
Zachary Turnerfe114832016-11-12 16:56:47 +0000500 const bool expand_args = Args::StringToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000501 if (success)
502 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000503 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 error.SetErrorStringWithFormat(
505 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000506 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 break;
508 }
509
510 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000511 if (!option_arg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512 launch_info.SetShell(FileSpec(option_arg, false));
513 else
514 launch_info.SetShell(HostInfo::GetDefaultShell());
515 break;
516
517 case 'v':
Zachary Turnerfe114832016-11-12 16:56:47 +0000518 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 break;
520
521 default:
522 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
523 short_option);
524 break;
525 }
526 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000527}
528
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000529static OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
531 nullptr, nullptr, 0, eArgTypeNone,
532 "Stop at the entry point of the program when launching a process."},
533 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
534 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
535 "Set whether to disable address space layout randomization when launching "
536 "a process."},
537 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
538 nullptr, nullptr, 0, eArgTypePlugin,
539 "Name of the process plugin you want to use."},
540 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
541 OptionParser::eRequiredArgument, nullptr, nullptr, 0,
542 eArgTypeDirectoryName,
543 "Set the current working directory to <path> when running the inferior."},
544 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
545 nullptr, nullptr, 0, eArgTypeArchitecture,
546 "Set the architecture for the process to launch when ambiguous."},
547 {LLDB_OPT_SET_ALL, false, "environment", 'v',
548 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone,
549 "Specify an environment variable name/value string (--environment "
550 "NAME=VALUE). Can be specified multiple times for subsequent environment "
551 "entries."},
552 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
553 OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeFilename,
554 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
557 nullptr, nullptr, 0, eArgTypeFilename,
558 "Redirect stdin for the process to <filename>."},
559 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
560 nullptr, nullptr, 0, eArgTypeFilename,
561 "Redirect stdout for the process to <filename>."},
562 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
563 nullptr, nullptr, 0, eArgTypeFilename,
564 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000565
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
567 nullptr, 0, eArgTypeNone,
568 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000569
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
571 nullptr, 0, eArgTypeNone,
572 "Do not set up for terminal I/O to go to running process."},
573 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
574 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
575 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000576};
577
578llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000579 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000580}
Greg Clayton32e0a752011-03-30 18:16:51 +0000581
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
583 if (m_name_match_type == eNameMatchIgnore || process_name == nullptr)
Greg Clayton32e0a752011-03-30 18:16:51 +0000584 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585 const char *match_name = m_match_info.GetName();
586 if (!match_name)
Greg Clayton32e0a752011-03-30 18:16:51 +0000587 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588
589 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
Greg Clayton32e0a752011-03-30 18:16:51 +0000590}
591
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592bool ProcessInstanceInfoMatch::Matches(
593 const ProcessInstanceInfo &proc_info) const {
594 if (!NameMatches(proc_info.GetName()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000595 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596
597 if (m_match_info.ProcessIDIsValid() &&
598 m_match_info.GetProcessID() != proc_info.GetProcessID())
599 return false;
600
601 if (m_match_info.ParentProcessIDIsValid() &&
602 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
603 return false;
604
605 if (m_match_info.UserIDIsValid() &&
606 m_match_info.GetUserID() != proc_info.GetUserID())
607 return false;
608
609 if (m_match_info.GroupIDIsValid() &&
610 m_match_info.GetGroupID() != proc_info.GetGroupID())
611 return false;
612
613 if (m_match_info.EffectiveUserIDIsValid() &&
614 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
615 return false;
616
617 if (m_match_info.EffectiveGroupIDIsValid() &&
618 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
619 return false;
620
621 if (m_match_info.GetArchitecture().IsValid() &&
622 !m_match_info.GetArchitecture().IsCompatibleMatch(
623 proc_info.GetArchitecture()))
624 return false;
625 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000626}
627
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
629 if (m_name_match_type != eNameMatchIgnore)
630 return false;
631
632 if (m_match_info.ProcessIDIsValid())
633 return false;
634
635 if (m_match_info.ParentProcessIDIsValid())
636 return false;
637
638 if (m_match_info.UserIDIsValid())
639 return false;
640
641 if (m_match_info.GroupIDIsValid())
642 return false;
643
644 if (m_match_info.EffectiveUserIDIsValid())
645 return false;
646
647 if (m_match_info.EffectiveGroupIDIsValid())
648 return false;
649
650 if (m_match_info.GetArchitecture().IsValid())
651 return false;
652
653 if (m_match_all_users)
654 return false;
655
656 return true;
657}
658
659void ProcessInstanceInfoMatch::Clear() {
660 m_match_info.Clear();
661 m_name_match_type = eNameMatchIgnore;
662 m_match_all_users = false;
663}
664
665ProcessSP Process::FindPlugin(lldb::TargetSP target_sp, const char *plugin_name,
666 ListenerSP listener_sp,
667 const FileSpec *crash_file_path) {
668 static uint32_t g_process_unique_id = 0;
669
670 ProcessSP process_sp;
671 ProcessCreateInstance create_callback = nullptr;
672 if (plugin_name) {
673 ConstString const_plugin_name(plugin_name);
674 create_callback =
675 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
676 if (create_callback) {
677 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
678 if (process_sp) {
679 if (process_sp->CanDebug(target_sp, true)) {
680 process_sp->m_process_unique_id = ++g_process_unique_id;
681 } else
682 process_sp.reset();
683 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000684 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000685 } else {
686 for (uint32_t idx = 0;
687 (create_callback =
688 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
689 ++idx) {
690 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
691 if (process_sp) {
692 if (process_sp->CanDebug(target_sp, false)) {
693 process_sp->m_process_unique_id = ++g_process_unique_id;
694 break;
695 } else
696 process_sp.reset();
697 }
698 }
699 }
700 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000701}
702
Kate Stoneb9c1b512016-09-06 20:57:50 +0000703ConstString &Process::GetStaticBroadcasterClass() {
704 static ConstString class_name("lldb.process");
705 return class_name;
706}
707
708Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
709 : Process(target_sp, listener_sp,
710 UnixSignals::Create(HostInfo::GetArchitecture())) {
711 // This constructor just delegates to the full Process constructor,
712 // defaulting to using the Host's UnixSignals.
713}
714
715Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
716 const UnixSignalsSP &unix_signals_sp)
717 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
718 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
719 Process::GetStaticBroadcasterClass().AsCString()),
720 m_target_sp(target_sp), m_public_state(eStateUnloaded),
721 m_private_state(eStateUnloaded),
722 m_private_state_broadcaster(nullptr,
723 "lldb.process.internal_state_broadcaster"),
724 m_private_state_control_broadcaster(
725 nullptr, "lldb.process.internal_state_control_broadcaster"),
726 m_private_state_listener_sp(
727 Listener::MakeListener("lldb.process.internal_state_listener")),
728 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
729 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
730 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
731 m_thread_list(this), m_extended_thread_list(this),
732 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
733 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
734 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
735 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
736 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
737 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
738 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
739 m_memory_cache(*this), m_allocated_memory_cache(*this),
740 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
741 m_private_run_lock(), m_stop_info_override_callback(nullptr),
742 m_finalizing(false), m_finalize_called(false),
743 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
744 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
745 m_can_interpret_function_calls(false), m_warnings_issued(),
746 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
747 CheckInWithManager();
748
749 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
750 if (log)
751 log->Printf("%p Process::Process()", static_cast<void *>(this));
752
753 if (!m_unix_signals_sp)
754 m_unix_signals_sp = std::make_shared<UnixSignals>();
755
756 SetEventName(eBroadcastBitStateChanged, "state-changed");
757 SetEventName(eBroadcastBitInterrupt, "interrupt");
758 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
759 SetEventName(eBroadcastBitSTDERR, "stderr-available");
760 SetEventName(eBroadcastBitProfileData, "profile-data-available");
761 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
762
763 m_private_state_control_broadcaster.SetEventName(
764 eBroadcastInternalStateControlStop, "control-stop");
765 m_private_state_control_broadcaster.SetEventName(
766 eBroadcastInternalStateControlPause, "control-pause");
767 m_private_state_control_broadcaster.SetEventName(
768 eBroadcastInternalStateControlResume, "control-resume");
769
770 m_listener_sp->StartListeningForEvents(
771 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
772 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
773 eBroadcastBitProfileData | eBroadcastBitStructuredData);
774
775 m_private_state_listener_sp->StartListeningForEvents(
776 &m_private_state_broadcaster,
777 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
778
779 m_private_state_listener_sp->StartListeningForEvents(
780 &m_private_state_control_broadcaster,
781 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
782 eBroadcastInternalStateControlResume);
783 // We need something valid here, even if just the default UnixSignalsSP.
784 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
785
786 // Allow the platform to override the default cache line size
787 OptionValueSP value_sp =
788 m_collection_sp
789 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
790 ->GetValue();
791 uint32_t platform_cache_line_size =
792 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
793 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
794 value_sp->SetUInt64Value(platform_cache_line_size);
795}
796
797Process::~Process() {
798 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
799 if (log)
800 log->Printf("%p Process::~Process()", static_cast<void *>(this));
801 StopPrivateStateThread();
802
803 // ThreadList::Clear() will try to acquire this process's mutex, so
804 // explicitly clear the thread list here to ensure that the mutex
805 // is not destroyed before the thread list.
806 m_thread_list.Clear();
807}
808
809const ProcessPropertiesSP &Process::GetGlobalProperties() {
810 // NOTE: intentional leak so we don't crash if global destructor chain gets
811 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000812 static ProcessPropertiesSP *g_settings_sp_ptr =
813 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 return *g_settings_sp_ptr;
815}
816
817void Process::Finalize() {
818 m_finalizing = true;
819
820 // Destroy this process if needed
821 switch (GetPrivateState()) {
822 case eStateConnected:
823 case eStateAttaching:
824 case eStateLaunching:
825 case eStateStopped:
826 case eStateRunning:
827 case eStateStepping:
828 case eStateCrashed:
829 case eStateSuspended:
830 Destroy(false);
831 break;
832
833 case eStateInvalid:
834 case eStateUnloaded:
835 case eStateDetached:
836 case eStateExited:
837 break;
838 }
839
840 // Clear our broadcaster before we proceed with destroying
841 Broadcaster::Clear();
842
843 // Do any cleanup needed prior to being destructed... Subclasses
844 // that override this method should call this superclass method as well.
845
846 // We need to destroy the loader before the derived Process class gets
847 // destroyed
848 // since it is very likely that undoing the loader will require access to the
849 // real process.
850 m_dynamic_checkers_ap.reset();
851 m_abi_sp.reset();
852 m_os_ap.reset();
853 m_system_runtime_ap.reset();
854 m_dyld_ap.reset();
855 m_jit_loaders_ap.reset();
856 m_thread_list_real.Destroy();
857 m_thread_list.Destroy();
858 m_extended_thread_list.Destroy();
859 m_queue_list.Clear();
860 m_queue_list_stop_id = 0;
861 std::vector<Notifications> empty_notifications;
862 m_notifications.swap(empty_notifications);
863 m_image_tokens.clear();
864 m_memory_cache.Clear();
865 m_allocated_memory_cache.Clear();
866 m_language_runtimes.clear();
867 m_instrumentation_runtimes.clear();
868 m_next_event_action_ap.reset();
869 m_stop_info_override_callback = nullptr;
870 // Clear the last natural stop ID since it has a strong
871 // reference to this process
872 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
873 //#ifdef LLDB_CONFIGURATION_DEBUG
874 // StreamFile s(stdout, false);
875 // EventSP event_sp;
876 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
877 // {
878 // event_sp->Dump (&s);
879 // s.EOL();
880 // }
881 //#endif
882 // We have to be very careful here as the m_private_state_listener might
883 // contain events that have ProcessSP values in them which can keep this
884 // process around forever. These events need to be cleared out.
885 m_private_state_listener_sp->Clear();
886 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
887 m_public_run_lock.SetStopped();
888 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
889 m_private_run_lock.SetStopped();
890 m_finalize_called = true;
891}
892
893void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
894 m_notifications.push_back(callbacks);
895 if (callbacks.initialize != nullptr)
896 callbacks.initialize(callbacks.baton, this);
897}
898
899bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
900 std::vector<Notifications>::iterator pos, end = m_notifications.end();
901 for (pos = m_notifications.begin(); pos != end; ++pos) {
902 if (pos->baton == callbacks.baton &&
903 pos->initialize == callbacks.initialize &&
904 pos->process_state_changed == callbacks.process_state_changed) {
905 m_notifications.erase(pos);
906 return true;
907 }
908 }
909 return false;
910}
911
912void Process::SynchronouslyNotifyStateChanged(StateType state) {
913 std::vector<Notifications>::iterator notification_pos,
914 notification_end = m_notifications.end();
915 for (notification_pos = m_notifications.begin();
916 notification_pos != notification_end; ++notification_pos) {
917 if (notification_pos->process_state_changed)
918 notification_pos->process_state_changed(notification_pos->baton, this,
919 state);
920 }
921}
922
923// FIXME: We need to do some work on events before the general Listener sees
924// them.
925// For instance if we are continuing from a breakpoint, we need to ensure that
926// we do
927// the little "insert real insn, step & stop" trick. But we can't do that when
928// the
929// event is delivered by the broadcaster - since that is done on the thread that
930// is
931// waiting for new events, so if we needed more than one event for our handling,
932// we would
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000933// stall. So instead we do it when we fetch the event off of the queue.
934//
935
Kate Stoneb9c1b512016-09-06 20:57:50 +0000936StateType Process::GetNextEvent(EventSP &event_sp) {
937 StateType state = eStateInvalid;
938
939 if (m_listener_sp->GetNextEventForBroadcaster(this, event_sp) && event_sp)
940 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
941
942 return state;
943}
944
945void Process::SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec) {
946 // don't sync (potentially context switch) in case where there is no process
947 // IO
948 if (!m_process_input_reader)
949 return;
950
951 uint32_t new_iohandler_id = 0;
952 m_iohandler_sync.WaitForValueNotEqualTo(
953 iohandler_id, new_iohandler_id, std::chrono::milliseconds(timeout_msec));
954
955 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
956 if (log)
957 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, "
958 "new value is %u",
959 __FUNCTION__, iohandler_id, new_iohandler_id);
960}
961
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000962StateType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963Process::WaitForProcessToStop(const std::chrono::microseconds &timeout,
964 EventSP *event_sp_ptr, bool wait_always,
965 ListenerSP hijack_listener_sp, Stream *stream,
966 bool use_run_lock) {
967 // We can't just wait for a "stopped" event, because the stopped event may
968 // have restarted the target.
969 // We have to actually check each event, and in the case of a stopped event
970 // check the restarted flag
971 // on the event.
972 if (event_sp_ptr)
973 event_sp_ptr->reset();
974 StateType state = GetState();
975 // If we are exited or detached, we won't ever get back to any
976 // other valid state...
977 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000978 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
981 if (log)
982 log->Printf("Process::%s (timeout = %llu)", __FUNCTION__,
983 static_cast<unsigned long long>(timeout.count()));
Todd Fialaa3b89e22014-08-12 14:33:19 +0000984
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 if (!wait_always && StateIsStoppedState(state, true) &&
986 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000987 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 log->Printf("Process::%s returning without waiting for events; process "
989 "private and public states are already 'stopped'.",
990 __FUNCTION__);
991 // We need to toggle the run lock as this won't get done in
992 // SetPublicState() if the process is hijacked.
993 if (hijack_listener_sp && use_run_lock)
994 m_public_run_lock.SetStopped();
995 return state;
996 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 while (state != eStateInvalid) {
999 EventSP event_sp;
1000 state = WaitForStateChangedEvents(timeout, event_sp, hijack_listener_sp);
1001 if (event_sp_ptr && event_sp)
1002 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001003
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1005 Process::HandleProcessStateChangedEvent(event_sp, stream,
1006 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +00001007
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 switch (state) {
1009 case eStateCrashed:
1010 case eStateDetached:
1011 case eStateExited:
1012 case eStateUnloaded:
1013 // We need to toggle the run lock as this won't get done in
1014 // SetPublicState() if the process is hijacked.
1015 if (hijack_listener_sp && use_run_lock)
1016 m_public_run_lock.SetStopped();
1017 return state;
1018 case eStateStopped:
1019 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1020 continue;
1021 else {
Pavel Labath78521ef2015-03-06 10:52:47 +00001022 // We need to toggle the run lock as this won't get done in
1023 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001024 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025 m_public_run_lock.SetStopped();
1026 return state;
1027 }
1028 default:
1029 continue;
1030 }
1031 }
1032 return state;
1033}
1034
1035bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1036 Stream *stream,
1037 bool &pop_process_io_handler) {
1038 const bool handle_pop = pop_process_io_handler;
1039
1040 pop_process_io_handler = false;
1041 ProcessSP process_sp =
1042 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1043
1044 if (!process_sp)
1045 return false;
1046
1047 StateType event_state =
1048 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1049 if (event_state == eStateInvalid)
1050 return false;
1051
1052 switch (event_state) {
1053 case eStateInvalid:
1054 case eStateUnloaded:
1055 case eStateAttaching:
1056 case eStateLaunching:
1057 case eStateStepping:
1058 case eStateDetached:
1059 if (stream)
1060 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1061 StateAsCString(event_state));
1062 if (event_state == eStateDetached)
1063 pop_process_io_handler = true;
1064 break;
1065
1066 case eStateConnected:
1067 case eStateRunning:
1068 // Don't be chatty when we run...
1069 break;
1070
1071 case eStateExited:
1072 if (stream)
1073 process_sp->GetStatus(*stream);
1074 pop_process_io_handler = true;
1075 break;
1076
1077 case eStateStopped:
1078 case eStateCrashed:
1079 case eStateSuspended:
1080 // Make sure the program hasn't been auto-restarted:
1081 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1082 if (stream) {
1083 size_t num_reasons =
1084 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1085 if (num_reasons > 0) {
1086 // FIXME: Do we want to report this, or would that just be annoyingly
1087 // chatty?
1088 if (num_reasons == 1) {
1089 const char *reason =
1090 Process::ProcessEventData::GetRestartedReasonAtIndex(
1091 event_sp.get(), 0);
1092 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1093 process_sp->GetID(),
1094 reason ? reason : "<UNKNOWN REASON>");
1095 } else {
1096 stream->Printf("Process %" PRIu64
1097 " stopped and restarted, reasons:\n",
1098 process_sp->GetID());
1099
1100 for (size_t i = 0; i < num_reasons; i++) {
1101 const char *reason =
1102 Process::ProcessEventData::GetRestartedReasonAtIndex(
1103 event_sp.get(), i);
1104 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1105 }
1106 }
1107 }
1108 }
1109 } else {
1110 StopInfoSP curr_thread_stop_info_sp;
1111 // Lock the thread list so it doesn't change on us, this is the scope for
1112 // the locker:
1113 {
1114 ThreadList &thread_list = process_sp->GetThreadList();
1115 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1116
1117 ThreadSP curr_thread(thread_list.GetSelectedThread());
1118 ThreadSP thread;
1119 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1120 if (curr_thread) {
1121 curr_thread_stop_reason = curr_thread->GetStopReason();
1122 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1123 }
1124 if (!curr_thread || !curr_thread->IsValid() ||
1125 curr_thread_stop_reason == eStopReasonInvalid ||
1126 curr_thread_stop_reason == eStopReasonNone) {
1127 // Prefer a thread that has just completed its plan over another
1128 // thread as current thread.
1129 ThreadSP plan_thread;
1130 ThreadSP other_thread;
1131
1132 const size_t num_threads = thread_list.GetSize();
1133 size_t i;
1134 for (i = 0; i < num_threads; ++i) {
1135 thread = thread_list.GetThreadAtIndex(i);
1136 StopReason thread_stop_reason = thread->GetStopReason();
1137 switch (thread_stop_reason) {
1138 case eStopReasonInvalid:
1139 case eStopReasonNone:
1140 break;
1141
1142 case eStopReasonSignal: {
1143 // Don't select a signal thread if we weren't going to stop at
1144 // that
1145 // signal. We have to have had another reason for stopping here,
1146 // and
1147 // the user doesn't want to see this thread.
1148 uint64_t signo = thread->GetStopInfo()->GetValue();
1149 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1150 if (!other_thread)
1151 other_thread = thread;
1152 }
1153 break;
1154 }
1155 case eStopReasonTrace:
1156 case eStopReasonBreakpoint:
1157 case eStopReasonWatchpoint:
1158 case eStopReasonException:
1159 case eStopReasonExec:
1160 case eStopReasonThreadExiting:
1161 case eStopReasonInstrumentation:
1162 if (!other_thread)
1163 other_thread = thread;
1164 break;
1165 case eStopReasonPlanComplete:
1166 if (!plan_thread)
1167 plan_thread = thread;
1168 break;
1169 }
1170 }
1171 if (plan_thread)
1172 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1173 else if (other_thread)
1174 thread_list.SetSelectedThreadByID(other_thread->GetID());
1175 else {
1176 if (curr_thread && curr_thread->IsValid())
1177 thread = curr_thread;
1178 else
1179 thread = thread_list.GetThreadAtIndex(0);
1180
1181 if (thread)
1182 thread_list.SetSelectedThreadByID(thread->GetID());
1183 }
1184 }
1185 }
1186 // Drop the ThreadList mutex by here, since GetThreadStatus below might
1187 // have to run code,
1188 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the
1189 // process is going to
1190 // have a hard time restarting the process.
1191 if (stream) {
1192 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1193 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1194 &process_sp->GetTarget()) {
1195 const bool only_threads_with_stop_reason = true;
1196 const uint32_t start_frame = 0;
1197 const uint32_t num_frames = 1;
1198 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001199 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 process_sp->GetStatus(*stream);
1201 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1202 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001203 num_frames_with_source,
1204 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 if (curr_thread_stop_info_sp) {
1206 lldb::addr_t crashing_address;
1207 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1208 curr_thread_stop_info_sp, &crashing_address);
1209 if (valobj_sp) {
1210 const bool qualify_cxx_base_classes = false;
1211
1212 const ValueObject::GetExpressionPathFormat format =
1213 ValueObject::GetExpressionPathFormat::
1214 eGetExpressionPathFormatHonorPointers;
1215 stream->PutCString("Likely cause: ");
1216 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1217 format);
1218 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1219 }
1220 }
1221 } else {
1222 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1223 process_sp->GetTarget().shared_from_this());
1224 if (target_idx != UINT32_MAX)
1225 stream->Printf("Target %d: (", target_idx);
1226 else
1227 stream->Printf("Target <unknown index>: (");
1228 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1229 stream->Printf(") stopped.\n");
1230 }
1231 }
1232
1233 // Pop the process IO handler
1234 pop_process_io_handler = true;
1235 }
1236 break;
1237 }
1238
1239 if (handle_pop && pop_process_io_handler)
1240 process_sp->PopProcessIOHandler();
1241
1242 return true;
1243}
1244
1245StateType Process::WaitForState(const std::chrono::microseconds &timeout,
1246 const StateType *match_states,
1247 const uint32_t num_match_states) {
1248 EventSP event_sp;
1249 StateType state = GetState();
1250 while (state != eStateInvalid) {
1251 // If we are exited or detached, we won't ever get back to any
1252 // other valid state...
1253 if (state == eStateDetached || state == eStateExited)
1254 return state;
1255
1256 state = WaitForStateChangedEvents(timeout, event_sp, nullptr);
1257
1258 for (uint32_t i = 0; i < num_match_states; ++i) {
1259 if (match_states[i] == state)
Daniel Malea9e9919f2013-10-09 16:56:28 +00001260 return state;
1261 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 }
1263 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001264}
1265
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1267 if (listener_sp) {
1268 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1269 eBroadcastBitInterrupt);
1270 } else
1271 return false;
1272}
Greg Claytondc6224e2014-10-21 01:00:42 +00001273
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001275
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276StateType
1277Process::WaitForStateChangedEvents(const std::chrono::microseconds &timeout,
1278 EventSP &event_sp,
1279 ListenerSP hijack_listener_sp) {
1280 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001281
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 if (log)
1283 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1284 static_cast<unsigned long long>(timeout.count()));
Greg Claytondc6224e2014-10-21 01:00:42 +00001285
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286 ListenerSP listener_sp = hijack_listener_sp;
1287 if (!listener_sp)
1288 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001289
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 StateType state = eStateInvalid;
1291 if (listener_sp->WaitForEventForBroadcasterWithType(
1292 timeout, this, eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1293 event_sp)) {
1294 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1295 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1296 else if (log)
1297 log->Printf("Process::%s got no event or was interrupted.", __FUNCTION__);
1298 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001299
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 if (log)
1301 log->Printf("Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1302 static_cast<unsigned long long>(timeout.count()),
1303 StateAsCString(state));
1304 return state;
1305}
Greg Claytondc6224e2014-10-21 01:00:42 +00001306
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307Event *Process::PeekAtStateChangedEvents() {
1308 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001309
Kate Stoneb9c1b512016-09-06 20:57:50 +00001310 if (log)
1311 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001312
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313 Event *event_ptr;
1314 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1315 this, eBroadcastBitStateChanged);
1316 if (log) {
1317 if (event_ptr) {
1318 log->Printf(
1319 "Process::%s (event_ptr) => %s", __FUNCTION__,
1320 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1321 } else {
1322 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001323 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324 }
1325 return event_ptr;
1326}
Greg Claytondc6224e2014-10-21 01:00:42 +00001327
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328StateType Process::WaitForStateChangedEventsPrivate(
1329 const std::chrono::microseconds &timeout, EventSP &event_sp) {
1330 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001331
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332 if (log)
1333 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1334 static_cast<unsigned long long>(timeout.count()));
1335
1336 StateType state = eStateInvalid;
1337 if (m_private_state_listener_sp->WaitForEventForBroadcasterWithType(
1338 timeout, &m_private_state_broadcaster,
1339 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp))
1340 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1341 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1342
1343 // This is a bit of a hack, but when we wait here we could very well return
1344 // to the command-line, and that could disable the log, which would render the
1345 // log we got above invalid.
1346 if (log)
1347 log->Printf("Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1348 static_cast<unsigned long long>(timeout.count()),
1349 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1350 return state;
1351}
1352
1353bool Process::WaitForEventsPrivate(const std::chrono::microseconds &timeout,
1354 EventSP &event_sp, bool control_only) {
1355 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1356
1357 if (log)
1358 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1359 static_cast<unsigned long long>(timeout.count()));
1360
1361 if (control_only)
1362 return m_private_state_listener_sp->WaitForEventForBroadcaster(
1363 timeout, &m_private_state_control_broadcaster, event_sp);
1364 else
1365 return m_private_state_listener_sp->WaitForEvent(timeout, event_sp);
1366}
1367
1368bool Process::IsRunning() const {
1369 return StateIsRunningState(m_public_state.GetValue());
1370}
1371
1372int Process::GetExitStatus() {
1373 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1374
1375 if (m_public_state.GetValue() == eStateExited)
1376 return m_exit_status;
1377 return -1;
1378}
1379
1380const char *Process::GetExitDescription() {
1381 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1382
1383 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1384 return m_exit_string.c_str();
1385 return nullptr;
1386}
1387
1388bool Process::SetExitStatus(int status, const char *cstr) {
1389 // Use a mutex to protect setting the exit status.
1390 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1391
1392 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1393 LIBLLDB_LOG_PROCESS));
1394 if (log)
1395 log->Printf(
1396 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1397 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1398 cstr ? "\"" : "");
1399
1400 // We were already in the exited state
1401 if (m_private_state.GetValue() == eStateExited) {
1402 if (log)
1403 log->Printf("Process::SetExitStatus () ignoring exit status because "
1404 "state was already set to eStateExited");
1405 return false;
1406 }
1407
1408 m_exit_status = status;
1409 if (cstr)
1410 m_exit_string = cstr;
1411 else
1412 m_exit_string.clear();
1413
1414 // Clear the last natural stop ID since it has a strong
1415 // reference to this process
1416 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1417
1418 SetPrivateState(eStateExited);
1419
1420 // Allow subclasses to do some cleanup
1421 DidExit();
1422
1423 return true;
1424}
1425
1426bool Process::IsAlive() {
1427 switch (m_private_state.GetValue()) {
1428 case eStateConnected:
1429 case eStateAttaching:
1430 case eStateLaunching:
1431 case eStateStopped:
1432 case eStateRunning:
1433 case eStateStepping:
1434 case eStateCrashed:
1435 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001436 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 default:
1438 return false;
1439 }
Jason Molendaa814f702015-11-05 23:03:44 +00001440}
1441
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001442// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001443// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001444// found in the global target list (we want to be completely sure that the
1445// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446bool Process::SetProcessExitStatus(
1447 lldb::pid_t pid, bool exited,
1448 int signo, // Zero for no signal
1449 int exit_status // Exit value of process if signal is zero
1450 ) {
1451 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1452 if (log)
1453 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1454 ", exited=%i, signal=%i, exit_status=%i)\n",
1455 pid, exited, signo, exit_status);
1456
1457 if (exited) {
1458 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1459 if (target_sp) {
1460 ProcessSP process_sp(target_sp->GetProcessSP());
1461 if (process_sp) {
1462 const char *signal_cstr = nullptr;
1463 if (signo)
1464 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1465
1466 process_sp->SetExitStatus(exit_status, signal_cstr);
1467 }
1468 }
1469 return true;
1470 }
1471 return false;
1472}
1473
1474void Process::UpdateThreadListIfNeeded() {
1475 const uint32_t stop_id = GetStopID();
1476 if (m_thread_list.GetSize(false) == 0 ||
1477 stop_id != m_thread_list.GetStopID()) {
1478 const StateType state = GetPrivateState();
1479 if (StateIsStoppedState(state, true)) {
1480 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1481 // m_thread_list does have its own mutex, but we need to
1482 // hold onto the mutex between the call to UpdateThreadList(...)
1483 // and the os->UpdateThreadList(...) so it doesn't change on us
1484 ThreadList &old_thread_list = m_thread_list;
1485 ThreadList real_thread_list(this);
1486 ThreadList new_thread_list(this);
1487 // Always update the thread list with the protocol specific
1488 // thread list, but only update if "true" is returned
1489 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1490 // Don't call into the OperatingSystem to update the thread list if we
1491 // are shutting down, since
1492 // that may call back into the SBAPI's, requiring the API lock which is
1493 // already held by whoever is
1494 // shutting us down, causing a deadlock.
1495 OperatingSystem *os = GetOperatingSystem();
1496 if (os && !m_destroy_in_process) {
1497 // Clear any old backing threads where memory threads might have been
1498 // backed by actual threads from the lldb_private::Process subclass
1499 size_t num_old_threads = old_thread_list.GetSize(false);
1500 for (size_t i = 0; i < num_old_threads; ++i)
1501 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1502
1503 // Turn off dynamic types to ensure we don't run any expressions.
1504 // Objective C
1505 // can run an expression to determine if a SBValue is a dynamic type
1506 // or not
1507 // and we need to avoid this. OperatingSystem plug-ins can't run
1508 // expressions
1509 // that require running code...
1510
1511 Target &target = GetTarget();
1512 const lldb::DynamicValueType saved_prefer_dynamic =
1513 target.GetPreferDynamicValue();
1514 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1515 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1516
1517 // Now let the OperatingSystem plug-in update the thread list
1518
1519 os->UpdateThreadList(
1520 old_thread_list, // Old list full of threads created by OS plug-in
1521 real_thread_list, // The actual thread list full of threads
1522 // created by each lldb_private::Process
1523 // subclass
1524 new_thread_list); // The new thread list that we will show to the
1525 // user that gets filled in
1526
1527 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1528 target.SetPreferDynamicValue(saved_prefer_dynamic);
1529 } else {
1530 // No OS plug-in, the new thread list is the same as the real thread
1531 // list
1532 new_thread_list = real_thread_list;
1533 }
1534
1535 m_thread_list_real.Update(real_thread_list);
1536 m_thread_list.Update(new_thread_list);
1537 m_thread_list.SetStopID(stop_id);
1538
1539 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1540 // Clear any extended threads that we may have accumulated previously
1541 m_extended_thread_list.Clear();
1542 m_extended_thread_stop_id = GetLastNaturalStopID();
1543
1544 m_queue_list.Clear();
1545 m_queue_list_stop_id = GetLastNaturalStopID();
1546 }
1547 }
1548 }
1549 }
1550}
1551
1552void Process::UpdateQueueListIfNeeded() {
1553 if (m_system_runtime_ap) {
1554 if (m_queue_list.GetSize() == 0 ||
1555 m_queue_list_stop_id != GetLastNaturalStopID()) {
1556 const StateType state = GetPrivateState();
1557 if (StateIsStoppedState(state, true)) {
1558 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1559 m_queue_list_stop_id = GetLastNaturalStopID();
1560 }
1561 }
1562 }
1563}
1564
1565ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1566 OperatingSystem *os = GetOperatingSystem();
1567 if (os)
1568 return os->CreateThread(tid, context);
1569 return ThreadSP();
1570}
1571
1572uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1573 return AssignIndexIDToThread(thread_id);
1574}
1575
1576bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1577 return (m_thread_id_to_index_id_map.find(thread_id) !=
1578 m_thread_id_to_index_id_map.end());
1579}
1580
1581uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1582 uint32_t result = 0;
1583 std::map<uint64_t, uint32_t>::iterator iterator =
1584 m_thread_id_to_index_id_map.find(thread_id);
1585 if (iterator == m_thread_id_to_index_id_map.end()) {
1586 result = ++m_thread_index_id;
1587 m_thread_id_to_index_id_map[thread_id] = result;
1588 } else {
1589 result = iterator->second;
1590 }
1591
1592 return result;
1593}
1594
1595StateType Process::GetState() {
1596 // If any other threads access this we will need a mutex for it
1597 return m_public_state.GetValue();
1598}
1599
1600bool Process::StateChangedIsExternallyHijacked() {
1601 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1602 const char *hijacking_name = GetHijackingListenerName();
1603 if (hijacking_name &&
1604 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1605 return true;
1606 }
1607 return false;
1608}
1609
1610void Process::SetPublicState(StateType new_state, bool restarted) {
1611 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1612 LIBLLDB_LOG_PROCESS));
1613 if (log)
1614 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1615 StateAsCString(new_state), restarted);
1616 const StateType old_state = m_public_state.GetValue();
1617 m_public_state.SetValue(new_state);
1618
1619 // On the transition from Run to Stopped, we unlock the writer end of the
1620 // run lock. The lock gets locked in Resume, which is the public API
1621 // to tell the program to run.
1622 if (!StateChangedIsExternallyHijacked()) {
1623 if (new_state == eStateDetached) {
1624 if (log)
1625 log->Printf(
1626 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1627 StateAsCString(new_state));
1628 m_public_run_lock.SetStopped();
1629 } else {
1630 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1631 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1632 if ((old_state_is_stopped != new_state_is_stopped)) {
1633 if (new_state_is_stopped && !restarted) {
1634 if (log)
1635 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1636 StateAsCString(new_state));
1637 m_public_run_lock.SetStopped();
1638 }
1639 }
1640 }
1641 }
1642}
1643
1644Error Process::Resume() {
1645 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1646 LIBLLDB_LOG_PROCESS));
1647 if (log)
1648 log->Printf("Process::Resume -- locking run lock");
1649 if (!m_public_run_lock.TrySetRunning()) {
1650 Error error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001651 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001652 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001653 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001654 }
1655 return PrivateResume();
Greg Claytondc6224e2014-10-21 01:00:42 +00001656}
1657
Kate Stoneb9c1b512016-09-06 20:57:50 +00001658Error Process::ResumeSynchronous(Stream *stream) {
1659 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1660 LIBLLDB_LOG_PROCESS));
1661 if (log)
1662 log->Printf("Process::ResumeSynchronous -- locking run lock");
1663 if (!m_public_run_lock.TrySetRunning()) {
1664 Error error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001665 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001666 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1667 return error;
1668 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001669
Kate Stoneb9c1b512016-09-06 20:57:50 +00001670 ListenerSP listener_sp(
1671 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1672 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001673
Kate Stoneb9c1b512016-09-06 20:57:50 +00001674 Error error = PrivateResume();
1675 if (error.Success()) {
1676 StateType state = WaitForProcessToStop(std::chrono::microseconds(0), NULL,
1677 true, listener_sp, stream);
1678 const bool must_be_alive =
1679 false; // eStateExited is ok, so this must be false
1680 if (!StateIsStoppedState(state, must_be_alive))
1681 error.SetErrorStringWithFormat(
1682 "process not in stopped state after synchronous resume: %s",
1683 StateAsCString(state));
1684 }
Ed Mastec29693f2013-07-02 16:35:47 +00001685
Kate Stoneb9c1b512016-09-06 20:57:50 +00001686 // Undo the hijacking of process events...
1687 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001688
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 return error;
1690}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001691
Kate Stoneb9c1b512016-09-06 20:57:50 +00001692StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001693
Kate Stoneb9c1b512016-09-06 20:57:50 +00001694void Process::SetPrivateState(StateType new_state) {
1695 if (m_finalize_called)
1696 return;
1697
1698 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1699 LIBLLDB_LOG_PROCESS));
1700 bool state_changed = false;
1701
1702 if (log)
1703 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1704
1705 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1706 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1707
1708 const StateType old_state = m_private_state.GetValueNoLock();
1709 state_changed = old_state != new_state;
1710
1711 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1712 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1713 if (old_state_is_stopped != new_state_is_stopped) {
1714 if (new_state_is_stopped)
1715 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001716 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717 m_private_run_lock.SetRunning();
1718 }
1719
1720 if (state_changed) {
1721 m_private_state.SetValueNoLock(new_state);
1722 EventSP event_sp(
1723 new Event(eBroadcastBitStateChanged,
1724 new ProcessEventData(shared_from_this(), new_state)));
1725 if (StateIsStoppedState(new_state, false)) {
1726 // Note, this currently assumes that all threads in the list
1727 // stop when the process stops. In the future we will want to
1728 // support a debugging model where some threads continue to run
1729 // while others are stopped. When that happens we will either need
1730 // a way for the thread list to identify which threads are stopping
1731 // or create a special thread list containing only threads which
1732 // actually stopped.
1733 //
1734 // The process plugin is responsible for managing the actual
1735 // behavior of the threads and should have stopped any threads
1736 // that are going to stop before we get here.
1737 m_thread_list.DidStop();
1738
1739 m_mod_id.BumpStopID();
1740 if (!m_mod_id.IsLastResumeForUserExpression())
1741 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1742 m_memory_cache.Clear();
1743 if (log)
1744 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1745 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001746 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001747
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748 // Use our target to get a shared pointer to ourselves...
1749 if (m_finalize_called && !PrivateStateThreadIsValid())
1750 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001751 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752 m_private_state_broadcaster.BroadcastEvent(event_sp);
1753 } else {
1754 if (log)
1755 log->Printf(
1756 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1757 StateAsCString(new_state));
1758 }
Jim Ingham22777012010-09-23 02:01:19 +00001759}
1760
Kate Stoneb9c1b512016-09-06 20:57:50 +00001761void Process::SetRunningUserExpression(bool on) {
1762 m_mod_id.SetRunningUserExpression(on);
1763}
1764
1765addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1766
1767const lldb::ABISP &Process::GetABI() {
1768 if (!m_abi_sp)
1769 m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture());
1770 return m_abi_sp;
1771}
1772
1773LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1774 bool retry_if_null) {
1775 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001776 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001777
1778 LanguageRuntimeCollection::iterator pos;
1779 pos = m_language_runtimes.find(language);
1780 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1781 lldb::LanguageRuntimeSP runtime_sp(
1782 LanguageRuntime::FindPlugin(this, language));
1783
1784 m_language_runtimes[language] = runtime_sp;
1785 return runtime_sp.get();
1786 } else
1787 return (*pos).second.get();
Jim Ingham22777012010-09-23 02:01:19 +00001788}
1789
Kate Stoneb9c1b512016-09-06 20:57:50 +00001790CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1791 LanguageRuntime *runtime =
1792 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1793 if (runtime != nullptr &&
1794 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1795 return static_cast<CPPLanguageRuntime *>(runtime);
1796 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001797}
1798
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1800 LanguageRuntime *runtime =
1801 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1802 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1803 return static_cast<ObjCLanguageRuntime *>(runtime);
1804 return nullptr;
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001805}
1806
Kate Stoneb9c1b512016-09-06 20:57:50 +00001807bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1808 if (m_finalizing)
1809 return false;
1810
1811 if (in_value.IsDynamic())
1812 return false;
1813 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1814
1815 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1816 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1817 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1818 }
1819
1820 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1821 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1822 return true;
1823
1824 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1825 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001826}
1827
Kate Stoneb9c1b512016-09-06 20:57:50 +00001828void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1829 m_dynamic_checkers_ap.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830}
1831
Kate Stoneb9c1b512016-09-06 20:57:50 +00001832BreakpointSiteList &Process::GetBreakpointSiteList() {
1833 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834}
1835
Kate Stoneb9c1b512016-09-06 20:57:50 +00001836const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1837 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001838}
1839
Kate Stoneb9c1b512016-09-06 20:57:50 +00001840void Process::DisableAllBreakpointSites() {
1841 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1842 // bp_site->SetEnabled(true);
1843 DisableBreakpointSite(bp_site);
1844 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001845}
1846
Kate Stoneb9c1b512016-09-06 20:57:50 +00001847Error Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1848 Error error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001849
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850 if (error.Success())
1851 m_breakpoint_site_list.Remove(break_id);
1852
1853 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001854}
1855
Kate Stoneb9c1b512016-09-06 20:57:50 +00001856Error Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1857 Error error;
1858 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1859 if (bp_site_sp) {
1860 if (bp_site_sp->IsEnabled())
1861 error = DisableBreakpointSite(bp_site_sp.get());
1862 } else {
1863 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1864 break_id);
1865 }
1866
1867 return error;
1868}
1869
1870Error Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1871 Error error;
1872 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1873 if (bp_site_sp) {
1874 if (!bp_site_sp->IsEnabled())
1875 error = EnableBreakpointSite(bp_site_sp.get());
1876 } else {
1877 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1878 break_id);
1879 }
1880 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001881}
1882
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001883lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001884Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1885 bool use_hardware) {
1886 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001887
Kate Stoneb9c1b512016-09-06 20:57:50 +00001888 bool show_error = true;
1889 switch (GetState()) {
1890 case eStateInvalid:
1891 case eStateUnloaded:
1892 case eStateConnected:
1893 case eStateAttaching:
1894 case eStateLaunching:
1895 case eStateDetached:
1896 case eStateExited:
1897 show_error = false;
1898 break;
1899
1900 case eStateStopped:
1901 case eStateRunning:
1902 case eStateStepping:
1903 case eStateCrashed:
1904 case eStateSuspended:
1905 show_error = IsAlive();
1906 break;
1907 }
1908
1909 // Reset the IsIndirect flag here, in case the location changes from
1910 // pointing to a indirect symbol to a regular symbol.
1911 owner->SetIsIndirect(false);
1912
1913 if (owner->ShouldResolveIndirectFunctions()) {
1914 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1915 if (symbol && symbol->IsIndirect()) {
1916 Error error;
1917 Address symbol_address = symbol->GetAddress();
1918 load_addr = ResolveIndirectFunction(&symbol_address, error);
1919 if (!error.Success() && show_error) {
1920 GetTarget().GetDebugger().GetErrorFile()->Printf(
1921 "warning: failed to resolve indirect function at 0x%" PRIx64
1922 " for breakpoint %i.%i: %s\n",
1923 symbol->GetLoadAddress(&GetTarget()),
1924 owner->GetBreakpoint().GetID(), owner->GetID(),
1925 error.AsCString() ? error.AsCString() : "unknown error");
1926 return LLDB_INVALID_BREAK_ID;
1927 }
1928 Address resolved_address(load_addr);
1929 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1930 owner->SetIsIndirect(true);
1931 } else
1932 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1933 } else
1934 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1935
1936 if (load_addr != LLDB_INVALID_ADDRESS) {
1937 BreakpointSiteSP bp_site_sp;
1938
1939 // Look up this breakpoint site. If it exists, then add this new owner,
1940 // otherwise
1941 // create a new breakpoint site and add it.
1942
1943 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1944
1945 if (bp_site_sp) {
1946 bp_site_sp->AddOwner(owner);
1947 owner->SetBreakpointSite(bp_site_sp);
1948 return bp_site_sp->GetID();
1949 } else {
1950 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1951 load_addr, use_hardware));
1952 if (bp_site_sp) {
1953 Error error = EnableBreakpointSite(bp_site_sp.get());
1954 if (error.Success()) {
1955 owner->SetBreakpointSite(bp_site_sp);
1956 return m_breakpoint_site_list.Add(bp_site_sp);
1957 } else {
1958 if (show_error) {
1959 // Report error for setting breakpoint...
1960 GetTarget().GetDebugger().GetErrorFile()->Printf(
1961 "warning: failed to set breakpoint site at 0x%" PRIx64
1962 " for breakpoint %i.%i: %s\n",
1963 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1964 error.AsCString() ? error.AsCString() : "unknown error");
1965 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001966 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001967 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001968 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001969 }
1970 // We failed to enable the breakpoint
1971 return LLDB_INVALID_BREAK_ID;
1972}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001973
Kate Stoneb9c1b512016-09-06 20:57:50 +00001974void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1975 lldb::user_id_t owner_loc_id,
1976 BreakpointSiteSP &bp_site_sp) {
1977 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1978 if (num_owners == 0) {
1979 // Don't try to disable the site if we don't have a live process anymore.
1980 if (IsAlive())
1981 DisableBreakpointSite(bp_site_sp.get());
1982 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1983 }
1984}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001985
Kate Stoneb9c1b512016-09-06 20:57:50 +00001986size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1987 uint8_t *buf) const {
1988 size_t bytes_removed = 0;
1989 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001990
Kate Stoneb9c1b512016-09-06 20:57:50 +00001991 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1992 bp_sites_in_range)) {
1993 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](
1994 BreakpointSite *bp_site) -> void {
1995 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1996 addr_t intersect_addr;
1997 size_t intersect_size;
1998 size_t opcode_offset;
1999 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
2000 &intersect_size, &opcode_offset)) {
2001 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2002 assert(bp_addr < intersect_addr + intersect_size &&
2003 intersect_addr + intersect_size <= bp_addr + size);
2004 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
2005 size_t buf_offset = intersect_addr - bp_addr;
2006 ::memcpy(buf + buf_offset,
2007 bp_site->GetSavedOpcodeBytes() + opcode_offset,
2008 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002009 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002010 }
2011 });
2012 }
2013 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014}
2015
Kate Stoneb9c1b512016-09-06 20:57:50 +00002016size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
2017 PlatformSP platform_sp(GetTarget().GetPlatform());
2018 if (platform_sp)
2019 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
2020 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002021}
2022
Kate Stoneb9c1b512016-09-06 20:57:50 +00002023Error Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
2024 Error error;
2025 assert(bp_site != nullptr);
2026 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2027 const addr_t bp_addr = bp_site->GetLoadAddress();
2028 if (log)
2029 log->Printf(
2030 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
2031 bp_site->GetID(), (uint64_t)bp_addr);
2032 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002033 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002034 log->Printf(
2035 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2036 " -- already enabled",
2037 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002038 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002039 }
2040
2041 if (bp_addr == LLDB_INVALID_ADDRESS) {
2042 error.SetErrorString("BreakpointSite contains an invalid load address.");
2043 return error;
2044 }
2045 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2046 // trap for the breakpoint site
2047 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2048
2049 if (bp_opcode_size == 0) {
2050 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2051 "returned zero, unable to get breakpoint "
2052 "trap for address 0x%" PRIx64,
2053 bp_addr);
2054 } else {
2055 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2056
2057 if (bp_opcode_bytes == nullptr) {
2058 error.SetErrorString(
2059 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2060 return error;
2061 }
2062
2063 // Save the original opcode by reading it
2064 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2065 error) == bp_opcode_size) {
2066 // Write a software breakpoint in place of the original opcode
2067 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2068 bp_opcode_size) {
2069 uint8_t verify_bp_opcode_bytes[64];
2070 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2071 error) == bp_opcode_size) {
2072 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2073 bp_opcode_size) == 0) {
2074 bp_site->SetEnabled(true);
2075 bp_site->SetType(BreakpointSite::eSoftware);
2076 if (log)
2077 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2078 "addr = 0x%" PRIx64 " -- SUCCESS",
2079 bp_site->GetID(), (uint64_t)bp_addr);
2080 } else
2081 error.SetErrorString(
2082 "failed to verify the breakpoint trap in memory.");
2083 } else
2084 error.SetErrorString(
2085 "Unable to read memory to verify breakpoint trap.");
2086 } else
2087 error.SetErrorString("Unable to write breakpoint trap to memory.");
2088 } else
2089 error.SetErrorString("Unable to read memory at breakpoint address.");
2090 }
2091 if (log && error.Fail())
2092 log->Printf(
2093 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2094 " -- FAILED: %s",
2095 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2096 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002097}
2098
Kate Stoneb9c1b512016-09-06 20:57:50 +00002099Error Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2100 Error error;
2101 assert(bp_site != nullptr);
2102 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2103 addr_t bp_addr = bp_site->GetLoadAddress();
2104 lldb::user_id_t breakID = bp_site->GetID();
2105 if (log)
2106 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2107 ") addr = 0x%" PRIx64,
2108 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002109
Kate Stoneb9c1b512016-09-06 20:57:50 +00002110 if (bp_site->IsHardware()) {
2111 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2112 } else if (bp_site->IsEnabled()) {
2113 const size_t break_op_size = bp_site->GetByteSize();
2114 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2115 if (break_op_size > 0) {
2116 // Clear a software breakpoint instruction
2117 uint8_t curr_break_op[8];
2118 assert(break_op_size <= sizeof(curr_break_op));
2119 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002120
Kate Stoneb9c1b512016-09-06 20:57:50 +00002121 // Read the breakpoint opcode
2122 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2123 break_op_size) {
2124 bool verify = false;
2125 // Make sure the breakpoint opcode exists at this address
2126 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2127 break_op_found = true;
2128 // We found a valid breakpoint opcode at this address, now restore
2129 // the saved opcode.
2130 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2131 break_op_size, error) == break_op_size) {
2132 verify = true;
2133 } else
2134 error.SetErrorString(
2135 "Memory write failed when restoring original opcode.");
2136 } else {
2137 error.SetErrorString(
2138 "Original breakpoint trap is no longer in memory.");
2139 // Set verify to true and so we can check if the original opcode has
2140 // already been restored
2141 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002142 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002143
Kate Stoneb9c1b512016-09-06 20:57:50 +00002144 if (verify) {
2145 uint8_t verify_opcode[8];
2146 assert(break_op_size < sizeof(verify_opcode));
2147 // Verify that our original opcode made it back to the inferior
2148 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2149 break_op_size) {
2150 // compare the memory we just read with the original opcode
2151 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2152 break_op_size) == 0) {
2153 // SUCCESS
2154 bp_site->SetEnabled(false);
2155 if (log)
2156 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2157 "addr = 0x%" PRIx64 " -- SUCCESS",
2158 bp_site->GetID(), (uint64_t)bp_addr);
2159 return error;
2160 } else {
2161 if (break_op_found)
2162 error.SetErrorString("Failed to restore original opcode.");
2163 }
2164 } else
2165 error.SetErrorString("Failed to read memory to verify that "
2166 "breakpoint trap was restored.");
2167 }
2168 } else
2169 error.SetErrorString(
2170 "Unable to read memory that should contain the breakpoint trap.");
2171 }
2172 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002173 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002174 log->Printf(
2175 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2176 " -- already disabled",
2177 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002178 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002179 }
2180
2181 if (log)
2182 log->Printf(
2183 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2184 " -- FAILED: %s",
2185 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2186 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002187}
2188
Greg Clayton58be07b2011-01-07 06:08:19 +00002189// Uncomment to verify memory caching works after making changes to caching code
2190//#define VERIFY_MEMORY_READS
2191
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Error &error) {
2193 error.Clear();
2194 if (!GetDisableMemoryCache()) {
2195#if defined(VERIFY_MEMORY_READS)
2196 // Memory caching is enabled, with debug verification
2197
2198 if (buf && size) {
2199 // Uncomment the line below to make sure memory caching is working.
2200 // I ran this through the test suite and got no assertions, so I am
2201 // pretty confident this is working well. If any changes are made to
2202 // memory caching, uncomment the line below and test your changes!
2203
2204 // Verify all memory reads by using the cache first, then redundantly
2205 // reading the same memory from the inferior and comparing to make sure
2206 // everything is exactly the same.
2207 std::string verify_buf(size, '\0');
2208 assert(verify_buf.size() == size);
2209 const size_t cache_bytes_read =
2210 m_memory_cache.Read(this, addr, buf, size, error);
2211 Error verify_error;
2212 const size_t verify_bytes_read =
2213 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2214 verify_buf.size(), verify_error);
2215 assert(cache_bytes_read == verify_bytes_read);
2216 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2217 assert(verify_error.Success() == error.Success());
2218 return cache_bytes_read;
2219 }
2220 return 0;
2221#else // !defined(VERIFY_MEMORY_READS)
2222 // Memory caching is enabled, without debug verification
2223
2224 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002225#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226 } else {
2227 // Memory caching is disabled
2228
2229 return ReadMemoryFromInferior(addr, buf, size, error);
2230 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002231}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002232
2233size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2234 Error &error) {
2235 char buf[256];
2236 out_str.clear();
2237 addr_t curr_addr = addr;
2238 while (true) {
2239 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2240 if (length == 0)
2241 break;
2242 out_str.append(buf, length);
2243 // If we got "length - 1" bytes, we didn't get the whole C string, we
2244 // need to read some more characters
2245 if (length == sizeof(buf) - 1)
2246 curr_addr += length;
2247 else
2248 break;
2249 }
2250 return out_str.size();
2251}
2252
2253size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
2254 Error &error, size_t type_width) {
2255 size_t total_bytes_read = 0;
2256 if (dst && max_bytes && type_width && max_bytes >= type_width) {
2257 // Ensure a null terminator independent of the number of bytes that is read.
2258 memset(dst, 0, max_bytes);
2259 size_t bytes_left = max_bytes - type_width;
2260
2261 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2262 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2263 "string with more than 4 bytes "
2264 "per character!");
2265
Greg Clayton4c82d422012-05-18 23:20:01 +00002266 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002267 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2268 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002269
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270 error.Clear();
2271 while (bytes_left > 0 && error.Success()) {
2272 addr_t cache_line_bytes_left =
2273 cache_line_size - (curr_addr % cache_line_size);
2274 addr_t bytes_to_read =
2275 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2276 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002277
Kate Stoneb9c1b512016-09-06 20:57:50 +00002278 if (bytes_read == 0)
2279 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002280
Kate Stoneb9c1b512016-09-06 20:57:50 +00002281 // Search for a null terminator of correct size and alignment in
2282 // bytes_read
2283 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2284 for (size_t i = aligned_start;
2285 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2286 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2287 error.Clear();
2288 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002289 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002290
2291 total_bytes_read += bytes_read;
2292 curr_dst += bytes_read;
2293 curr_addr += bytes_read;
2294 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002295 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002296 } else {
2297 if (max_bytes)
2298 error.SetErrorString("invalid arguments");
2299 }
2300 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002301}
2302
Kate Stoneb9c1b512016-09-06 20:57:50 +00002303// Deprecated in favor of ReadStringFromMemory which has wchar support and
2304// correct code to find
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002305// null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002306size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
2307 size_t dst_max_len, Error &result_error) {
2308 size_t total_cstr_len = 0;
2309 if (dst && dst_max_len) {
2310 result_error.Clear();
2311 // NULL out everything just to be safe
2312 memset(dst, 0, dst_max_len);
2313 Error error;
2314 addr_t curr_addr = addr;
2315 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2316 size_t bytes_left = dst_max_len - 1;
2317 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002318
Kate Stoneb9c1b512016-09-06 20:57:50 +00002319 while (bytes_left > 0) {
2320 addr_t cache_line_bytes_left =
2321 cache_line_size - (curr_addr % cache_line_size);
2322 addr_t bytes_to_read =
2323 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2324 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002325
Kate Stoneb9c1b512016-09-06 20:57:50 +00002326 if (bytes_read == 0) {
2327 result_error = error;
2328 dst[total_cstr_len] = '\0';
2329 break;
2330 }
2331 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002332
Kate Stoneb9c1b512016-09-06 20:57:50 +00002333 total_cstr_len += len;
2334
2335 if (len < bytes_to_read)
2336 break;
2337
2338 curr_dst += bytes_read;
2339 curr_addr += bytes_read;
2340 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002341 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002342 } else {
2343 if (dst == nullptr)
2344 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002345 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002346 result_error.Clear();
2347 }
2348 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002349}
2350
Kate Stoneb9c1b512016-09-06 20:57:50 +00002351size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2352 Error &error) {
2353 if (buf == nullptr || size == 0)
2354 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002355
Kate Stoneb9c1b512016-09-06 20:57:50 +00002356 size_t bytes_read = 0;
2357 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002358
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359 while (bytes_read < size) {
2360 const size_t curr_size = size - bytes_read;
2361 const size_t curr_bytes_read =
2362 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2363 bytes_read += curr_bytes_read;
2364 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2365 break;
2366 }
2367
2368 // Replace any software breakpoint opcodes that fall into this range back
2369 // into "buf" before we return
2370 if (bytes_read > 0)
2371 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2372 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002373}
2374
Kate Stoneb9c1b512016-09-06 20:57:50 +00002375uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2376 size_t integer_byte_size,
2377 uint64_t fail_value,
2378 Error &error) {
2379 Scalar scalar;
2380 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2381 error))
2382 return scalar.ULongLong(fail_value);
2383 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002384}
2385
Kate Stoneb9c1b512016-09-06 20:57:50 +00002386int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2387 size_t integer_byte_size,
2388 int64_t fail_value, Error &error) {
2389 Scalar scalar;
2390 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2391 error))
2392 return scalar.SLongLong(fail_value);
2393 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002394}
2395
Kate Stoneb9c1b512016-09-06 20:57:50 +00002396addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error) {
2397 Scalar scalar;
2398 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2399 error))
2400 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2401 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002402}
2403
Kate Stoneb9c1b512016-09-06 20:57:50 +00002404bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
2405 Error &error) {
2406 Scalar scalar;
2407 const uint32_t addr_byte_size = GetAddressByteSize();
2408 if (addr_byte_size <= 4)
2409 scalar = (uint32_t)ptr_value;
2410 else
2411 scalar = ptr_value;
2412 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2413 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002414}
2415
Kate Stoneb9c1b512016-09-06 20:57:50 +00002416size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2417 Error &error) {
2418 size_t bytes_written = 0;
2419 const uint8_t *bytes = (const uint8_t *)buf;
2420
2421 while (bytes_written < size) {
2422 const size_t curr_size = size - bytes_written;
2423 const size_t curr_bytes_written = DoWriteMemory(
2424 addr + bytes_written, bytes + bytes_written, curr_size, error);
2425 bytes_written += curr_bytes_written;
2426 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2427 break;
2428 }
2429 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002430}
2431
Kate Stoneb9c1b512016-09-06 20:57:50 +00002432size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2433 Error &error) {
2434#if defined(ENABLE_MEMORY_CACHING)
2435 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002436#endif
2437
Kate Stoneb9c1b512016-09-06 20:57:50 +00002438 if (buf == nullptr || size == 0)
2439 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002440
Kate Stoneb9c1b512016-09-06 20:57:50 +00002441 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002442
Kate Stoneb9c1b512016-09-06 20:57:50 +00002443 // We need to write any data that would go where any current software traps
2444 // (enabled software breakpoints) any software traps (breakpoints) that we
2445 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002446
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002448
Kate Stoneb9c1b512016-09-06 20:57:50 +00002449 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2450 bp_sites_in_range)) {
2451 // No breakpoint sites overlap
2452 if (bp_sites_in_range.IsEmpty())
2453 return WriteMemoryPrivate(addr, buf, size, error);
2454 else {
2455 const uint8_t *ubuf = (const uint8_t *)buf;
2456 uint64_t bytes_written = 0;
2457
2458 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2459 &error](BreakpointSite *bp) -> void {
2460
2461 if (error.Success()) {
2462 addr_t intersect_addr;
2463 size_t intersect_size;
2464 size_t opcode_offset;
2465 const bool intersects = bp->IntersectsRange(
2466 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2467 UNUSED_IF_ASSERT_DISABLED(intersects);
2468 assert(intersects);
2469 assert(addr <= intersect_addr && intersect_addr < addr + size);
2470 assert(addr < intersect_addr + intersect_size &&
2471 intersect_addr + intersect_size <= addr + size);
2472 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2473
2474 // Check for bytes before this breakpoint
2475 const addr_t curr_addr = addr + bytes_written;
2476 if (intersect_addr > curr_addr) {
2477 // There are some bytes before this breakpoint that we need to
2478 // just write to memory
2479 size_t curr_size = intersect_addr - curr_addr;
2480 size_t curr_bytes_written = WriteMemoryPrivate(
2481 curr_addr, ubuf + bytes_written, curr_size, error);
2482 bytes_written += curr_bytes_written;
2483 if (curr_bytes_written != curr_size) {
2484 // We weren't able to write all of the requested bytes, we
2485 // are done looping and will return the number of bytes that
2486 // we have written so far.
2487 if (error.Success())
2488 error.SetErrorToGenericError();
2489 }
2490 }
2491 // Now write any bytes that would cover up any software breakpoints
2492 // directly into the breakpoint opcode buffer
2493 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2494 ubuf + bytes_written, intersect_size);
2495 bytes_written += intersect_size;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002496 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002497 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002498
Kate Stoneb9c1b512016-09-06 20:57:50 +00002499 if (bytes_written < size)
2500 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2501 size - bytes_written, error);
2502 }
2503 } else {
2504 return WriteMemoryPrivate(addr, buf, size, error);
2505 }
2506
2507 // Write any remaining bytes after the last breakpoint if we have any left
2508 return 0; // bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002509}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002510
Kate Stoneb9c1b512016-09-06 20:57:50 +00002511size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2512 size_t byte_size, Error &error) {
2513 if (byte_size == UINT32_MAX)
2514 byte_size = scalar.GetByteSize();
2515 if (byte_size > 0) {
2516 uint8_t buf[32];
2517 const size_t mem_size =
2518 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2519 if (mem_size > 0)
2520 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002521 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002522 error.SetErrorString("failed to get scalar as memory data");
2523 } else {
2524 error.SetErrorString("invalid scalar value");
2525 }
2526 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002527}
2528
Kate Stoneb9c1b512016-09-06 20:57:50 +00002529size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2530 bool is_signed, Scalar &scalar,
2531 Error &error) {
2532 uint64_t uval = 0;
2533 if (byte_size == 0) {
2534 error.SetErrorString("byte size is zero");
2535 } else if (byte_size & (byte_size - 1)) {
2536 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2537 byte_size);
2538 } else if (byte_size <= sizeof(uval)) {
2539 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2540 if (bytes_read == byte_size) {
2541 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2542 GetAddressByteSize());
2543 lldb::offset_t offset = 0;
2544 if (byte_size <= 4)
2545 scalar = data.GetMaxU32(&offset, byte_size);
2546 else
2547 scalar = data.GetMaxU64(&offset, byte_size);
2548 if (is_signed)
2549 scalar.SignExtend(byte_size * 8);
2550 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002551 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552 } else {
2553 error.SetErrorStringWithFormat(
2554 "byte size of %u is too large for integer scalar type", byte_size);
2555 }
2556 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002557}
2558
Greg Claytond495c532011-05-17 03:37:42 +00002559#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002560addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2561 Error &error) {
2562 if (GetPrivateState() != eStateStopped)
2563 return LLDB_INVALID_ADDRESS;
2564
2565#if defined(USE_ALLOCATE_MEMORY_CACHE)
2566 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002567#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002568 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2569 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2570 if (log)
2571 log->Printf("Process::AllocateMemory(size=%" PRIu64
2572 ", permissions=%s) => 0x%16.16" PRIx64
2573 " (m_stop_id = %u m_memory_id = %u)",
2574 (uint64_t)size, GetPermissionsAsCString(permissions),
2575 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2576 m_mod_id.GetMemoryID());
2577 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002578#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002579}
2580
Kate Stoneb9c1b512016-09-06 20:57:50 +00002581addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2582 Error &error) {
2583 addr_t return_addr = AllocateMemory(size, permissions, error);
2584 if (error.Success()) {
2585 std::string buffer(size, 0);
2586 WriteMemory(return_addr, buffer.c_str(), size, error);
2587 }
2588 return return_addr;
2589}
2590
2591bool Process::CanJIT() {
2592 if (m_can_jit == eCanJITDontKnow) {
2593 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2594 Error err;
2595
2596 uint64_t allocated_memory = AllocateMemory(
2597 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2598 err);
2599
2600 if (err.Success()) {
2601 m_can_jit = eCanJITYes;
2602 if (log)
2603 log->Printf("Process::%s pid %" PRIu64
2604 " allocation test passed, CanJIT () is true",
2605 __FUNCTION__, GetID());
2606 } else {
2607 m_can_jit = eCanJITNo;
2608 if (log)
2609 log->Printf("Process::%s pid %" PRIu64
2610 " allocation test failed, CanJIT () is false: %s",
2611 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002612 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002613
2614 DeallocateMemory(allocated_memory);
2615 }
2616
2617 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002618}
2619
Kate Stoneb9c1b512016-09-06 20:57:50 +00002620void Process::SetCanJIT(bool can_jit) {
2621 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002622}
2623
Kate Stoneb9c1b512016-09-06 20:57:50 +00002624void Process::SetCanRunCode(bool can_run_code) {
2625 SetCanJIT(can_run_code);
2626 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002627}
2628
Kate Stoneb9c1b512016-09-06 20:57:50 +00002629Error Process::DeallocateMemory(addr_t ptr) {
2630 Error error;
2631#if defined(USE_ALLOCATE_MEMORY_CACHE)
2632 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2633 error.SetErrorStringWithFormat(
2634 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2635 }
Greg Claytond495c532011-05-17 03:37:42 +00002636#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002637 error = DoDeallocateMemory(ptr);
2638
2639 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2640 if (log)
2641 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2642 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2643 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2644 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002645#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002646 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002647}
2648
Kate Stoneb9c1b512016-09-06 20:57:50 +00002649ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2650 lldb::addr_t header_addr,
2651 size_t size_to_read) {
2652 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2653 if (log) {
2654 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2655 file_spec.GetPath().c_str());
2656 }
2657 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2658 if (module_sp) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002659 Error error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002660 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2661 shared_from_this(), header_addr, error, size_to_read);
2662 if (objfile)
2663 return module_sp;
2664 }
2665 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002666}
2667
Kate Stoneb9c1b512016-09-06 20:57:50 +00002668bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2669 uint32_t &permissions) {
2670 MemoryRegionInfo range_info;
2671 permissions = 0;
2672 Error error(GetMemoryRegionInfo(load_addr, range_info));
2673 if (!error.Success())
2674 return false;
2675 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2676 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2677 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2678 return false;
2679 }
2680
2681 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2682 permissions |= lldb::ePermissionsReadable;
2683
2684 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2685 permissions |= lldb::ePermissionsWritable;
2686
2687 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2688 permissions |= lldb::ePermissionsExecutable;
2689
2690 return true;
2691}
2692
2693Error Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2694 Error error;
2695 error.SetErrorString("watchpoints are not supported");
2696 return error;
2697}
2698
2699Error Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2700 Error error;
2701 error.SetErrorString("watchpoints are not supported");
2702 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002703}
2704
2705StateType
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706Process::WaitForProcessStopPrivate(const std::chrono::microseconds &timeout,
2707 EventSP &event_sp) {
2708 StateType state;
2709 // Now wait for the process to launch and return control to us, and then
2710 // call DidLaunch:
2711 while (true) {
2712 event_sp.reset();
2713 state = WaitForStateChangedEventsPrivate(timeout, event_sp);
Greg Clayton6779606a2011-01-22 23:43:18 +00002714
Kate Stoneb9c1b512016-09-06 20:57:50 +00002715 if (StateIsStoppedState(state, false))
2716 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002717
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718 // If state is invalid, then we timed out
2719 if (state == eStateInvalid)
2720 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002721
Kate Stoneb9c1b512016-09-06 20:57:50 +00002722 if (event_sp)
2723 HandlePrivateEvent(event_sp);
2724 }
2725 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002726}
2727
Kate Stoneb9c1b512016-09-06 20:57:50 +00002728void Process::LoadOperatingSystemPlugin(bool flush) {
2729 if (flush)
2730 m_thread_list.Clear();
2731 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2732 if (flush)
2733 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002734}
2735
Kate Stoneb9c1b512016-09-06 20:57:50 +00002736Error Process::Launch(ProcessLaunchInfo &launch_info) {
2737 Error error;
2738 m_abi_sp.reset();
2739 m_dyld_ap.reset();
2740 m_jit_loaders_ap.reset();
2741 m_system_runtime_ap.reset();
2742 m_os_ap.reset();
2743 m_process_input_reader.reset();
2744 m_stop_info_override_callback = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745
Kate Stoneb9c1b512016-09-06 20:57:50 +00002746 Module *exe_module = GetTarget().GetExecutableModulePointer();
2747 if (exe_module) {
2748 char local_exec_file_path[PATH_MAX];
2749 char platform_exec_file_path[PATH_MAX];
2750 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2751 sizeof(local_exec_file_path));
2752 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2753 sizeof(platform_exec_file_path));
2754 if (exe_module->GetFileSpec().Exists()) {
2755 // Install anything that might need to be installed prior to launching.
2756 // For host systems, this will do nothing, but if we are connected to a
2757 // remote platform it will install any needed binaries
2758 error = GetTarget().Install(&launch_info);
2759 if (error.Fail())
2760 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002761
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762 if (PrivateStateThreadIsValid())
2763 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002764
Kate Stoneb9c1b512016-09-06 20:57:50 +00002765 error = WillLaunch(exe_module);
2766 if (error.Success()) {
2767 const bool restarted = false;
2768 SetPublicState(eStateLaunching, restarted);
2769 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002770
Kate Stoneb9c1b512016-09-06 20:57:50 +00002771 if (m_public_run_lock.TrySetRunning()) {
2772 // Now launch using these arguments.
2773 error = DoLaunch(exe_module, launch_info);
2774 } else {
2775 // This shouldn't happen
2776 error.SetErrorString("failed to acquire process run lock");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002777 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002778
Kate Stoneb9c1b512016-09-06 20:57:50 +00002779 if (error.Fail()) {
2780 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2781 SetID(LLDB_INVALID_PROCESS_ID);
2782 const char *error_string = error.AsCString();
2783 if (error_string == nullptr)
2784 error_string = "launch failed";
2785 SetExitStatus(-1, error_string);
2786 }
2787 } else {
2788 EventSP event_sp;
2789 StateType state =
2790 WaitForProcessStopPrivate(std::chrono::seconds(10), event_sp);
Greg Clayton35824e32015-02-20 20:59:47 +00002791
Kate Stoneb9c1b512016-09-06 20:57:50 +00002792 if (state == eStateInvalid || !event_sp) {
2793 // We were able to launch the process, but we failed to
2794 // catch the initial stop.
2795 error.SetErrorString("failed to catch stop after launch");
2796 SetExitStatus(0, "failed to catch stop after launch");
2797 Destroy(false);
2798 } else if (state == eStateStopped || state == eStateCrashed) {
2799 DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002800
Kate Stoneb9c1b512016-09-06 20:57:50 +00002801 DynamicLoader *dyld = GetDynamicLoader();
2802 if (dyld)
2803 dyld->DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002804
Kate Stoneb9c1b512016-09-06 20:57:50 +00002805 GetJITLoaders().DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002806
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807 SystemRuntime *system_runtime = GetSystemRuntime();
2808 if (system_runtime)
2809 system_runtime->DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002810
Kate Stoneb9c1b512016-09-06 20:57:50 +00002811 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002812
Kate Stoneb9c1b512016-09-06 20:57:50 +00002813 // Note, the stop event was consumed above, but not handled. This
2814 // was done
2815 // to give DidLaunch a chance to run. The target is either stopped
2816 // or crashed.
2817 // Directly set the state. This is done to prevent a stop message
2818 // with a bunch
2819 // of spurious output on thread status, as well as not pop a
2820 // ProcessIOHandler.
2821 SetPublicState(state, false);
Greg Claytonc3776bf2012-02-09 06:16:32 +00002822
Kate Stoneb9c1b512016-09-06 20:57:50 +00002823 if (PrivateStateThreadIsValid())
2824 ResumePrivateStateThread();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002825 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 StartPrivateStateThread();
Todd Fiala76e0fc92014-08-27 22:58:26 +00002827
Kate Stoneb9c1b512016-09-06 20:57:50 +00002828 m_stop_info_override_callback =
2829 GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002830
Kate Stoneb9c1b512016-09-06 20:57:50 +00002831 // Target was stopped at entry as was intended. Need to notify the
2832 // listeners
2833 // about it.
2834 if (state == eStateStopped &&
2835 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2836 HandlePrivateEvent(event_sp);
2837 } else if (state == eStateExited) {
2838 // We exited while trying to launch somehow. Don't call DidLaunch
2839 // as that's
2840 // not likely to work, and return an invalid pid.
2841 HandlePrivateEvent(event_sp);
2842 }
2843 }
2844 }
2845 } else {
2846 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2847 local_exec_file_path);
Jim Inghambb3a2832011-01-29 01:49:25 +00002848 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002849 }
2850 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002851}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852
Kate Stoneb9c1b512016-09-06 20:57:50 +00002853Error Process::LoadCore() {
2854 Error error = DoLoadCore();
2855 if (error.Success()) {
2856 ListenerSP listener_sp(
2857 Listener::MakeListener("lldb.process.load_core_listener"));
2858 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002859
Kate Stoneb9c1b512016-09-06 20:57:50 +00002860 if (PrivateStateThreadIsValid())
2861 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002862 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002863 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002864
Kate Stoneb9c1b512016-09-06 20:57:50 +00002865 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002866 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002867 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002868
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002869 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002870
Kate Stoneb9c1b512016-09-06 20:57:50 +00002871 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002872 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002873 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002874
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002875 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876 // We successfully loaded a core file, now pretend we stopped so we can
2877 // show all of the threads in the core file and explore the crashed
2878 // state.
2879 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002880
Kate Stoneb9c1b512016-09-06 20:57:50 +00002881 // Wait indefinitely for a stopped event since we just posted one above...
2882 lldb::EventSP event_sp;
2883 listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp);
2884 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2885
2886 if (!StateIsStoppedState(state, false)) {
2887 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2888 if (log)
2889 log->Printf("Process::Halt() failed to stop, state is: %s",
2890 StateAsCString(state));
2891 error.SetErrorString(
2892 "Did not get stopped event after loading the core file.");
2893 }
2894 RestoreProcessEvents();
2895 }
2896 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002897}
2898
Kate Stoneb9c1b512016-09-06 20:57:50 +00002899DynamicLoader *Process::GetDynamicLoader() {
2900 if (!m_dyld_ap)
2901 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2902 return m_dyld_ap.get();
2903}
2904
2905const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2906
2907JITLoaderList &Process::GetJITLoaders() {
2908 if (!m_jit_loaders_ap) {
2909 m_jit_loaders_ap.reset(new JITLoaderList());
2910 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2911 }
2912 return *m_jit_loaders_ap;
2913}
2914
2915SystemRuntime *Process::GetSystemRuntime() {
2916 if (!m_system_runtime_ap)
2917 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2918 return m_system_runtime_ap.get();
2919}
2920
2921Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2922 uint32_t exec_count)
2923 : NextEventAction(process), m_exec_count(exec_count) {
2924 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2925 if (log)
2926 log->Printf(
2927 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2928 __FUNCTION__, static_cast<void *>(process), exec_count);
2929}
2930
2931Process::NextEventAction::EventActionResult
2932Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2933 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2934
2935 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2936 if (log)
2937 log->Printf(
2938 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2939 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2940
2941 switch (state) {
2942 case eStateAttaching:
2943 return eEventActionSuccess;
2944
2945 case eStateRunning:
2946 case eStateConnected:
2947 return eEventActionRetry;
2948
2949 case eStateStopped:
2950 case eStateCrashed:
2951 // During attach, prior to sending the eStateStopped event,
2952 // lldb_private::Process subclasses must set the new process ID.
2953 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2954 // We don't want these events to be reported, so go set the ShouldReportStop
2955 // here:
2956 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2957
2958 if (m_exec_count > 0) {
2959 --m_exec_count;
2960
2961 if (log)
2962 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2963 "remaining exec count to %" PRIu32 ", requesting resume",
2964 __FUNCTION__, StateAsCString(state), m_exec_count);
2965
2966 RequestResume();
2967 return eEventActionRetry;
2968 } else {
2969 if (log)
2970 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2971 "execs expected to start, continuing with attach",
2972 __FUNCTION__, StateAsCString(state));
2973
2974 m_process->CompleteAttach();
2975 return eEventActionSuccess;
2976 }
2977 break;
2978
2979 default:
2980 case eStateExited:
2981 case eStateInvalid:
2982 break;
2983 }
2984
2985 m_exit_string.assign("No valid Process");
2986 return eEventActionExit;
2987}
2988
2989Process::NextEventAction::EventActionResult
2990Process::AttachCompletionHandler::HandleBeingInterrupted() {
2991 return eEventActionSuccess;
2992}
2993
2994const char *Process::AttachCompletionHandler::GetExitString() {
2995 return m_exit_string.c_str();
2996}
2997
2998ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2999 if (m_listener_sp)
3000 return m_listener_sp;
3001 else
3002 return debugger.GetListener();
3003}
3004
3005Error Process::Attach(ProcessAttachInfo &attach_info) {
3006 m_abi_sp.reset();
3007 m_process_input_reader.reset();
3008 m_dyld_ap.reset();
3009 m_jit_loaders_ap.reset();
3010 m_system_runtime_ap.reset();
3011 m_os_ap.reset();
3012 m_stop_info_override_callback = nullptr;
3013
3014 lldb::pid_t attach_pid = attach_info.GetProcessID();
3015 Error error;
3016 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
3017 char process_name[PATH_MAX];
3018
3019 if (attach_info.GetExecutableFile().GetPath(process_name,
3020 sizeof(process_name))) {
3021 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3022
3023 if (wait_for_launch) {
3024 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3025 if (error.Success()) {
3026 if (m_public_run_lock.TrySetRunning()) {
3027 m_should_detach = true;
3028 const bool restarted = false;
3029 SetPublicState(eStateAttaching, restarted);
3030 // Now attach using these arguments.
3031 error = DoAttachToProcessWithName(process_name, attach_info);
3032 } else {
3033 // This shouldn't happen
3034 error.SetErrorString("failed to acquire process run lock");
3035 }
3036
3037 if (error.Fail()) {
3038 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3039 SetID(LLDB_INVALID_PROCESS_ID);
3040 if (error.AsCString() == nullptr)
3041 error.SetErrorString("attach failed");
3042
3043 SetExitStatus(-1, error.AsCString());
3044 }
3045 } else {
3046 SetNextEventAction(new Process::AttachCompletionHandler(
3047 this, attach_info.GetResumeCount()));
3048 StartPrivateStateThread();
3049 }
3050 return error;
3051 }
3052 } else {
3053 ProcessInstanceInfoList process_infos;
3054 PlatformSP platform_sp(GetTarget().GetPlatform());
3055
3056 if (platform_sp) {
3057 ProcessInstanceInfoMatch match_info;
3058 match_info.GetProcessInfo() = attach_info;
3059 match_info.SetNameMatchType(eNameMatchEquals);
3060 platform_sp->FindProcesses(match_info, process_infos);
3061 const uint32_t num_matches = process_infos.GetSize();
3062 if (num_matches == 1) {
3063 attach_pid = process_infos.GetProcessIDAtIndex(0);
3064 // Fall through and attach using the above process ID
3065 } else {
3066 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3067 process_name, sizeof(process_name));
3068 if (num_matches > 1) {
3069 StreamString s;
3070 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3071 false);
3072 for (size_t i = 0; i < num_matches; i++) {
3073 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3074 s, platform_sp.get(), true, false);
3075 }
3076 error.SetErrorStringWithFormat(
3077 "more than one process named %s:\n%s", process_name,
3078 s.GetData());
3079 } else
3080 error.SetErrorStringWithFormat(
3081 "could not find a process named %s", process_name);
3082 }
3083 } else {
3084 error.SetErrorString(
3085 "invalid platform, can't find processes by name");
3086 return error;
3087 }
3088 }
3089 } else {
3090 error.SetErrorString("invalid process name");
3091 }
3092 }
3093
3094 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3095 error = WillAttachToProcessWithID(attach_pid);
3096 if (error.Success()) {
3097
3098 if (m_public_run_lock.TrySetRunning()) {
3099 // Now attach using these arguments.
3100 m_should_detach = true;
3101 const bool restarted = false;
3102 SetPublicState(eStateAttaching, restarted);
3103 error = DoAttachToProcessWithID(attach_pid, attach_info);
3104 } else {
3105 // This shouldn't happen
3106 error.SetErrorString("failed to acquire process run lock");
3107 }
3108
3109 if (error.Success()) {
3110 SetNextEventAction(new Process::AttachCompletionHandler(
3111 this, attach_info.GetResumeCount()));
3112 StartPrivateStateThread();
3113 } else {
Greg Clayton71337622011-02-24 22:24:29 +00003114 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003115 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003116
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117 const char *error_string = error.AsCString();
3118 if (error_string == nullptr)
3119 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00003120
Kate Stoneb9c1b512016-09-06 20:57:50 +00003121 SetExitStatus(-1, error_string);
3122 }
Greg Claytonb766a732011-02-04 01:58:07 +00003123 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003124 }
3125 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00003126}
3127
Kate Stoneb9c1b512016-09-06 20:57:50 +00003128void Process::CompleteAttach() {
3129 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3130 LIBLLDB_LOG_TARGET));
3131 if (log)
3132 log->Printf("Process::%s()", __FUNCTION__);
3133
3134 // Let the process subclass figure out at much as it can about the process
3135 // before we go looking for a dynamic loader plug-in.
3136 ArchSpec process_arch;
3137 DidAttach(process_arch);
3138
3139 if (process_arch.IsValid()) {
3140 GetTarget().SetArchitecture(process_arch);
3141 if (log) {
3142 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3143 log->Printf("Process::%s replacing process architecture with DidAttach() "
3144 "architecture: %s",
3145 __FUNCTION__, triple_str ? triple_str : "<null>");
3146 }
3147 }
3148
3149 // We just attached. If we have a platform, ask it for the process
3150 // architecture, and if it isn't
3151 // the same as the one we've already set, switch architectures.
3152 PlatformSP platform_sp(GetTarget().GetPlatform());
3153 assert(platform_sp);
3154 if (platform_sp) {
3155 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3156 if (target_arch.IsValid() &&
3157 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3158 ArchSpec platform_arch;
3159 platform_sp =
3160 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3161 if (platform_sp) {
3162 GetTarget().SetPlatform(platform_sp);
3163 GetTarget().SetArchitecture(platform_arch);
3164 if (log)
3165 log->Printf("Process::%s switching platform to %s and architecture "
3166 "to %s based on info from attach",
3167 __FUNCTION__, platform_sp->GetName().AsCString(""),
3168 platform_arch.GetTriple().getTriple().c_str());
3169 }
3170 } else if (!process_arch.IsValid()) {
3171 ProcessInstanceInfo process_info;
3172 GetProcessInfo(process_info);
3173 const ArchSpec &process_arch = process_info.GetArchitecture();
3174 if (process_arch.IsValid() &&
3175 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3176 GetTarget().SetArchitecture(process_arch);
3177 if (log)
3178 log->Printf("Process::%s switching architecture to %s based on info "
3179 "the platform retrieved for pid %" PRIu64,
3180 __FUNCTION__,
3181 process_arch.GetTriple().getTriple().c_str(), GetID());
3182 }
3183 }
3184 }
3185
3186 // We have completed the attach, now it is time to find the dynamic loader
3187 // plug-in
3188 DynamicLoader *dyld = GetDynamicLoader();
3189 if (dyld) {
3190 dyld->DidAttach();
3191 if (log) {
3192 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3193 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3194 "executable is %s (using %s plugin)",
3195 __FUNCTION__,
3196 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3197 : "<none>",
3198 dyld->GetPluginName().AsCString("<unnamed>"));
3199 }
3200 }
3201
3202 GetJITLoaders().DidAttach();
3203
3204 SystemRuntime *system_runtime = GetSystemRuntime();
3205 if (system_runtime) {
3206 system_runtime->DidAttach();
3207 if (log) {
3208 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3209 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3210 "executable is %s (using %s plugin)",
3211 __FUNCTION__,
3212 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3213 : "<none>",
3214 system_runtime->GetPluginName().AsCString("<unnamed>"));
3215 }
3216 }
3217
3218 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
3219 // Figure out which one is the executable, and set that in our target:
3220 const ModuleList &target_modules = GetTarget().GetImages();
3221 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3222 size_t num_modules = target_modules.GetSize();
3223 ModuleSP new_executable_module_sp;
3224
3225 for (size_t i = 0; i < num_modules; i++) {
3226 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3227 if (module_sp && module_sp->IsExecutable()) {
3228 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3229 new_executable_module_sp = module_sp;
3230 break;
3231 }
3232 }
3233 if (new_executable_module_sp) {
3234 GetTarget().SetExecutableModule(new_executable_module_sp, false);
3235 if (log) {
3236 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3237 log->Printf(
3238 "Process::%s after looping through modules, target executable is %s",
3239 __FUNCTION__,
3240 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3241 : "<none>");
3242 }
3243 }
3244
3245 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
3246}
3247
3248Error Process::ConnectRemote(Stream *strm, const char *remote_url) {
3249 m_abi_sp.reset();
3250 m_process_input_reader.reset();
3251
3252 // Find the process and its architecture. Make sure it matches the
3253 // architecture
3254 // of the current Target, and if not adjust it.
3255
3256 Error error(DoConnectRemote(strm, remote_url));
3257 if (error.Success()) {
3258 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3259 EventSP event_sp;
3260 StateType state =
3261 WaitForProcessStopPrivate(std::chrono::microseconds(0), event_sp);
3262
3263 if (state == eStateStopped || state == eStateCrashed) {
3264 // If we attached and actually have a process on the other end, then
3265 // this ended up being the equivalent of an attach.
3266 CompleteAttach();
3267
3268 // This delays passing the stopped event to listeners till
3269 // CompleteAttach gets a chance to complete...
3270 HandlePrivateEvent(event_sp);
3271 }
3272 }
3273
3274 if (PrivateStateThreadIsValid())
3275 ResumePrivateStateThread();
3276 else
3277 StartPrivateStateThread();
3278 }
3279 return error;
3280}
3281
3282Error Process::PrivateResume() {
3283 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3284 LIBLLDB_LOG_STEP));
3285 if (log)
3286 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3287 "private state: %s",
3288 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3289 StateAsCString(m_private_state.GetValue()));
3290
3291 Error error(WillResume());
3292 // Tell the process it is about to resume before the thread list
3293 if (error.Success()) {
3294 // Now let the thread list know we are about to resume so it
3295 // can let all of our threads know that they are about to be
3296 // resumed. Threads will each be called with
3297 // Thread::WillResume(StateType) where StateType contains the state
3298 // that they are supposed to have when the process is resumed
3299 // (suspended/running/stepping). Threads should also check
3300 // their resume signal in lldb::Thread::GetResumeSignal()
3301 // to see if they are supposed to start back up with a signal.
3302 if (m_thread_list.WillResume()) {
3303 // Last thing, do the PreResumeActions.
3304 if (!RunPreResumeActions()) {
3305 error.SetErrorStringWithFormat(
3306 "Process::PrivateResume PreResumeActions failed, not resuming.");
3307 } else {
3308 m_mod_id.BumpResumeID();
3309 error = DoResume();
3310 if (error.Success()) {
3311 DidResume();
3312 m_thread_list.DidResume();
3313 if (log)
3314 log->Printf("Process thinks the process has resumed.");
3315 }
3316 }
3317 } else {
3318 // Somebody wanted to run without running (e.g. we were faking a step from
3319 // one frame of a set of inlined
3320 // frames that share the same PC to another.) So generate a continue & a
3321 // stopped event,
3322 // and let the world handle them.
3323 if (log)
3324 log->Printf(
3325 "Process::PrivateResume() asked to simulate a start & stop.");
3326
3327 SetPrivateState(eStateRunning);
3328 SetPrivateState(eStateStopped);
3329 }
3330 } else if (log)
3331 log->Printf("Process::PrivateResume() got an error \"%s\".",
3332 error.AsCString("<unknown error>"));
3333 return error;
3334}
3335
3336Error Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3337 if (!StateIsRunningState(m_public_state.GetValue()))
3338 return Error("Process is not running.");
3339
3340 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3341 // in case it was already set and some thread plan logic calls halt on its
3342 // own.
3343 m_clear_thread_plans_on_stop |= clear_thread_plans;
3344
3345 ListenerSP halt_listener_sp(
3346 Listener::MakeListener("lldb.process.halt_listener"));
3347 HijackProcessEvents(halt_listener_sp);
3348
3349 EventSP event_sp;
3350
3351 SendAsyncInterrupt();
3352
3353 if (m_public_state.GetValue() == eStateAttaching) {
3354 // Don't hijack and eat the eStateExited as the code that was doing
3355 // the attach will be waiting for this event...
3356 RestoreProcessEvents();
3357 SetExitStatus(SIGKILL, "Cancelled async attach.");
3358 Destroy(false);
Mehdi Aminic1edf562016-11-11 04:29:25 +00003359 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003360 }
3361
3362 // Wait for 10 second for the process to stop.
3363 StateType state =
3364 WaitForProcessToStop(std::chrono::seconds(10), &event_sp, true,
3365 halt_listener_sp, nullptr, use_run_lock);
3366 RestoreProcessEvents();
3367
3368 if (state == eStateInvalid || !event_sp) {
3369 // We timed out and didn't get a stop event...
3370 return Error("Halt timed out. State = %s", StateAsCString(GetState()));
3371 }
3372
3373 BroadcastEvent(event_sp);
3374
Mehdi Aminic1edf562016-11-11 04:29:25 +00003375 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003376}
3377
3378Error Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3379 Error error;
3380
3381 // Check both the public & private states here. If we're hung evaluating an
3382 // expression, for instance, then
3383 // the public state will be stopped, but we still need to interrupt.
3384 if (m_public_state.GetValue() == eStateRunning ||
3385 m_private_state.GetValue() == eStateRunning) {
3386 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003387 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003388 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003389
Kate Stoneb9c1b512016-09-06 20:57:50 +00003390 ListenerSP listener_sp(
3391 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3392 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003393
Pavel Labath19da1f12015-12-07 12:36:52 +00003394 SendAsyncInterrupt();
3395
Kate Stoneb9c1b512016-09-06 20:57:50 +00003396 // Consume the interrupt event.
3397 StateType state = WaitForProcessToStop(std::chrono::seconds(10),
3398 &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003399
Pavel Labath19da1f12015-12-07 12:36:52 +00003400 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003401
Kate Stoneb9c1b512016-09-06 20:57:50 +00003402 // If the process exited while we were waiting for it to stop, put the
3403 // exited event into
3404 // the shared pointer passed in and return. Our caller doesn't need to do
3405 // anything else, since
3406 // they don't have a process anymore...
3407
3408 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3409 if (log)
3410 log->Printf("Process::%s() Process exited while waiting to stop.",
3411 __FUNCTION__);
3412 return error;
3413 } else
3414 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3415
3416 if (state != eStateStopped) {
3417 if (log)
3418 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3419 StateAsCString(state));
3420 // If we really couldn't stop the process then we should just error out
3421 // here, but if the
3422 // lower levels just bobbled sending the event and we really are stopped,
3423 // then continue on.
3424 StateType private_state = m_private_state.GetValue();
3425 if (private_state != eStateStopped) {
3426 return Error("Attempt to stop the target in order to detach timed out. "
3427 "State = %s",
3428 StateAsCString(GetState()));
3429 }
3430 }
3431 }
3432 return error;
3433}
3434
3435Error Process::Detach(bool keep_stopped) {
3436 EventSP exit_event_sp;
3437 Error error;
3438 m_destroy_in_process = true;
3439
3440 error = WillDetach();
3441
3442 if (error.Success()) {
3443 if (DetachRequiresHalt()) {
3444 error = StopForDestroyOrDetach(exit_event_sp);
3445 if (!error.Success()) {
3446 m_destroy_in_process = false;
3447 return error;
3448 } else if (exit_event_sp) {
3449 // We shouldn't need to do anything else here. There's no process left
3450 // to detach from...
3451 StopPrivateStateThread();
3452 m_destroy_in_process = false;
3453 return error;
3454 }
3455 }
3456
3457 m_thread_list.DiscardThreadPlans();
3458 DisableAllBreakpointSites();
3459
3460 error = DoDetach(keep_stopped);
3461 if (error.Success()) {
3462 DidDetach();
3463 StopPrivateStateThread();
3464 } else {
3465 return error;
3466 }
3467 }
3468 m_destroy_in_process = false;
3469
3470 // If we exited when we were waiting for a process to stop, then
3471 // forward the event here so we don't lose the event
3472 if (exit_event_sp) {
3473 // Directly broadcast our exited event because we shut down our
3474 // private state thread above
3475 BroadcastEvent(exit_event_sp);
3476 }
3477
3478 // If we have been interrupted (to kill us) in the middle of running, we may
3479 // not end up propagating
3480 // the last events through the event system, in which case we might strand the
3481 // write lock. Unlock
3482 // it here so when we do to tear down the process we don't get an error
3483 // destroying the lock.
3484
3485 m_public_run_lock.SetStopped();
3486 return error;
3487}
3488
3489Error Process::Destroy(bool force_kill) {
3490
3491 // Tell ourselves we are in the process of destroying the process, so that we
3492 // don't do any unnecessary work
3493 // that might hinder the destruction. Remember to set this back to false when
3494 // we are done. That way if the attempt
3495 // failed and the process stays around for some reason it won't be in a
3496 // confused state.
3497
3498 if (force_kill)
3499 m_should_detach = false;
3500
3501 if (GetShouldDetach()) {
3502 // FIXME: This will have to be a process setting:
3503 bool keep_stopped = false;
3504 Detach(keep_stopped);
3505 }
3506
3507 m_destroy_in_process = true;
3508
3509 Error error(WillDestroy());
3510 if (error.Success()) {
3511 EventSP exit_event_sp;
3512 if (DestroyRequiresHalt()) {
3513 error = StopForDestroyOrDetach(exit_event_sp);
3514 }
3515
3516 if (m_public_state.GetValue() != eStateRunning) {
3517 // Ditch all thread plans, and remove all our breakpoints: in case we have
3518 // to restart the target to
3519 // kill it, we don't want it hitting a breakpoint...
3520 // Only do this if we've stopped, however, since if we didn't manage to
3521 // halt it above, then
3522 // we're not going to have much luck doing this now.
3523 m_thread_list.DiscardThreadPlans();
3524 DisableAllBreakpointSites();
3525 }
3526
3527 error = DoDestroy();
3528 if (error.Success()) {
3529 DidDestroy();
3530 StopPrivateStateThread();
3531 }
3532 m_stdio_communication.Disconnect();
3533 m_stdio_communication.StopReadThread();
3534 m_stdin_forward = false;
3535
3536 if (m_process_input_reader) {
3537 m_process_input_reader->SetIsDone(true);
3538 m_process_input_reader->Cancel();
3539 m_process_input_reader.reset();
3540 }
3541
3542 // If we exited when we were waiting for a process to stop, then
3543 // forward the event here so we don't lose the event
3544 if (exit_event_sp) {
3545 // Directly broadcast our exited event because we shut down our
3546 // private state thread above
3547 BroadcastEvent(exit_event_sp);
3548 }
3549
3550 // If we have been interrupted (to kill us) in the middle of running, we may
3551 // not end up propagating
3552 // the last events through the event system, in which case we might strand
3553 // the write lock. Unlock
3554 // it here so when we do to tear down the process we don't get an error
3555 // destroying the lock.
3556 m_public_run_lock.SetStopped();
3557 }
3558
3559 m_destroy_in_process = false;
3560
3561 return error;
3562}
3563
3564Error Process::Signal(int signal) {
3565 Error error(WillSignal());
3566 if (error.Success()) {
3567 error = DoSignal(signal);
3568 if (error.Success())
3569 DidSignal();
3570 }
3571 return error;
3572}
3573
3574void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3575 assert(signals_sp && "null signals_sp");
3576 m_unix_signals_sp = signals_sp;
3577}
3578
3579const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3580 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3581 return m_unix_signals_sp;
3582}
3583
3584lldb::ByteOrder Process::GetByteOrder() const {
3585 return GetTarget().GetArchitecture().GetByteOrder();
3586}
3587
3588uint32_t Process::GetAddressByteSize() const {
3589 return GetTarget().GetArchitecture().GetAddressByteSize();
3590}
3591
3592bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3593 const StateType state =
3594 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3595 bool return_value = true;
3596 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3597 LIBLLDB_LOG_PROCESS));
3598
3599 switch (state) {
3600 case eStateDetached:
3601 case eStateExited:
3602 case eStateUnloaded:
3603 m_stdio_communication.SynchronizeWithReadThread();
3604 m_stdio_communication.Disconnect();
3605 m_stdio_communication.StopReadThread();
3606 m_stdin_forward = false;
3607
3608 LLVM_FALLTHROUGH;
3609 case eStateConnected:
3610 case eStateAttaching:
3611 case eStateLaunching:
3612 // These events indicate changes in the state of the debugging session,
3613 // always report them.
3614 return_value = true;
3615 break;
3616 case eStateInvalid:
3617 // We stopped for no apparent reason, don't report it.
3618 return_value = false;
3619 break;
3620 case eStateRunning:
3621 case eStateStepping:
3622 // If we've started the target running, we handle the cases where we
3623 // are already running and where there is a transition from stopped to
3624 // running differently.
3625 // running -> running: Automatically suppress extra running events
3626 // stopped -> running: Report except when there is one or more no votes
3627 // and no yes votes.
3628 SynchronouslyNotifyStateChanged(state);
3629 if (m_force_next_event_delivery)
3630 return_value = true;
3631 else {
3632 switch (m_last_broadcast_state) {
3633 case eStateRunning:
3634 case eStateStepping:
3635 // We always suppress multiple runnings with no PUBLIC stop in between.
3636 return_value = false;
3637 break;
3638 default:
3639 // TODO: make this work correctly. For now always report
3640 // run if we aren't running so we don't miss any running
3641 // events. If I run the lldb/test/thread/a.out file and
3642 // break at main.cpp:58, run and hit the breakpoints on
3643 // multiple threads, then somehow during the stepping over
3644 // of all breakpoints no run gets reported.
3645
3646 // This is a transition from stop to run.
3647 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3648 case eVoteYes:
3649 case eVoteNoOpinion:
3650 return_value = true;
3651 break;
3652 case eVoteNo:
3653 return_value = false;
3654 break;
3655 }
3656 break;
3657 }
3658 }
3659 break;
3660 case eStateStopped:
3661 case eStateCrashed:
3662 case eStateSuspended:
3663 // We've stopped. First see if we're going to restart the target.
3664 // If we are going to stop, then we always broadcast the event.
3665 // If we aren't going to stop, let the thread plans decide if we're going to
3666 // report this event.
3667 // If no thread has an opinion, we don't report it.
3668
3669 m_stdio_communication.SynchronizeWithReadThread();
3670 RefreshStateAfterStop();
3671 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3672 if (log)
3673 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3674 "interrupt, state: %s",
3675 static_cast<void *>(event_ptr), StateAsCString(state));
3676 // Even though we know we are going to stop, we should let the threads
3677 // have a look at the stop,
3678 // so they can properly set their state.
3679 m_thread_list.ShouldStop(event_ptr);
3680 return_value = true;
3681 } else {
3682 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3683 bool should_resume = false;
3684
3685 // It makes no sense to ask "ShouldStop" if we've already been
3686 // restarted...
3687 // Asking the thread list is also not likely to go well, since we are
3688 // running again.
3689 // So in that case just report the event.
3690
3691 if (!was_restarted)
3692 should_resume = !m_thread_list.ShouldStop(event_ptr);
3693
3694 if (was_restarted || should_resume || m_resume_requested) {
3695 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3696 if (log)
3697 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3698 "%s was_restarted: %i stop_vote: %d.",
3699 should_resume, StateAsCString(state), was_restarted,
3700 stop_vote);
3701
3702 switch (stop_vote) {
3703 case eVoteYes:
3704 return_value = true;
3705 break;
3706 case eVoteNoOpinion:
3707 case eVoteNo:
3708 return_value = false;
3709 break;
3710 }
3711
3712 if (!was_restarted) {
3713 if (log)
3714 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3715 "from state: %s",
3716 static_cast<void *>(event_ptr), StateAsCString(state));
3717 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3718 PrivateResume();
3719 }
3720 } else {
3721 return_value = true;
3722 SynchronouslyNotifyStateChanged(state);
3723 }
3724 }
3725 break;
3726 }
3727
3728 // Forcing the next event delivery is a one shot deal. So reset it here.
3729 m_force_next_event_delivery = false;
3730
3731 // We do some coalescing of events (for instance two consecutive running
3732 // events get coalesced.)
3733 // But we only coalesce against events we actually broadcast. So we use
3734 // m_last_broadcast_state
3735 // to track that. NB - you can't use "m_public_state.GetValue()" for that
3736 // purpose, as was originally done,
3737 // because the PublicState reflects the last event pulled off the queue, and
3738 // there may be several
3739 // events stacked up on the queue unserviced. So the PublicState may not
3740 // reflect the last broadcasted event
3741 // yet. m_last_broadcast_state gets updated here.
3742
3743 if (return_value)
3744 m_last_broadcast_state = state;
3745
3746 if (log)
3747 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3748 "broadcast state: %s - %s",
3749 static_cast<void *>(event_ptr), StateAsCString(state),
3750 StateAsCString(m_last_broadcast_state),
3751 return_value ? "YES" : "NO");
3752 return return_value;
3753}
3754
3755bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3756 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3757
3758 bool already_running = PrivateStateThreadIsValid();
3759 if (log)
3760 log->Printf("Process::%s()%s ", __FUNCTION__,
3761 already_running ? " already running"
3762 : " starting private state thread");
3763
3764 if (!is_secondary_thread && already_running)
3765 return true;
3766
3767 // Create a thread that watches our internal state and controls which
3768 // events make it to clients (into the DCProcess event queue).
3769 char thread_name[1024];
3770
3771 if (HostInfo::GetMaxThreadNameLength() <= 30) {
3772 // On platforms with abbreviated thread name lengths, choose thread names
3773 // that fit within the limit.
3774 if (already_running)
3775 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3776 else
3777 snprintf(thread_name, sizeof(thread_name), "intern-state");
3778 } else {
3779 if (already_running)
3780 snprintf(thread_name, sizeof(thread_name),
3781 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3782 GetID());
3783 else
3784 snprintf(thread_name, sizeof(thread_name),
3785 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3786 }
3787
3788 // Create the private state thread, and start it running.
3789 PrivateStateThreadArgs *args_ptr =
3790 new PrivateStateThreadArgs(this, is_secondary_thread);
3791 m_private_state_thread =
3792 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3793 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3794 if (m_private_state_thread.IsJoinable()) {
3795 ResumePrivateStateThread();
3796 return true;
3797 } else
3798 return false;
3799}
3800
3801void Process::PausePrivateStateThread() {
3802 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3803}
3804
3805void Process::ResumePrivateStateThread() {
3806 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3807}
3808
3809void Process::StopPrivateStateThread() {
3810 if (m_private_state_thread.IsJoinable())
3811 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3812 else {
3813 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3814 if (log)
3815 log->Printf(
3816 "Went to stop the private state thread, but it was already invalid.");
3817 }
3818}
3819
3820void Process::ControlPrivateStateThread(uint32_t signal) {
3821 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3822
3823 assert(signal == eBroadcastInternalStateControlStop ||
3824 signal == eBroadcastInternalStateControlPause ||
3825 signal == eBroadcastInternalStateControlResume);
3826
3827 if (log)
3828 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3829
3830 // Signal the private state thread
3831 if (m_private_state_thread.IsJoinable()) {
3832 // Broadcast the event.
3833 // It is important to do this outside of the if below, because
3834 // it's possible that the thread state is invalid but that the
3835 // thread is waiting on a control event instead of simply being
3836 // on its way out (this should not happen, but it apparently can).
3837 if (log)
3838 log->Printf("Sending control event of type: %d.", signal);
3839 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3840 m_private_state_control_broadcaster.BroadcastEvent(signal,
3841 event_receipt_sp);
3842
3843 // Wait for the event receipt or for the private state thread to exit
3844 bool receipt_received = false;
3845 if (PrivateStateThreadIsValid()) {
3846 while (!receipt_received) {
3847 bool timed_out = false;
3848 // Check for a receipt for 2 seconds and then check if the private state
3849 // thread is still around.
3850 receipt_received = event_receipt_sp->WaitForEventReceived(
3851 std::chrono::seconds(2), &timed_out);
3852 if (!receipt_received) {
3853 // Check if the private state thread is still around. If it isn't then
3854 // we are done waiting
3855 if (!PrivateStateThreadIsValid())
3856 break; // Private state thread exited or is exiting, we are done
3857 }
3858 }
3859 }
3860
3861 if (signal == eBroadcastInternalStateControlStop) {
3862 thread_result_t result = NULL;
3863 m_private_state_thread.Join(&result);
3864 m_private_state_thread.Reset();
3865 }
3866 } else {
3867 if (log)
3868 log->Printf(
3869 "Private state thread already dead, no need to signal it to stop.");
3870 }
3871}
3872
3873void Process::SendAsyncInterrupt() {
3874 if (PrivateStateThreadIsValid())
3875 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3876 nullptr);
3877 else
3878 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3879}
3880
3881void Process::HandlePrivateEvent(EventSP &event_sp) {
3882 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3883 m_resume_requested = false;
3884
3885 const StateType new_state =
3886 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3887
3888 // First check to see if anybody wants a shot at this event:
3889 if (m_next_event_action_ap) {
3890 NextEventAction::EventActionResult action_result =
3891 m_next_event_action_ap->PerformAction(event_sp);
3892 if (log)
3893 log->Printf("Ran next event action, result was %d.", action_result);
3894
3895 switch (action_result) {
3896 case NextEventAction::eEventActionSuccess:
3897 SetNextEventAction(nullptr);
3898 break;
3899
3900 case NextEventAction::eEventActionRetry:
3901 break;
3902
3903 case NextEventAction::eEventActionExit:
3904 // Handle Exiting Here. If we already got an exited event,
3905 // we should just propagate it. Otherwise, swallow this event,
3906 // and set our state to exit so the next event will kill us.
3907 if (new_state != eStateExited) {
3908 // FIXME: should cons up an exited event, and discard this one.
3909 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3910 SetNextEventAction(nullptr);
3911 return;
3912 }
3913 SetNextEventAction(nullptr);
3914 break;
3915 }
3916 }
3917
3918 // See if we should broadcast this state to external clients?
3919 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3920
3921 if (should_broadcast) {
3922 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3923 if (log) {
3924 log->Printf("Process::%s (pid = %" PRIu64
3925 ") broadcasting new state %s (old state %s) to %s",
3926 __FUNCTION__, GetID(), StateAsCString(new_state),
3927 StateAsCString(GetState()),
3928 is_hijacked ? "hijacked" : "public");
3929 }
3930 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3931 if (StateIsRunningState(new_state)) {
3932 // Only push the input handler if we aren't fowarding events,
3933 // as this means the curses GUI is in use...
3934 // Or don't push it if we are launching since it will come up stopped.
3935 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3936 new_state != eStateLaunching && new_state != eStateAttaching) {
3937 PushProcessIOHandler();
3938 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3939 eBroadcastAlways);
3940 if (log)
3941 log->Printf("Process::%s updated m_iohandler_sync to %d",
3942 __FUNCTION__, m_iohandler_sync.GetValue());
3943 }
3944 } else if (StateIsStoppedState(new_state, false)) {
3945 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3946 // If the lldb_private::Debugger is handling the events, we don't
3947 // want to pop the process IOHandler here, we want to do it when
3948 // we receive the stopped event so we can carefully control when
3949 // the process IOHandler is popped because when we stop we want to
3950 // display some text stating how and why we stopped, then maybe some
3951 // process/thread/frame info, and then we want the "(lldb) " prompt
3952 // to show up. If we pop the process IOHandler here, then we will
3953 // cause the command interpreter to become the top IOHandler after
3954 // the process pops off and it will update its prompt right away...
3955 // See the Debugger.cpp file where it calls the function as
3956 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3957 // Otherwise we end up getting overlapping "(lldb) " prompts and
3958 // garbled output.
3959 //
3960 // If we aren't handling the events in the debugger (which is indicated
3961 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3962 // are hijacked, then we always pop the process IO handler manually.
3963 // Hijacking happens when the internal process state thread is running
3964 // thread plans, or when commands want to run in synchronous mode
3965 // and they call "process->WaitForProcessToStop()". An example of
3966 // something
3967 // that will hijack the events is a simple expression:
3968 //
3969 // (lldb) expr (int)puts("hello")
3970 //
3971 // This will cause the internal process state thread to resume and halt
3972 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3973 // events) and we do need the IO handler to be pushed and popped
3974 // correctly.
3975
3976 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3977 PopProcessIOHandler();
3978 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003979 }
3980
3981 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003982 } else {
3983 if (log) {
3984 log->Printf(
3985 "Process::%s (pid = %" PRIu64
3986 ") suppressing state %s (old state %s): should_broadcast == false",
3987 __FUNCTION__, GetID(), StateAsCString(new_state),
3988 StateAsCString(GetState()));
3989 }
3990 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003991}
3992
Kate Stoneb9c1b512016-09-06 20:57:50 +00003993Error Process::HaltPrivate() {
3994 EventSP event_sp;
3995 Error error(WillHalt());
3996 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003997 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003998
3999 // Ask the process subclass to actually halt our process
4000 bool caused_stop;
4001 error = DoHalt(caused_stop);
4002
4003 DidHalt();
4004 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004005}
4006
Kate Stoneb9c1b512016-09-06 20:57:50 +00004007thread_result_t Process::PrivateStateThread(void *arg) {
4008 std::unique_ptr<PrivateStateThreadArgs> args_up(
4009 static_cast<PrivateStateThreadArgs *>(arg));
4010 thread_result_t result =
4011 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
4012 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004013}
4014
Kate Stoneb9c1b512016-09-06 20:57:50 +00004015thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
4016 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00004017
Kate Stoneb9c1b512016-09-06 20:57:50 +00004018 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4019 if (log)
4020 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4021 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00004022
Kate Stoneb9c1b512016-09-06 20:57:50 +00004023 bool exit_now = false;
4024 bool interrupt_requested = false;
4025 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00004026 EventSP event_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004027 WaitForEventsPrivate(std::chrono::microseconds(0), event_sp, control_only);
4028 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4029 if (log)
4030 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4031 ") got a control event: %d",
4032 __FUNCTION__, static_cast<void *>(this), GetID(),
4033 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00004034
Kate Stoneb9c1b512016-09-06 20:57:50 +00004035 switch (event_sp->GetType()) {
4036 case eBroadcastInternalStateControlStop:
4037 exit_now = true;
4038 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00004039
Kate Stoneb9c1b512016-09-06 20:57:50 +00004040 case eBroadcastInternalStateControlPause:
4041 control_only = true;
4042 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004043
Kate Stoneb9c1b512016-09-06 20:57:50 +00004044 case eBroadcastInternalStateControlResume:
4045 control_only = false;
4046 break;
4047 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004048
Kate Stoneb9c1b512016-09-06 20:57:50 +00004049 continue;
4050 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4051 if (m_public_state.GetValue() == eStateAttaching) {
4052 if (log)
4053 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4054 ") woke up with an interrupt while attaching - "
4055 "forwarding interrupt.",
4056 __FUNCTION__, static_cast<void *>(this), GetID());
4057 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4058 } else if (StateIsRunningState(m_last_broadcast_state)) {
4059 if (log)
4060 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4061 ") woke up with an interrupt - Halting.",
4062 __FUNCTION__, static_cast<void *>(this), GetID());
4063 Error error = HaltPrivate();
4064 if (error.Fail() && log)
4065 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4066 ") failed to halt the process: %s",
4067 __FUNCTION__, static_cast<void *>(this), GetID(),
4068 error.AsCString());
4069 // Halt should generate a stopped event. Make a note of the fact that we
4070 // were
4071 // doing the interrupt, so we can set the interrupted flag after we
4072 // receive the
4073 // event. We deliberately set this to true even if HaltPrivate failed,
4074 // so that we
4075 // can interrupt on the next natural stop.
4076 interrupt_requested = true;
4077 } else {
4078 // This can happen when someone (e.g. Process::Halt) sees that we are
4079 // running and
4080 // sends an interrupt request, but the process actually stops before we
4081 // receive
4082 // it. In that case, we can just ignore the request. We use
4083 // m_last_broadcast_state, because the Stopped event may not have been
4084 // popped of
4085 // the event queue yet, which is when the public state gets updated.
4086 if (log)
4087 log->Printf(
4088 "Process::%s ignoring interrupt as we have already stopped.",
4089 __FUNCTION__);
4090 }
4091 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004092 }
4093
Kate Stoneb9c1b512016-09-06 20:57:50 +00004094 const StateType internal_state =
4095 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004096
Kate Stoneb9c1b512016-09-06 20:57:50 +00004097 if (internal_state != eStateInvalid) {
4098 if (m_clear_thread_plans_on_stop &&
4099 StateIsStoppedState(internal_state, true)) {
4100 m_clear_thread_plans_on_stop = false;
4101 m_thread_list.DiscardThreadPlans();
4102 }
4103
4104 if (interrupt_requested) {
4105 if (StateIsStoppedState(internal_state, true)) {
4106 // We requested the interrupt, so mark this as such in the stop event
4107 // so
4108 // clients can tell an interrupted process from a natural stop
4109 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4110 interrupt_requested = false;
4111 } else if (log) {
4112 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4113 "state '%s' received.",
4114 __FUNCTION__, StateAsCString(internal_state));
4115 }
4116 }
4117
4118 HandlePrivateEvent(event_sp);
4119 }
4120
4121 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4122 internal_state == eStateDetached) {
4123 if (log)
4124 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4125 ") about to exit with internal state %s...",
4126 __FUNCTION__, static_cast<void *>(this), GetID(),
4127 StateAsCString(internal_state));
4128
4129 break;
4130 }
4131 }
4132
4133 // Verify log is still enabled before attempting to write to it...
4134 if (log)
4135 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4136 __FUNCTION__, static_cast<void *>(this), GetID());
4137
4138 // If we are a secondary thread, then the primary thread we are working for
4139 // will have already
4140 // acquired the public_run_lock, and isn't done with what it was doing yet, so
4141 // don't
4142 // try to change it on the way out.
4143 if (!is_secondary_thread)
4144 m_public_run_lock.SetStopped();
4145 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004146}
4147
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004148//------------------------------------------------------------------
4149// Process Event Data
4150//------------------------------------------------------------------
4151
Kate Stoneb9c1b512016-09-06 20:57:50 +00004152Process::ProcessEventData::ProcessEventData()
4153 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4154 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004155
Kate Stoneb9c1b512016-09-06 20:57:50 +00004156Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4157 StateType state)
4158 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4159 m_update_state(0), m_interrupted(false) {
4160 if (process_sp)
4161 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004162}
4163
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004164Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004165
Kate Stoneb9c1b512016-09-06 20:57:50 +00004166const ConstString &Process::ProcessEventData::GetFlavorString() {
4167 static ConstString g_flavor("Process::ProcessEventData");
4168 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004169}
4170
Kate Stoneb9c1b512016-09-06 20:57:50 +00004171const ConstString &Process::ProcessEventData::GetFlavor() const {
4172 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004173}
4174
Kate Stoneb9c1b512016-09-06 20:57:50 +00004175void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4176 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004177
Kate Stoneb9c1b512016-09-06 20:57:50 +00004178 if (!process_sp)
4179 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004180
Kate Stoneb9c1b512016-09-06 20:57:50 +00004181 // This function gets called twice for each event, once when the event gets
4182 // pulled
4183 // off of the private process event queue, and then any number of times, first
4184 // when it gets pulled off of
4185 // the public event queue, then other times when we're pretending that this is
4186 // where we stopped at the
4187 // end of expression evaluation. m_update_state is used to distinguish these
4188 // three cases; it is 0 when we're just pulling it off for private handling,
4189 // and > 1 for expression evaluation, and we don't want to do the breakpoint
4190 // command handling then.
4191 if (m_update_state != 1)
4192 return;
4193
4194 process_sp->SetPublicState(
4195 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4196
4197 // If this is a halt event, even if the halt stopped with some reason other
4198 // than a plain interrupt (e.g. we had
4199 // already stopped for a breakpoint when the halt request came through) don't
4200 // do the StopInfo actions, as they may
4201 // end up restarting the process.
4202 if (m_interrupted)
4203 return;
4204
4205 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4206 if (m_state == eStateStopped && !m_restarted) {
4207 // Let process subclasses know we are about to do a public stop and
4208 // do anything they might need to in order to speed up register and
4209 // memory accesses.
4210 process_sp->WillPublicStop();
4211
4212 ThreadList &curr_thread_list = process_sp->GetThreadList();
4213 uint32_t num_threads = curr_thread_list.GetSize();
4214 uint32_t idx;
4215
4216 // The actions might change one of the thread's stop_info's opinions about
4217 // whether we should
4218 // stop the process, so we need to query that as we go.
4219
4220 // One other complication here, is that we try to catch any case where the
4221 // target has run (except for expressions)
4222 // and immediately exit, but if we get that wrong (which is possible) then
4223 // the thread list might have changed, and
4224 // that would cause our iteration here to crash. We could make a copy of
4225 // the thread list, but we'd really like
4226 // to also know if it has changed at all, so we make up a vector of the
4227 // thread ID's and check what we get back
4228 // against this list & bag out if anything differs.
4229 std::vector<uint32_t> thread_index_array(num_threads);
4230 for (idx = 0; idx < num_threads; ++idx)
4231 thread_index_array[idx] =
4232 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4233
4234 // Use this to track whether we should continue from here. We will only
4235 // continue the target running if
4236 // no thread says we should stop. Of course if some thread's PerformAction
4237 // actually sets the target running,
4238 // then it doesn't matter what the other threads say...
4239
4240 bool still_should_stop = false;
4241
4242 // Sometimes - for instance if we have a bug in the stub we are talking to,
4243 // we stop but no thread has a
4244 // valid stop reason. In that case we should just stop, because we have no
4245 // way of telling what the right
4246 // thing to do is, and it's better to let the user decide than continue
4247 // behind their backs.
4248
4249 bool does_anybody_have_an_opinion = false;
4250
4251 for (idx = 0; idx < num_threads; ++idx) {
4252 curr_thread_list = process_sp->GetThreadList();
4253 if (curr_thread_list.GetSize() != num_threads) {
4254 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4255 LIBLLDB_LOG_PROCESS));
4256 if (log)
4257 log->Printf(
4258 "Number of threads changed from %u to %u while processing event.",
4259 num_threads, curr_thread_list.GetSize());
4260 break;
4261 }
4262
4263 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4264
4265 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4266 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4267 LIBLLDB_LOG_PROCESS));
4268 if (log)
4269 log->Printf("The thread at position %u changed from %u to %u while "
4270 "processing event.",
4271 idx, thread_index_array[idx], thread_sp->GetIndexID());
4272 break;
4273 }
4274
4275 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4276 if (stop_info_sp && stop_info_sp->IsValid()) {
4277 does_anybody_have_an_opinion = true;
4278 bool this_thread_wants_to_stop;
4279 if (stop_info_sp->GetOverrideShouldStop()) {
4280 this_thread_wants_to_stop =
4281 stop_info_sp->GetOverriddenShouldStopValue();
4282 } else {
4283 stop_info_sp->PerformAction(event_ptr);
4284 // The stop action might restart the target. If it does, then we want
4285 // to mark that in the
4286 // event so that whoever is receiving it will know to wait for the
4287 // running event and reflect
4288 // that state appropriately.
4289 // We also need to stop processing actions, since they aren't
4290 // expecting the target to be running.
4291
4292 // FIXME: we might have run.
4293 if (stop_info_sp->HasTargetRunSinceMe()) {
4294 SetRestarted(true);
4295 break;
4296 }
4297
4298 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004299 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004300
4301 if (!still_should_stop)
4302 still_should_stop = this_thread_wants_to_stop;
4303 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004304 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004305
4306 if (!GetRestarted()) {
4307 if (!still_should_stop && does_anybody_have_an_opinion) {
4308 // We've been asked to continue, so do that here.
4309 SetRestarted(true);
4310 // Use the public resume method here, since this is just
4311 // extending a public resume.
4312 process_sp->PrivateResume();
4313 } else {
4314 // If we didn't restart, run the Stop Hooks here:
4315 // They might also restart the target, so watch for that.
4316 process_sp->GetTarget().RunStopHooks();
4317 if (process_sp->GetPrivateState() == eStateRunning)
4318 SetRestarted(true);
4319 }
4320 }
4321 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004322}
4323
Kate Stoneb9c1b512016-09-06 20:57:50 +00004324void Process::ProcessEventData::Dump(Stream *s) const {
4325 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004326
Kate Stoneb9c1b512016-09-06 20:57:50 +00004327 if (process_sp)
4328 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4329 static_cast<void *>(process_sp.get()), process_sp->GetID());
4330 else
4331 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004332
Kate Stoneb9c1b512016-09-06 20:57:50 +00004333 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004334}
4335
4336const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004337Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4338 if (event_ptr) {
4339 const EventData *event_data = event_ptr->GetData();
4340 if (event_data &&
4341 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4342 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4343 }
4344 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004345}
4346
4347ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004348Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4349 ProcessSP process_sp;
4350 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4351 if (data)
4352 process_sp = data->GetProcessSP();
4353 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004354}
4355
Kate Stoneb9c1b512016-09-06 20:57:50 +00004356StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4357 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4358 if (data == nullptr)
4359 return eStateInvalid;
4360 else
4361 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004362}
4363
Kate Stoneb9c1b512016-09-06 20:57:50 +00004364bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4365 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4366 if (data == nullptr)
4367 return false;
4368 else
4369 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004370}
4371
Kate Stoneb9c1b512016-09-06 20:57:50 +00004372void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4373 bool new_value) {
4374 ProcessEventData *data =
4375 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4376 if (data != nullptr)
4377 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004378}
4379
Jim Ingham0161b492013-02-09 01:29:05 +00004380size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004381Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4382 ProcessEventData *data =
4383 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4384 if (data != nullptr)
4385 return data->GetNumRestartedReasons();
4386 else
4387 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004388}
4389
4390const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004391Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4392 size_t idx) {
4393 ProcessEventData *data =
4394 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4395 if (data != nullptr)
4396 return data->GetRestartedReasonAtIndex(idx);
4397 else
4398 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004399}
4400
Kate Stoneb9c1b512016-09-06 20:57:50 +00004401void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4402 const char *reason) {
4403 ProcessEventData *data =
4404 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4405 if (data != nullptr)
4406 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004407}
4408
Kate Stoneb9c1b512016-09-06 20:57:50 +00004409bool Process::ProcessEventData::GetInterruptedFromEvent(
4410 const Event *event_ptr) {
4411 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4412 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004413 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004414 else
4415 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004416}
4417
Kate Stoneb9c1b512016-09-06 20:57:50 +00004418void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4419 bool new_value) {
4420 ProcessEventData *data =
4421 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4422 if (data != nullptr)
4423 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004424}
4425
Kate Stoneb9c1b512016-09-06 20:57:50 +00004426bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4427 ProcessEventData *data =
4428 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4429 if (data) {
4430 data->SetUpdateStateOnRemoval();
4431 return true;
4432 }
4433 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004434}
4435
Kate Stoneb9c1b512016-09-06 20:57:50 +00004436lldb::TargetSP Process::CalculateTarget() { return m_target_sp.lock(); }
4437
4438void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4439 exe_ctx.SetTargetPtr(&GetTarget());
4440 exe_ctx.SetProcessPtr(this);
4441 exe_ctx.SetThreadPtr(nullptr);
4442 exe_ctx.SetFramePtr(nullptr);
4443}
4444
4445// uint32_t
4446// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4447// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004448//{
4449// return 0;
4450//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004451//
4452// ArchSpec
4453// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004454//{
4455// return Host::GetArchSpecForExistingProcess (pid);
4456//}
4457//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004458// ArchSpec
4459// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004460//{
4461// return Host::GetArchSpecForExistingProcess (process_name);
4462//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004463
Kate Stoneb9c1b512016-09-06 20:57:50 +00004464void Process::AppendSTDOUT(const char *s, size_t len) {
4465 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4466 m_stdout_data.append(s, len);
4467 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4468 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004469}
4470
Kate Stoneb9c1b512016-09-06 20:57:50 +00004471void Process::AppendSTDERR(const char *s, size_t len) {
4472 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4473 m_stderr_data.append(s, len);
4474 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4475 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004476}
4477
Kate Stoneb9c1b512016-09-06 20:57:50 +00004478void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4479 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4480 m_profile_data.push_back(one_profile_data);
4481 BroadcastEventIfUnique(eBroadcastBitProfileData,
4482 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004483}
4484
Kate Stoneb9c1b512016-09-06 20:57:50 +00004485void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4486 const StructuredDataPluginSP &plugin_sp) {
4487 BroadcastEvent(
4488 eBroadcastBitStructuredData,
4489 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004490}
4491
4492StructuredDataPluginSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004493Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4494 auto find_it = m_structured_data_plugin_map.find(type_name);
4495 if (find_it != m_structured_data_plugin_map.end())
4496 return find_it->second;
4497 else
4498 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004499}
4500
Kate Stoneb9c1b512016-09-06 20:57:50 +00004501size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Error &error) {
4502 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4503 if (m_profile_data.empty())
4504 return 0;
4505
4506 std::string &one_profile_data = m_profile_data.front();
4507 size_t bytes_available = one_profile_data.size();
4508 if (bytes_available > 0) {
4509 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4510 if (log)
4511 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4512 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4513 if (bytes_available > buf_size) {
4514 memcpy(buf, one_profile_data.c_str(), buf_size);
4515 one_profile_data.erase(0, buf_size);
4516 bytes_available = buf_size;
4517 } else {
4518 memcpy(buf, one_profile_data.c_str(), bytes_available);
4519 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004520 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004521 }
4522 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004523}
4524
Greg Clayton93e86192011-11-13 04:45:22 +00004525//------------------------------------------------------------------
4526// Process STDIO
4527//------------------------------------------------------------------
4528
Kate Stoneb9c1b512016-09-06 20:57:50 +00004529size_t Process::GetSTDOUT(char *buf, size_t buf_size, Error &error) {
4530 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4531 size_t bytes_available = m_stdout_data.size();
4532 if (bytes_available > 0) {
4533 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4534 if (log)
4535 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4536 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4537 if (bytes_available > buf_size) {
4538 memcpy(buf, m_stdout_data.c_str(), buf_size);
4539 m_stdout_data.erase(0, buf_size);
4540 bytes_available = buf_size;
4541 } else {
4542 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4543 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004544 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004545 }
4546 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004547}
4548
Kate Stoneb9c1b512016-09-06 20:57:50 +00004549size_t Process::GetSTDERR(char *buf, size_t buf_size, Error &error) {
4550 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4551 size_t bytes_available = m_stderr_data.size();
4552 if (bytes_available > 0) {
4553 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4554 if (log)
4555 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4556 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4557 if (bytes_available > buf_size) {
4558 memcpy(buf, m_stderr_data.c_str(), buf_size);
4559 m_stderr_data.erase(0, buf_size);
4560 bytes_available = buf_size;
4561 } else {
4562 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4563 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004564 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004565 }
4566 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004567}
4568
Kate Stoneb9c1b512016-09-06 20:57:50 +00004569void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4570 size_t src_len) {
4571 Process *process = (Process *)baton;
4572 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004573}
4574
Kate Stoneb9c1b512016-09-06 20:57:50 +00004575class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004576public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004577 IOHandlerProcessSTDIO(Process *process, int write_fd)
4578 : IOHandler(process->GetTarget().GetDebugger(),
4579 IOHandler::Type::ProcessIO),
4580 m_process(process), m_read_file(), m_write_file(write_fd, false),
4581 m_pipe() {
4582 m_pipe.CreateNew(false);
4583 m_read_file.SetDescriptor(GetInputFD(), false);
4584 }
4585
4586 ~IOHandlerProcessSTDIO() override = default;
4587
4588 // Each IOHandler gets to run until it is done. It should read data
4589 // from the "in" and place output into "out" and "err and return
4590 // when done.
4591 void Run() override {
4592 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4593 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4594 SetIsDone(true);
4595 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004596 }
4597
Kate Stoneb9c1b512016-09-06 20:57:50 +00004598 SetIsDone(false);
4599 const int read_fd = m_read_file.GetDescriptor();
4600 TerminalState terminal_state;
4601 terminal_state.Save(read_fd, false);
4602 Terminal terminal(read_fd);
4603 terminal.SetCanonical(false);
4604 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004605// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004606#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004607 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4608 m_is_running = true;
4609 while (!GetIsDone()) {
4610 SelectHelper select_helper;
4611 select_helper.FDSetRead(read_fd);
4612 select_helper.FDSetRead(pipe_read_fd);
4613 Error error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004614
Kate Stoneb9c1b512016-09-06 20:57:50 +00004615 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004616 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004617 } else {
4618 char ch = 0;
4619 size_t n;
4620 if (select_helper.FDIsSetRead(read_fd)) {
4621 n = 1;
4622 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4623 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4624 SetIsDone(true);
4625 } else
4626 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004627 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004628 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4629 size_t bytes_read;
4630 // Consume the interrupt byte
4631 Error error = m_pipe.Read(&ch, 1, bytes_read);
4632 if (error.Success()) {
4633 switch (ch) {
4634 case 'q':
4635 SetIsDone(true);
4636 break;
4637 case 'i':
4638 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004639 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004640 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004641 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004642 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004643 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004644 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004645 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004646 m_is_running = false;
4647#endif
4648 terminal_state.Restore();
4649 }
4650
4651 void Cancel() override {
4652 SetIsDone(true);
4653 // Only write to our pipe to cancel if we are in
4654 // IOHandlerProcessSTDIO::Run().
4655 // We can end up with a python command that is being run from the command
4656 // interpreter:
4657 //
4658 // (lldb) step_process_thousands_of_times
4659 //
4660 // In this case the command interpreter will be in the middle of handling
4661 // the command and if the process pushes and pops the IOHandler thousands
4662 // of times, we can end up writing to m_pipe without ever consuming the
4663 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4664 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4665 if (m_is_running) {
4666 char ch = 'q'; // Send 'q' for quit
4667 size_t bytes_written = 0;
4668 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004669 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004670 }
4671
4672 bool Interrupt() override {
4673 // Do only things that are safe to do in an interrupt context (like in
4674 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4675 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4676 // that was written to the pipe and then call
4677 // m_process->SendAsyncInterrupt()
4678 // from a much safer location in code.
4679 if (m_active) {
4680 char ch = 'i'; // Send 'i' for interrupt
4681 size_t bytes_written = 0;
4682 Error result = m_pipe.Write(&ch, 1, bytes_written);
4683 return result.Success();
4684 } else {
4685 // This IOHandler might be pushed on the stack, but not being run
4686 // currently
4687 // so do the right thing if we aren't actively watching for STDIN by
4688 // sending
4689 // the interrupt to the process. Otherwise the write to the pipe above
4690 // would
4691 // do nothing. This can happen when the command interpreter is running and
4692 // gets a "expression ...". It will be on the IOHandler thread and sending
4693 // the input is complete to the delegate which will cause the expression
4694 // to
4695 // run, which will push the process IO handler, but not run it.
4696
4697 if (StateIsRunningState(m_process->GetState())) {
4698 m_process->SendAsyncInterrupt();
4699 return true;
4700 }
4701 }
4702 return false;
4703 }
4704
4705 void GotEOF() override {}
4706
Greg Clayton44d93782014-01-27 23:43:24 +00004707protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004708 Process *m_process;
4709 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4710 File m_write_file; // Write to this file (usually the master pty for getting
4711 // io to debuggee)
4712 Pipe m_pipe;
4713 std::atomic<bool> m_is_running;
Greg Clayton44d93782014-01-27 23:43:24 +00004714};
4715
Kate Stoneb9c1b512016-09-06 20:57:50 +00004716void Process::SetSTDIOFileDescriptor(int fd) {
4717 // First set up the Read Thread for reading/handling process I/O
4718
4719 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4720 new ConnectionFileDescriptor(fd, true));
4721
4722 if (conn_ap) {
4723 m_stdio_communication.SetConnection(conn_ap.release());
4724 if (m_stdio_communication.IsConnected()) {
4725 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4726 STDIOReadThreadBytesReceived, this);
4727 m_stdio_communication.StartReadThread();
4728
4729 // Now read thread is set up, set up input reader.
4730
4731 if (!m_process_input_reader)
4732 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004733 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004734 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004735}
4736
Kate Stoneb9c1b512016-09-06 20:57:50 +00004737bool Process::ProcessIOHandlerIsActive() {
4738 IOHandlerSP io_handler_sp(m_process_input_reader);
4739 if (io_handler_sp)
4740 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4741 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004742}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004743bool Process::PushProcessIOHandler() {
4744 IOHandlerSP io_handler_sp(m_process_input_reader);
4745 if (io_handler_sp) {
4746 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4747 if (log)
4748 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004749
Kate Stoneb9c1b512016-09-06 20:57:50 +00004750 io_handler_sp->SetIsDone(false);
4751 GetTarget().GetDebugger().PushIOHandler(io_handler_sp);
4752 return true;
4753 }
4754 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004755}
4756
Kate Stoneb9c1b512016-09-06 20:57:50 +00004757bool Process::PopProcessIOHandler() {
4758 IOHandlerSP io_handler_sp(m_process_input_reader);
4759 if (io_handler_sp)
4760 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4761 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004762}
4763
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004764// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004765void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004766
Kate Stoneb9c1b512016-09-06 20:57:50 +00004767void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004768
Kate Stoneb9c1b512016-09-06 20:57:50 +00004769namespace {
4770// RestorePlanState is used to record the "is private", "is master" and "okay to
4771// discard" fields of
4772// the plan we are running, and reset it on Clean or on destruction.
4773// It will only reset the state once, so you can call Clean and then monkey with
4774// the state and it
4775// won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004776
Kate Stoneb9c1b512016-09-06 20:57:50 +00004777class RestorePlanState {
4778public:
4779 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4780 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4781 if (m_thread_plan_sp) {
4782 m_private = m_thread_plan_sp->GetPrivate();
4783 m_is_master = m_thread_plan_sp->IsMasterPlan();
4784 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4785 }
4786 }
4787
4788 ~RestorePlanState() { Clean(); }
4789
4790 void Clean() {
4791 if (!m_already_reset && m_thread_plan_sp) {
4792 m_already_reset = true;
4793 m_thread_plan_sp->SetPrivate(m_private);
4794 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4795 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4796 }
4797 }
4798
4799private:
4800 lldb::ThreadPlanSP m_thread_plan_sp;
4801 bool m_already_reset;
4802 bool m_private;
4803 bool m_is_master;
4804 bool m_okay_to_discard;
4805};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004806} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004807
Jim Ingham1624a2d2014-05-05 02:26:40 +00004808ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004809Process::RunThreadPlan(ExecutionContext &exe_ctx,
4810 lldb::ThreadPlanSP &thread_plan_sp,
4811 const EvaluateExpressionOptions &options,
4812 DiagnosticManager &diagnostic_manager) {
4813 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004814
Kate Stoneb9c1b512016-09-06 20:57:50 +00004815 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4816
4817 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004818 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004819 eDiagnosticSeverityError,
4820 "RunThreadPlan called with empty thread plan.");
4821 return eExpressionSetupError;
4822 }
4823
4824 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004825 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004826 eDiagnosticSeverityError,
4827 "RunThreadPlan called with an invalid thread plan.");
4828 return eExpressionSetupError;
4829 }
4830
4831 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004832 diagnostic_manager.PutString(eDiagnosticSeverityError,
4833 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004834 return eExpressionSetupError;
4835 }
4836
4837 Thread *thread = exe_ctx.GetThreadPtr();
4838 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004839 diagnostic_manager.PutString(eDiagnosticSeverityError,
4840 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004841 return eExpressionSetupError;
4842 }
4843
4844 // We need to change some of the thread plan attributes for the thread plan
4845 // runner. This will restore them
4846 // when we are done:
4847
4848 RestorePlanState thread_plan_restorer(thread_plan_sp);
4849
4850 // We rely on the thread plan we are running returning "PlanCompleted" if when
4851 // it successfully completes.
4852 // For that to be true the plan can't be private - since private plans
4853 // suppress themselves in the
4854 // GetCompletedPlan call.
4855
4856 thread_plan_sp->SetPrivate(false);
4857
4858 // The plans run with RunThreadPlan also need to be terminal master plans or
4859 // when they are done we will end
4860 // up asking the plan above us whether we should stop, which may give the
4861 // wrong answer.
4862
4863 thread_plan_sp->SetIsMasterPlan(true);
4864 thread_plan_sp->SetOkayToDiscard(false);
4865
4866 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004867 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004868 eDiagnosticSeverityError,
4869 "RunThreadPlan called while the private state was not stopped.");
4870 return eExpressionSetupError;
4871 }
4872
4873 // Save the thread & frame from the exe_ctx for restoration after we run
4874 const uint32_t thread_idx_id = thread->GetIndexID();
4875 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4876 if (!selected_frame_sp) {
4877 thread->SetSelectedFrame(nullptr);
4878 selected_frame_sp = thread->GetSelectedFrame();
4879 if (!selected_frame_sp) {
4880 diagnostic_manager.Printf(
4881 eDiagnosticSeverityError,
4882 "RunThreadPlan called without a selected frame on thread %d",
4883 thread_idx_id);
4884 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004885 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004886 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004887
Kate Stoneb9c1b512016-09-06 20:57:50 +00004888 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004889
Kate Stoneb9c1b512016-09-06 20:57:50 +00004890 // N.B. Running the target may unset the currently selected thread and frame.
4891 // We don't want to do that either,
4892 // so we should arrange to reset them as well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004893
Kate Stoneb9c1b512016-09-06 20:57:50 +00004894 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004895
Kate Stoneb9c1b512016-09-06 20:57:50 +00004896 uint32_t selected_tid;
4897 StackID selected_stack_id;
4898 if (selected_thread_sp) {
4899 selected_tid = selected_thread_sp->GetIndexID();
4900 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4901 } else {
4902 selected_tid = LLDB_INVALID_THREAD_ID;
4903 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004904
Kate Stoneb9c1b512016-09-06 20:57:50 +00004905 HostThread backup_private_state_thread;
4906 lldb::StateType old_state = eStateInvalid;
4907 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004908
Kate Stoneb9c1b512016-09-06 20:57:50 +00004909 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4910 LIBLLDB_LOG_PROCESS));
4911 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4912 // Yikes, we are running on the private state thread! So we can't wait for
4913 // public events on this thread, since
4914 // we are the thread that is generating public events.
4915 // The simplest thing to do is to spin up a temporary thread to handle
4916 // private state thread events while
4917 // we are fielding public events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004918 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004919 log->Printf("Running thread plan on private state thread, spinning up "
4920 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004921
Kate Stoneb9c1b512016-09-06 20:57:50 +00004922 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004923
Kate Stoneb9c1b512016-09-06 20:57:50 +00004924 // One other bit of business: we want to run just this thread plan and
4925 // anything it pushes, and then stop,
4926 // returning control here.
4927 // But in the normal course of things, the plan above us on the stack would
4928 // be given a shot at the stop
4929 // event before deciding to stop, and we don't want that. So we insert a
4930 // "stopper" base plan on the stack
4931 // before the plan we want to run. Since base plans always stop and return
4932 // control to the user, that will
4933 // do just what we want.
4934 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4935 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4936 // Have to make sure our public state is stopped, since otherwise the
4937 // reporting logic below doesn't work correctly.
4938 old_state = m_public_state.GetValue();
4939 m_public_state.SetValueNoLock(eStateStopped);
4940
4941 // Now spin up the private state thread:
4942 StartPrivateStateThread(true);
4943 }
4944
4945 thread->QueueThreadPlan(
4946 thread_plan_sp, false); // This used to pass "true" does that make sense?
4947
4948 if (options.GetDebug()) {
4949 // In this case, we aren't actually going to run, we just want to stop right
4950 // away.
4951 // Flush this thread so we will refetch the stacks and show the correct
4952 // backtrace.
4953 // FIXME: To make this prettier we should invent some stop reason for this,
4954 // but that
4955 // is only cosmetic, and this functionality is only of use to lldb
4956 // developers who can
4957 // live with not pretty...
4958 thread->Flush();
4959 return eExpressionStoppedForDebug;
4960 }
4961
4962 ListenerSP listener_sp(
4963 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4964
4965 lldb::EventSP event_to_broadcast_sp;
4966
4967 {
4968 // This process event hijacker Hijacks the Public events and its destructor
4969 // makes sure that the process events get
4970 // restored on exit to the function.
4971 //
4972 // If the event needs to propagate beyond the hijacker (e.g., the process
4973 // exits during execution), then the event
4974 // is put into event_to_broadcast_sp for rebroadcasting.
4975
4976 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4977
4978 if (log) {
4979 StreamString s;
4980 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4981 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4982 " to run thread plan \"%s\".",
4983 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004984 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004985
4986 bool got_event;
4987 lldb::EventSP event_sp;
4988 lldb::StateType stop_state = lldb::eStateInvalid;
4989
4990 bool before_first_timeout = true; // This is set to false the first time
4991 // that we have to halt the target.
4992 bool do_resume = true;
4993 bool handle_running_event = true;
4994 const uint64_t default_one_thread_timeout_usec = 250000;
4995
4996 // This is just for accounting:
4997 uint32_t num_resumes = 0;
4998
4999 uint32_t timeout_usec = options.GetTimeoutUsec();
5000 uint32_t one_thread_timeout_usec;
5001 uint32_t all_threads_timeout_usec = 0;
5002
5003 // If we are going to run all threads the whole time, or if we are only
5004 // going to run one thread,
5005 // then we don't need the first timeout. So we set the final timeout, and
5006 // pretend we are after the
5007 // first timeout already.
5008
5009 if (!options.GetStopOthers() || !options.GetTryAllThreads()) {
5010 before_first_timeout = false;
5011 one_thread_timeout_usec = 0;
5012 all_threads_timeout_usec = timeout_usec;
5013 } else {
5014 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
5015
5016 // If the overall wait is forever, then we only need to set the one thread
5017 // timeout:
5018 if (timeout_usec == 0) {
5019 if (option_one_thread_timeout != 0)
5020 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005021 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005022 one_thread_timeout_usec = default_one_thread_timeout_usec;
5023 } else {
5024 // Otherwise, if the one thread timeout is set, make sure it isn't
5025 // longer than the overall timeout,
5026 // and use it, otherwise use half the total timeout, bounded by the
5027 // default_one_thread_timeout_usec.
5028 uint64_t computed_one_thread_timeout;
5029 if (option_one_thread_timeout != 0) {
5030 if (timeout_usec < option_one_thread_timeout) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00005031 diagnostic_manager.PutString(eDiagnosticSeverityError,
5032 "RunThreadPlan called without one "
5033 "thread timeout greater than total "
5034 "timeout");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005035 return eExpressionSetupError;
5036 }
5037 computed_one_thread_timeout = option_one_thread_timeout;
5038 } else {
5039 computed_one_thread_timeout = timeout_usec / 2;
5040 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5041 computed_one_thread_timeout = default_one_thread_timeout_usec;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005042 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005043 one_thread_timeout_usec = computed_one_thread_timeout;
5044 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5045 }
Kuba Breckaafdf8422014-10-10 23:43:03 +00005046 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005047
Kate Stoneb9c1b512016-09-06 20:57:50 +00005048 if (log)
5049 log->Printf(
5050 "Stop others: %u, try all: %u, before_first: %u, one thread: %" PRIu32
5051 " - all threads: %" PRIu32 ".\n",
5052 options.GetStopOthers(), options.GetTryAllThreads(),
5053 before_first_timeout, one_thread_timeout_usec,
5054 all_threads_timeout_usec);
5055
5056 // This isn't going to work if there are unfetched events on the queue.
5057 // Are there cases where we might want to run the remaining events here, and
5058 // then try to
5059 // call the function? That's probably being too tricky for our own good.
5060
5061 Event *other_events = listener_sp->PeekAtNextEvent();
5062 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00005063 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005064 eDiagnosticSeverityError,
5065 "RunThreadPlan called with pending events on the queue.");
5066 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00005067 }
5068
Kate Stoneb9c1b512016-09-06 20:57:50 +00005069 // We also need to make sure that the next event is delivered. We might be
5070 // calling a function as part of
5071 // a thread plan, in which case the last delivered event could be the
5072 // running event, and we don't want
5073 // event coalescing to cause us to lose OUR running event...
5074 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00005075
Kate Stoneb9c1b512016-09-06 20:57:50 +00005076// This while loop must exit out the bottom, there's cleanup that we need to do
5077// when we are done.
5078// So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00005079
Kate Stoneb9c1b512016-09-06 20:57:50 +00005080#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5081 // It's pretty much impossible to write test cases for things like:
5082 // One thread timeout expires, I go to halt, but the process already stopped
5083 // on the function call stop breakpoint. Turning on this define will make
5084 // us not
5085 // fetch the first event till after the halt. So if you run a quick
5086 // function, it will have
5087 // completed, and the completion event will be waiting, when you interrupt
5088 // for halt.
5089 // The expression evaluation should still succeed.
5090 bool miss_first_event = true;
5091#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00005092 std::chrono::microseconds timeout = std::chrono::microseconds(0);
Kuba Breckaa51ea382014-09-06 01:33:13 +00005093
Kate Stoneb9c1b512016-09-06 20:57:50 +00005094 while (true) {
5095 // We usually want to resume the process if we get to the top of the loop.
5096 // The only exception is if we get two running events with no intervening
5097 // stop, which can happen, we will just wait for then next stop event.
5098 if (log)
5099 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5100 "before_first_timeout: %i.",
5101 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00005102
Kate Stoneb9c1b512016-09-06 20:57:50 +00005103 if (do_resume || handle_running_event) {
5104 // Do the initial resume and wait for the running event before going
5105 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00005106
Kate Stoneb9c1b512016-09-06 20:57:50 +00005107 if (do_resume) {
5108 num_resumes++;
5109 Error resume_error = PrivateResume();
5110 if (!resume_error.Success()) {
5111 diagnostic_manager.Printf(
5112 eDiagnosticSeverityError,
5113 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5114 resume_error.AsCString());
5115 return_value = eExpressionSetupError;
5116 break;
5117 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005118 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005119
5120 got_event = listener_sp->WaitForEvent(std::chrono::microseconds(500000),
5121 event_sp);
5122 if (!got_event) {
5123 if (log)
5124 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5125 "resume %" PRIu32 ", exiting.",
5126 num_resumes);
5127
5128 diagnostic_manager.Printf(eDiagnosticSeverityError,
5129 "didn't get any event after resume %" PRIu32
5130 ", exiting.",
5131 num_resumes);
5132 return_value = eExpressionSetupError;
5133 break;
5134 }
5135
5136 stop_state =
5137 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5138
5139 if (stop_state != eStateRunning) {
5140 bool restarted = false;
5141
5142 if (stop_state == eStateStopped) {
5143 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5144 event_sp.get());
5145 if (log)
5146 log->Printf(
5147 "Process::RunThreadPlan(): didn't get running event after "
5148 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5149 "handle_running_event: %i).",
5150 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5151 handle_running_event);
5152 }
5153
5154 if (restarted) {
5155 // This is probably an overabundance of caution, I don't think I
5156 // should ever get a stopped & restarted
5157 // event here. But if I do, the best thing is to Halt and then get
5158 // out of here.
5159 const bool clear_thread_plans = false;
5160 const bool use_run_lock = false;
5161 Halt(clear_thread_plans, use_run_lock);
5162 }
5163
5164 diagnostic_manager.Printf(
5165 eDiagnosticSeverityError,
5166 "didn't get running event after initial resume, got %s instead.",
5167 StateAsCString(stop_state));
5168 return_value = eExpressionSetupError;
5169 break;
5170 }
5171
5172 if (log)
5173 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5174 // We need to call the function synchronously, so spin waiting for it to
5175 // return.
5176 // If we get interrupted while executing, we're going to lose our
5177 // context, and
5178 // won't be able to gather the result at this point.
5179 // We set the timeout AFTER the resume, since the resume takes some time
5180 // and we
5181 // don't want to charge that to the timeout.
5182 } else {
5183 if (log)
5184 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5185 }
5186
5187 if (before_first_timeout) {
5188 if (options.GetTryAllThreads())
5189 timeout = std::chrono::microseconds(one_thread_timeout_usec);
Jason Molendaef7d6412015-08-06 03:27:10 +00005190 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005191 timeout = std::chrono::microseconds(timeout_usec);
5192 } else {
5193 if (timeout_usec == 0)
5194 timeout = std::chrono::microseconds(0);
5195 else
5196 timeout = std::chrono::microseconds(all_threads_timeout_usec);
5197 }
5198
5199 do_resume = true;
5200 handle_running_event = true;
5201
5202 // Now wait for the process to stop again:
5203 event_sp.reset();
5204
5205 if (log) {
5206 if (timeout.count()) {
5207 log->Printf(
5208 "Process::RunThreadPlan(): about to wait - now is %llu - "
5209 "endpoint is %llu",
5210 static_cast<unsigned long long>(
5211 std::chrono::system_clock::now().time_since_epoch().count()),
5212 static_cast<unsigned long long>(
5213 std::chrono::time_point<std::chrono::system_clock,
5214 std::chrono::microseconds>(timeout)
5215 .time_since_epoch()
5216 .count()));
5217 } else {
5218 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005219 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005220 }
5221
5222#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5223 // See comment above...
5224 if (miss_first_event) {
5225 usleep(1000);
5226 miss_first_event = false;
5227 got_event = false;
5228 } else
5229#endif
5230 got_event = listener_sp->WaitForEvent(timeout, event_sp);
5231
5232 if (got_event) {
5233 if (event_sp) {
5234 bool keep_going = false;
5235 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5236 const bool clear_thread_plans = false;
5237 const bool use_run_lock = false;
5238 Halt(clear_thread_plans, use_run_lock);
5239 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005240 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5241 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005242 if (log)
5243 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5244 "eBroadcastBitInterrupted, exiting.");
5245 break;
5246 } else {
5247 stop_state =
5248 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5249 if (log)
5250 log->Printf(
5251 "Process::RunThreadPlan(): in while loop, got event: %s.",
5252 StateAsCString(stop_state));
5253
5254 switch (stop_state) {
5255 case lldb::eStateStopped: {
5256 // We stopped, figure out what we are going to do now.
5257 ThreadSP thread_sp =
5258 GetThreadList().FindThreadByIndexID(thread_idx_id);
5259 if (!thread_sp) {
5260 // Ooh, our thread has vanished. Unlikely that this was
5261 // successful execution...
5262 if (log)
5263 log->Printf("Process::RunThreadPlan(): execution completed "
5264 "but our thread (index-id=%u) has vanished.",
5265 thread_idx_id);
5266 return_value = eExpressionInterrupted;
5267 } else {
5268 // If we were restarted, we just need to go back up to fetch
5269 // another event.
5270 if (Process::ProcessEventData::GetRestartedFromEvent(
5271 event_sp.get())) {
5272 if (log) {
5273 log->Printf("Process::RunThreadPlan(): Got a stop and "
5274 "restart, so we'll continue waiting.");
5275 }
5276 keep_going = true;
5277 do_resume = false;
5278 handle_running_event = true;
5279 } else {
5280 StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
5281 StopReason stop_reason = eStopReasonInvalid;
5282 if (stop_info_sp)
5283 stop_reason = stop_info_sp->GetStopReason();
5284
5285 // FIXME: We only check if the stop reason is plan complete,
5286 // should we make sure that
5287 // it is OUR plan that is complete?
5288 if (stop_reason == eStopReasonPlanComplete) {
5289 if (log)
5290 log->PutCString("Process::RunThreadPlan(): execution "
5291 "completed successfully.");
5292
5293 // Restore the plan state so it will get reported as
5294 // intended when we are done.
5295 thread_plan_restorer.Clean();
5296
5297 return_value = eExpressionCompleted;
5298 } else {
5299 // Something restarted the target, so just wait for it to
5300 // stop for real.
5301 if (stop_reason == eStopReasonBreakpoint) {
5302 if (log)
5303 log->Printf("Process::RunThreadPlan() stopped for "
5304 "breakpoint: %s.",
5305 stop_info_sp->GetDescription());
5306 return_value = eExpressionHitBreakpoint;
5307 if (!options.DoesIgnoreBreakpoints()) {
5308 // Restore the plan state and then force Private to
5309 // false. We are
5310 // going to stop because of this plan so we need it to
5311 // become a public
5312 // plan or it won't report correctly when we continue to
5313 // its termination
5314 // later on.
5315 thread_plan_restorer.Clean();
5316 if (thread_plan_sp)
5317 thread_plan_sp->SetPrivate(false);
5318 event_to_broadcast_sp = event_sp;
5319 }
5320 } else {
5321 if (log)
5322 log->PutCString("Process::RunThreadPlan(): thread plan "
5323 "didn't successfully complete.");
5324 if (!options.DoesUnwindOnError())
5325 event_to_broadcast_sp = event_sp;
5326 return_value = eExpressionInterrupted;
5327 }
5328 }
5329 }
5330 }
5331 } break;
5332
5333 case lldb::eStateRunning:
5334 // This shouldn't really happen, but sometimes we do get two
5335 // running events without an
5336 // intervening stop, and in that case we should just go back to
5337 // waiting for the stop.
5338 do_resume = false;
5339 keep_going = true;
5340 handle_running_event = false;
5341 break;
5342
5343 default:
5344 if (log)
5345 log->Printf("Process::RunThreadPlan(): execution stopped with "
5346 "unexpected state: %s.",
5347 StateAsCString(stop_state));
5348
5349 if (stop_state == eStateExited)
5350 event_to_broadcast_sp = event_sp;
5351
Zachary Turnere2411fa2016-11-12 19:12:56 +00005352 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005353 eDiagnosticSeverityError,
5354 "execution stopped with unexpected state.");
5355 return_value = eExpressionInterrupted;
5356 break;
5357 }
5358 }
5359
5360 if (keep_going)
5361 continue;
5362 else
5363 break;
5364 } else {
5365 if (log)
5366 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5367 "the event pointer was null. How odd...");
5368 return_value = eExpressionInterrupted;
5369 break;
5370 }
5371 } else {
5372 // If we didn't get an event that means we've timed out...
5373 // We will interrupt the process here. Depending on what we were asked
5374 // to do we will
5375 // either exit, or try with all threads running for the same timeout.
5376
5377 if (log) {
5378 if (options.GetTryAllThreads()) {
5379 if (before_first_timeout) {
5380 if (timeout_usec != 0) {
5381 log->Printf("Process::RunThreadPlan(): Running function with "
5382 "one thread timeout timed out, "
5383 "running for %" PRIu32
5384 " usec with all threads enabled.",
5385 all_threads_timeout_usec);
5386 } else {
5387 log->Printf("Process::RunThreadPlan(): Running function with "
5388 "one thread timeout timed out, "
5389 "running forever with all threads enabled.");
5390 }
5391 } else
5392 log->Printf("Process::RunThreadPlan(): Restarting function with "
5393 "all threads enabled "
5394 "and timeout: %u timed out, abandoning execution.",
5395 timeout_usec);
5396 } else
5397 log->Printf("Process::RunThreadPlan(): Running function with "
5398 "timeout: %u timed out, "
5399 "abandoning execution.",
5400 timeout_usec);
5401 }
5402
5403 // It is possible that between the time we issued the Halt, and we get
5404 // around to calling Halt the target
5405 // could have stopped. That's fine, Halt will figure that out and send
5406 // the appropriate Stopped event.
5407 // BUT it is also possible that we stopped & restarted (e.g. hit a
5408 // signal with "stop" set to false.) In
5409 // that case, we'll get the stopped & restarted event, and we should go
5410 // back to waiting for the Halt's
5411 // stopped event. That's what this while loop does.
5412
5413 bool back_to_top = true;
5414 uint32_t try_halt_again = 0;
5415 bool do_halt = true;
5416 const uint32_t num_retries = 5;
5417 while (try_halt_again < num_retries) {
5418 Error halt_error;
5419 if (do_halt) {
5420 if (log)
5421 log->Printf("Process::RunThreadPlan(): Running Halt.");
5422 const bool clear_thread_plans = false;
5423 const bool use_run_lock = false;
5424 Halt(clear_thread_plans, use_run_lock);
5425 }
5426 if (halt_error.Success()) {
5427 if (log)
5428 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5429
5430 got_event = listener_sp->WaitForEvent(
5431 std::chrono::microseconds(500000), event_sp);
5432
5433 if (got_event) {
5434 stop_state =
5435 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5436 if (log) {
5437 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5438 StateAsCString(stop_state));
5439 if (stop_state == lldb::eStateStopped &&
5440 Process::ProcessEventData::GetInterruptedFromEvent(
5441 event_sp.get()))
5442 log->PutCString(" Event was the Halt interruption event.");
5443 }
5444
5445 if (stop_state == lldb::eStateStopped) {
5446 // Between the time we initiated the Halt and the time we
5447 // delivered it, the process could have
5448 // already finished its job. Check that here:
5449
5450 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5451 if (log)
5452 log->PutCString("Process::RunThreadPlan(): Even though we "
5453 "timed out, the call plan was done. "
5454 "Exiting wait loop.");
5455 return_value = eExpressionCompleted;
5456 back_to_top = false;
5457 break;
5458 }
5459
5460 if (Process::ProcessEventData::GetRestartedFromEvent(
5461 event_sp.get())) {
5462 if (log)
5463 log->PutCString("Process::RunThreadPlan(): Went to halt "
5464 "but got a restarted event, there must be "
5465 "an un-restarted stopped event so try "
5466 "again... "
5467 "Exiting wait loop.");
5468 try_halt_again++;
5469 do_halt = false;
5470 continue;
5471 }
5472
5473 if (!options.GetTryAllThreads()) {
5474 if (log)
5475 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5476 "was false, we stopped so now we're "
5477 "quitting.");
5478 return_value = eExpressionInterrupted;
5479 back_to_top = false;
5480 break;
5481 }
5482
5483 if (before_first_timeout) {
5484 // Set all the other threads to run, and return to the top of
5485 // the loop, which will continue;
5486 before_first_timeout = false;
5487 thread_plan_sp->SetStopOthers(false);
5488 if (log)
5489 log->PutCString(
5490 "Process::RunThreadPlan(): about to resume.");
5491
5492 back_to_top = true;
5493 break;
5494 } else {
5495 // Running all threads failed, so return Interrupted.
5496 if (log)
5497 log->PutCString("Process::RunThreadPlan(): running all "
5498 "threads timed out.");
5499 return_value = eExpressionInterrupted;
5500 back_to_top = false;
5501 break;
5502 }
5503 }
5504 } else {
5505 if (log)
5506 log->PutCString("Process::RunThreadPlan(): halt said it "
5507 "succeeded, but I got no event. "
5508 "I'm getting out of here passing Interrupted.");
5509 return_value = eExpressionInterrupted;
5510 back_to_top = false;
5511 break;
5512 }
5513 } else {
5514 try_halt_again++;
5515 continue;
5516 }
5517 }
5518
5519 if (!back_to_top || try_halt_again > num_retries)
5520 break;
5521 else
5522 continue;
5523 }
5524 } // END WAIT LOOP
5525
5526 // If we had to start up a temporary private state thread to run this thread
5527 // plan, shut it down now.
5528 if (backup_private_state_thread.IsJoinable()) {
5529 StopPrivateStateThread();
5530 Error error;
5531 m_private_state_thread = backup_private_state_thread;
5532 if (stopper_base_plan_sp) {
5533 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5534 }
5535 if (old_state != eStateInvalid)
5536 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005537 }
5538
Kate Stoneb9c1b512016-09-06 20:57:50 +00005539 if (return_value != eExpressionCompleted && log) {
5540 // Print a backtrace into the log so we can figure out where we are:
5541 StreamString s;
5542 s.PutCString("Thread state after unsuccessful completion: \n");
5543 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
5544 log->PutCString(s.GetData());
Jason Molendaef7d6412015-08-06 03:27:10 +00005545 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005546 // Restore the thread state if we are going to discard the plan execution.
5547 // There are three cases where this
5548 // could happen:
5549 // 1) The execution successfully completed
5550 // 2) We hit a breakpoint, and ignore_breakpoints was true
5551 // 3) We got some other error, and discard_on_error was true
5552 bool should_unwind = (return_value == eExpressionInterrupted &&
5553 options.DoesUnwindOnError()) ||
5554 (return_value == eExpressionHitBreakpoint &&
5555 options.DoesIgnoreBreakpoints());
5556
5557 if (return_value == eExpressionCompleted || should_unwind) {
5558 thread_plan_sp->RestoreThreadState();
5559 }
5560
5561 // Now do some processing on the results of the run:
5562 if (return_value == eExpressionInterrupted ||
5563 return_value == eExpressionHitBreakpoint) {
5564 if (log) {
5565 StreamString s;
5566 if (event_sp)
5567 event_sp->Dump(&s);
5568 else {
5569 log->PutCString("Process::RunThreadPlan(): Stop event that "
5570 "interrupted us is NULL.");
5571 }
5572
5573 StreamString ts;
5574
5575 const char *event_explanation = nullptr;
5576
5577 do {
5578 if (!event_sp) {
5579 event_explanation = "<no event>";
5580 break;
5581 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5582 event_explanation = "<user interrupt>";
5583 break;
5584 } else {
5585 const Process::ProcessEventData *event_data =
5586 Process::ProcessEventData::GetEventDataFromEvent(
5587 event_sp.get());
5588
5589 if (!event_data) {
5590 event_explanation = "<no event data>";
5591 break;
5592 }
5593
5594 Process *process = event_data->GetProcessSP().get();
5595
5596 if (!process) {
5597 event_explanation = "<no process>";
5598 break;
5599 }
5600
5601 ThreadList &thread_list = process->GetThreadList();
5602
5603 uint32_t num_threads = thread_list.GetSize();
5604 uint32_t thread_index;
5605
5606 ts.Printf("<%u threads> ", num_threads);
5607
5608 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5609 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5610
5611 if (!thread) {
5612 ts.Printf("<?> ");
5613 continue;
5614 }
5615
5616 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5617 RegisterContext *register_context =
5618 thread->GetRegisterContext().get();
5619
5620 if (register_context)
5621 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5622 else
5623 ts.Printf("[ip unknown] ");
5624
5625 // Show the private stop info here, the public stop info will be
5626 // from the last natural stop.
5627 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5628 if (stop_info_sp) {
5629 const char *stop_desc = stop_info_sp->GetDescription();
5630 if (stop_desc)
5631 ts.PutCString(stop_desc);
5632 }
5633 ts.Printf(">");
5634 }
5635
5636 event_explanation = ts.GetData();
5637 }
5638 } while (0);
5639
5640 if (event_explanation)
5641 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5642 s.GetData(), event_explanation);
5643 else
5644 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5645 s.GetData());
5646 }
5647
5648 if (should_unwind) {
5649 if (log)
5650 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5651 "discarding thread plans up to %p.",
5652 static_cast<void *>(thread_plan_sp.get()));
5653 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5654 } else {
5655 if (log)
5656 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5657 "plan: %p not discarding.",
5658 static_cast<void *>(thread_plan_sp.get()));
5659 }
5660 } else if (return_value == eExpressionSetupError) {
5661 if (log)
5662 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5663
5664 if (options.DoesUnwindOnError()) {
5665 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5666 }
5667 } else {
5668 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5669 if (log)
5670 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5671 return_value = eExpressionCompleted;
5672 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5673 if (log)
5674 log->PutCString(
5675 "Process::RunThreadPlan(): thread plan was discarded");
5676 return_value = eExpressionDiscarded;
5677 } else {
5678 if (log)
5679 log->PutCString(
5680 "Process::RunThreadPlan(): thread plan stopped in mid course");
5681 if (options.DoesUnwindOnError() && thread_plan_sp) {
5682 if (log)
5683 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5684 "'cause unwind_on_error is set.");
5685 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5686 }
5687 }
5688 }
5689
5690 // Thread we ran the function in may have gone away because we ran the
5691 // target
5692 // Check that it's still there, and if it is put it back in the context.
5693 // Also restore the
5694 // frame in the context if it is still present.
5695 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5696 if (thread) {
5697 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5698 }
5699
5700 // Also restore the current process'es selected frame & thread, since this
5701 // function calling may
5702 // be done behind the user's back.
5703
5704 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5705 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5706 selected_stack_id.IsValid()) {
5707 // We were able to restore the selected thread, now restore the frame:
5708 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5709 StackFrameSP old_frame_sp =
5710 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5711 selected_stack_id);
5712 if (old_frame_sp)
5713 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5714 old_frame_sp.get());
5715 }
5716 }
5717 }
5718
5719 // If the process exited during the run of the thread plan, notify everyone.
5720
5721 if (event_to_broadcast_sp) {
5722 if (log)
5723 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5724 BroadcastEvent(event_to_broadcast_sp);
5725 }
5726
5727 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005728}
5729
Kate Stoneb9c1b512016-09-06 20:57:50 +00005730const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5731 const char *result_name;
5732
5733 switch (result) {
5734 case eExpressionCompleted:
5735 result_name = "eExpressionCompleted";
5736 break;
5737 case eExpressionDiscarded:
5738 result_name = "eExpressionDiscarded";
5739 break;
5740 case eExpressionInterrupted:
5741 result_name = "eExpressionInterrupted";
5742 break;
5743 case eExpressionHitBreakpoint:
5744 result_name = "eExpressionHitBreakpoint";
5745 break;
5746 case eExpressionSetupError:
5747 result_name = "eExpressionSetupError";
5748 break;
5749 case eExpressionParseError:
5750 result_name = "eExpressionParseError";
5751 break;
5752 case eExpressionResultUnavailable:
5753 result_name = "eExpressionResultUnavailable";
5754 break;
5755 case eExpressionTimedOut:
5756 result_name = "eExpressionTimedOut";
5757 break;
5758 case eExpressionStoppedForDebug:
5759 result_name = "eExpressionStoppedForDebug";
5760 break;
5761 }
5762 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005763}
5764
Kate Stoneb9c1b512016-09-06 20:57:50 +00005765void Process::GetStatus(Stream &strm) {
5766 const StateType state = GetState();
5767 if (StateIsStoppedState(state, false)) {
5768 if (state == eStateExited) {
5769 int exit_status = GetExitStatus();
5770 const char *exit_description = GetExitDescription();
5771 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5772 GetID(), exit_status, exit_status,
5773 exit_description ? exit_description : "");
5774 } else {
5775 if (state == eStateConnected)
5776 strm.Printf("Connected to remote target.\n");
5777 else
5778 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5779 }
5780 } else {
5781 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5782 }
Pavel Labatha933d512016-04-05 13:07:16 +00005783}
5784
Kate Stoneb9c1b512016-09-06 20:57:50 +00005785size_t Process::GetThreadStatus(Stream &strm,
5786 bool only_threads_with_stop_reason,
5787 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005788 uint32_t num_frames_with_source,
5789 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005790 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005791
Kate Stoneb9c1b512016-09-06 20:57:50 +00005792 // You can't hold the thread list lock while calling Thread::GetStatus. That
5793 // very well might run code (e.g. if we need it
5794 // to get return values or arguments.) For that to work the process has to be
5795 // able to acquire it. So instead copy the thread
5796 // ID's, and look them up one by one:
5797
5798 uint32_t num_threads;
5799 std::vector<lldb::tid_t> thread_id_array;
5800 // Scope for thread list locker;
5801 {
5802 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5803 ThreadList &curr_thread_list = GetThreadList();
5804 num_threads = curr_thread_list.GetSize();
5805 uint32_t idx;
5806 thread_id_array.resize(num_threads);
5807 for (idx = 0; idx < num_threads; ++idx)
5808 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5809 }
5810
5811 for (uint32_t i = 0; i < num_threads; i++) {
5812 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5813 if (thread_sp) {
5814 if (only_threads_with_stop_reason) {
5815 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5816 if (!stop_info_sp || !stop_info_sp->IsValid())
5817 continue;
5818 }
5819 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005820 num_frames_with_source,
5821 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005822 ++num_thread_infos_dumped;
5823 } else {
5824 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5825 if (log)
5826 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5827 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005828 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005829 }
5830 return num_thread_infos_dumped;
5831}
5832
5833void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5834 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5835}
5836
5837bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5838 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5839 region.GetByteSize());
5840}
5841
5842void Process::AddPreResumeAction(PreResumeActionCallback callback,
5843 void *baton) {
5844 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5845}
5846
5847bool Process::RunPreResumeActions() {
5848 bool result = true;
5849 while (!m_pre_resume_actions.empty()) {
5850 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5851 m_pre_resume_actions.pop_back();
5852 bool this_result = action.callback(action.baton);
5853 if (result)
5854 result = this_result;
5855 }
5856 return result;
5857}
5858
5859void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5860
Jim Inghamffd91752016-10-20 22:50:00 +00005861void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5862{
5863 PreResumeCallbackAndBaton element(callback, baton);
5864 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5865 if (found_iter != m_pre_resume_actions.end())
5866 {
5867 m_pre_resume_actions.erase(found_iter);
5868 }
5869}
5870
Kate Stoneb9c1b512016-09-06 20:57:50 +00005871ProcessRunLock &Process::GetRunLock() {
5872 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5873 return m_private_run_lock;
5874 else
5875 return m_public_run_lock;
5876}
5877
5878void Process::Flush() {
5879 m_thread_list.Flush();
5880 m_extended_thread_list.Flush();
5881 m_extended_thread_stop_id = 0;
5882 m_queue_list.Clear();
5883 m_queue_list_stop_id = 0;
5884}
5885
5886void Process::DidExec() {
5887 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5888 if (log)
5889 log->Printf("Process::%s()", __FUNCTION__);
5890
5891 Target &target = GetTarget();
5892 target.CleanupProcess();
5893 target.ClearModules(false);
5894 m_dynamic_checkers_ap.reset();
5895 m_abi_sp.reset();
5896 m_system_runtime_ap.reset();
5897 m_os_ap.reset();
5898 m_dyld_ap.reset();
5899 m_jit_loaders_ap.reset();
5900 m_image_tokens.clear();
5901 m_allocated_memory_cache.Clear();
5902 m_language_runtimes.clear();
5903 m_instrumentation_runtimes.clear();
5904 m_thread_list.DiscardThreadPlans();
5905 m_memory_cache.Clear(true);
5906 m_stop_info_override_callback = nullptr;
5907 DoDidExec();
5908 CompleteAttach();
5909 // Flush the process (threads and all stack frames) after running
5910 // CompleteAttach()
5911 // in case the dynamic loader loaded things in new locations.
5912 Flush();
5913
5914 // After we figure out what was loaded/unloaded in CompleteAttach,
5915 // we need to let the target know so it can do any cleanup it needs to.
5916 target.DidExec();
5917}
5918
5919addr_t Process::ResolveIndirectFunction(const Address *address, Error &error) {
5920 if (address == nullptr) {
5921 error.SetErrorString("Invalid address argument");
5922 return LLDB_INVALID_ADDRESS;
5923 }
5924
5925 addr_t function_addr = LLDB_INVALID_ADDRESS;
5926
5927 addr_t addr = address->GetLoadAddress(&GetTarget());
5928 std::map<addr_t, addr_t>::const_iterator iter =
5929 m_resolved_indirect_addresses.find(addr);
5930 if (iter != m_resolved_indirect_addresses.end()) {
5931 function_addr = (*iter).second;
5932 } else {
5933 if (!InferiorCall(this, address, function_addr)) {
5934 Symbol *symbol = address->CalculateSymbolContextSymbol();
5935 error.SetErrorStringWithFormat(
5936 "Unable to call resolver for indirect function %s",
5937 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5938 function_addr = LLDB_INVALID_ADDRESS;
5939 } else {
5940 m_resolved_indirect_addresses.insert(
5941 std::pair<addr_t, addr_t>(addr, function_addr));
5942 }
5943 }
5944 return function_addr;
5945}
5946
5947void Process::ModulesDidLoad(ModuleList &module_list) {
5948 SystemRuntime *sys_runtime = GetSystemRuntime();
5949 if (sys_runtime) {
5950 sys_runtime->ModulesDidLoad(module_list);
5951 }
5952
5953 GetJITLoaders().ModulesDidLoad(module_list);
5954
5955 // Give runtimes a chance to be created.
5956 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5957 m_instrumentation_runtimes);
5958
5959 // Tell runtimes about new modules.
5960 for (auto pos = m_instrumentation_runtimes.begin();
5961 pos != m_instrumentation_runtimes.end(); ++pos) {
5962 InstrumentationRuntimeSP runtime = pos->second;
5963 runtime->ModulesDidLoad(module_list);
5964 }
5965
5966 // Let any language runtimes we have already created know
5967 // about the modules that loaded.
5968
5969 // Iterate over a copy of this language runtime list in case
5970 // the language runtime ModulesDidLoad somehow causes the language
5971 // riuntime to be unloaded.
5972 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5973 for (const auto &pair : language_runtimes) {
5974 // We must check language_runtime_sp to make sure it is not
5975 // nullptr as we might cache the fact that we didn't have a
5976 // language runtime for a language.
5977 LanguageRuntimeSP language_runtime_sp = pair.second;
5978 if (language_runtime_sp)
5979 language_runtime_sp->ModulesDidLoad(module_list);
5980 }
5981
5982 // If we don't have an operating system plug-in, try to load one since
5983 // loading shared libraries might cause a new one to try and load
5984 if (!m_os_ap)
5985 LoadOperatingSystemPlugin(false);
5986
5987 // Give structured-data plugins a chance to see the modified modules.
5988 for (auto pair : m_structured_data_plugin_map) {
5989 if (pair.second)
5990 pair.second->ModulesDidLoad(*this, module_list);
5991 }
5992}
5993
5994void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5995 const char *fmt, ...) {
5996 bool print_warning = true;
5997
5998 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5999 if (!stream_sp)
6000 return;
6001 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
6002 return;
6003 }
6004
6005 if (repeat_key != nullptr) {
6006 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
6007 if (it == m_warnings_issued.end()) {
6008 m_warnings_issued[warning_type] = WarningsPointerSet();
6009 m_warnings_issued[warning_type].insert(repeat_key);
6010 } else {
6011 if (it->second.find(repeat_key) != it->second.end()) {
6012 print_warning = false;
6013 } else {
6014 it->second.insert(repeat_key);
6015 }
6016 }
6017 }
6018
6019 if (print_warning) {
6020 va_list args;
6021 va_start(args, fmt);
6022 stream_sp->PrintfVarArg(fmt, args);
6023 va_end(args);
6024 }
6025}
6026
6027void Process::PrintWarningOptimization(const SymbolContext &sc) {
6028 if (GetWarningsOptimization() && sc.module_sp &&
6029 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
6030 sc.function->GetIsOptimized()) {
6031 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
6032 "%s was compiled with optimization - stepping may behave "
6033 "oddly; variables may not be available.\n",
6034 sc.module_sp->GetFileSpec().GetFilename().GetCString());
6035 }
6036}
6037
6038bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
6039 info.Clear();
6040
6041 PlatformSP platform_sp = GetTarget().GetPlatform();
6042 if (!platform_sp)
6043 return false;
6044
6045 return platform_sp->GetProcessInfo(GetID(), info);
6046}
6047
6048ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
6049 ThreadCollectionSP threads;
6050
6051 const MemoryHistorySP &memory_history =
6052 MemoryHistory::FindPlugin(shared_from_this());
6053
6054 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00006055 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006056 }
6057
6058 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6059
6060 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00006061}
Kuba Brecka63927542014-10-11 01:59:32 +00006062
6063InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00006064Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
6065 InstrumentationRuntimeCollection::iterator pos;
6066 pos = m_instrumentation_runtimes.find(type);
6067 if (pos == m_instrumentation_runtimes.end()) {
6068 return InstrumentationRuntimeSP();
6069 } else
6070 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00006071}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006072
Kate Stoneb9c1b512016-09-06 20:57:50 +00006073bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6074 const ArchSpec &arch, ModuleSpec &module_spec) {
6075 module_spec.Clear();
6076 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006077}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006078
Kate Stoneb9c1b512016-09-06 20:57:50 +00006079size_t Process::AddImageToken(lldb::addr_t image_ptr) {
6080 m_image_tokens.push_back(image_ptr);
6081 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006082}
6083
Kate Stoneb9c1b512016-09-06 20:57:50 +00006084lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
6085 if (token < m_image_tokens.size())
6086 return m_image_tokens[token];
6087 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006088}
6089
Kate Stoneb9c1b512016-09-06 20:57:50 +00006090void Process::ResetImageToken(size_t token) {
6091 if (token < m_image_tokens.size())
6092 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00006093}
Jason Molendafd4cea52016-01-08 21:40:11 +00006094
6095Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00006096Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
6097 AddressRange range_bounds) {
6098 Target &target = GetTarget();
6099 DisassemblerSP disassembler_sp;
6100 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006101
Kate Stoneb9c1b512016-09-06 20:57:50 +00006102 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006103
Kate Stoneb9c1b512016-09-06 20:57:50 +00006104 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00006105 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006106 if (!default_stop_addr.IsValid())
6107 return retval;
6108
6109 ExecutionContext exe_ctx(this);
6110 const char *plugin_name = nullptr;
6111 const char *flavor = nullptr;
6112 const bool prefer_file_cache = true;
6113 disassembler_sp = Disassembler::DisassembleRange(
6114 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6115 prefer_file_cache);
6116 if (disassembler_sp)
6117 insn_list = &disassembler_sp->GetInstructionList();
6118
6119 if (insn_list == nullptr) {
6120 return retval;
6121 }
6122
6123 size_t insn_offset =
6124 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6125 if (insn_offset == UINT32_MAX) {
6126 return retval;
6127 }
6128
6129 uint32_t branch_index =
6130 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6131 if (branch_index == UINT32_MAX) {
6132 return retval;
6133 }
6134
6135 if (branch_index > insn_offset) {
6136 Address next_branch_insn_address =
6137 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6138 if (next_branch_insn_address.IsValid() &&
6139 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6140 retval = next_branch_insn_address;
6141 }
6142 }
6143
6144 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00006145}
Howard Hellyerad007562016-07-07 08:21:28 +00006146
Kate Stoneb9c1b512016-09-06 20:57:50 +00006147Error Process::GetMemoryRegions(
6148 std::vector<lldb::MemoryRegionInfoSP> &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00006149
Kate Stoneb9c1b512016-09-06 20:57:50 +00006150 Error error;
Howard Hellyerad007562016-07-07 08:21:28 +00006151
Kate Stoneb9c1b512016-09-06 20:57:50 +00006152 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00006153
Kate Stoneb9c1b512016-09-06 20:57:50 +00006154 region_list.clear();
6155 do {
6156 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6157 error = GetMemoryRegionInfo(range_end, *region_info);
6158 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6159 if (error.Fail()) {
6160 region_list.clear();
6161 break;
Todd Fiala75930012016-08-19 04:21:48 +00006162 }
6163
Kate Stoneb9c1b512016-09-06 20:57:50 +00006164 range_end = region_info->GetRange().GetRangeEnd();
6165 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6166 region_list.push_back(region_info);
6167 }
6168 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00006169
Kate Stoneb9c1b512016-09-06 20:57:50 +00006170 return error;
6171}
6172
6173Error Process::ConfigureStructuredData(
6174 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
6175 // If you get this, the Process-derived class needs to implement a method
6176 // to enable an already-reported asynchronous structured data feature.
6177 // See ProcessGDBRemote for an example implementation over gdb-remote.
6178 return Error("unimplemented");
6179}
6180
6181void Process::MapSupportedStructuredDataPlugins(
6182 const StructuredData::Array &supported_type_names) {
6183 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6184
6185 // Bail out early if there are no type names to map.
6186 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00006187 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006188 log->Printf("Process::%s(): no structured data types supported",
6189 __FUNCTION__);
6190 return;
6191 }
Todd Fiala75930012016-08-19 04:21:48 +00006192
Kate Stoneb9c1b512016-09-06 20:57:50 +00006193 // Convert StructuredData type names to ConstString instances.
6194 std::set<ConstString> const_type_names;
6195
6196 if (log)
6197 log->Printf("Process::%s(): the process supports the following async "
6198 "structured data types:",
6199 __FUNCTION__);
6200
6201 supported_type_names.ForEach(
6202 [&const_type_names, &log](StructuredData::Object *object) {
6203 if (!object) {
6204 // Invalid - shouldn't be null objects in the array.
6205 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006206 }
6207
6208 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006209 if (!type_name) {
6210 // Invalid format - all type names should be strings.
6211 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006212 }
6213
6214 const_type_names.insert(ConstString(type_name->GetValue()));
6215 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006216 log->Printf("- %s", type_name->GetValue().c_str());
Todd Fiala75930012016-08-19 04:21:48 +00006217 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006218 });
Todd Fiala75930012016-08-19 04:21:48 +00006219
Kate Stoneb9c1b512016-09-06 20:57:50 +00006220 // For each StructuredDataPlugin, if the plugin handles any of the
6221 // types in the supported_type_names, map that type name to that plugin.
6222 uint32_t plugin_index = 0;
6223 for (auto create_instance =
6224 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6225 plugin_index);
6226 create_instance && !const_type_names.empty(); ++plugin_index) {
6227 // Create the plugin.
6228 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6229 if (!plugin_sp) {
6230 // This plugin doesn't think it can work with the process.
6231 // Move on to the next.
6232 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006233 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006234
6235 // For any of the remaining type names, map any that this plugin
6236 // supports.
6237 std::vector<ConstString> names_to_remove;
6238 for (auto &type_name : const_type_names) {
6239 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6240 m_structured_data_plugin_map.insert(
6241 std::make_pair(type_name, plugin_sp));
6242 names_to_remove.push_back(type_name);
6243 if (log)
6244 log->Printf("Process::%s(): using plugin %s for type name "
6245 "%s",
6246 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6247 type_name.GetCString());
6248 }
6249 }
6250
6251 // Remove the type names that were consumed by this plugin.
6252 for (auto &type_name : names_to_remove)
6253 const_type_names.erase(type_name);
6254 }
Todd Fiala75930012016-08-19 04:21:48 +00006255}
6256
Kate Stoneb9c1b512016-09-06 20:57:50 +00006257bool Process::RouteAsyncStructuredData(
6258 const StructuredData::ObjectSP object_sp) {
6259 // Nothing to do if there's no data.
6260 if (!object_sp)
6261 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006262
Kate Stoneb9c1b512016-09-06 20:57:50 +00006263 // The contract is this must be a dictionary, so we can look up the
6264 // routing key via the top-level 'type' string value within the dictionary.
6265 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6266 if (!dictionary)
6267 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006268
Kate Stoneb9c1b512016-09-06 20:57:50 +00006269 // Grab the async structured type name (i.e. the feature/plugin name).
6270 ConstString type_name;
6271 if (!dictionary->GetValueForKeyAsString("type", type_name))
6272 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006273
Kate Stoneb9c1b512016-09-06 20:57:50 +00006274 // Check if there's a plugin registered for this type name.
6275 auto find_it = m_structured_data_plugin_map.find(type_name);
6276 if (find_it == m_structured_data_plugin_map.end()) {
6277 // We don't have a mapping for this structured data type.
6278 return false;
6279 }
Todd Fiala75930012016-08-19 04:21:48 +00006280
Kate Stoneb9c1b512016-09-06 20:57:50 +00006281 // Route the structured data to the plugin.
6282 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6283 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006284}