blob: 5fe1e17b3c74d9a6a08dbd80304a60ce51f4f2ba [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(
415 uint32_t option_idx, const char *option_arg,
416 ExecutionContext *execution_context) {
417 Error error;
418 const int short_option = m_getopt_table[option_idx].val;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000419 auto option_strref = llvm::StringRef::withNullAsEmpty(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420
421 switch (short_option) {
422 case 's': // Stop at program entry point
423 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
424 break;
425
426 case 'i': // STDIN for read only
427 {
428 FileAction action;
429 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
430 launch_info.AppendFileAction(action);
431 break;
432 }
433
434 case 'o': // Open STDOUT for write only
435 {
436 FileAction action;
437 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
438 launch_info.AppendFileAction(action);
439 break;
440 }
441
442 case 'e': // STDERR for write only
443 {
444 FileAction action;
445 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
446 launch_info.AppendFileAction(action);
447 break;
448 }
449
450 case 'p': // Process plug-in name
451 launch_info.SetProcessPluginName(option_arg);
452 break;
453
454 case 'n': // Disable STDIO
455 {
456 FileAction action;
457 const FileSpec dev_null{FileSystem::DEV_NULL, false};
458 if (action.Open(STDIN_FILENO, dev_null, true, false))
459 launch_info.AppendFileAction(action);
460 if (action.Open(STDOUT_FILENO, dev_null, false, true))
461 launch_info.AppendFileAction(action);
462 if (action.Open(STDERR_FILENO, dev_null, false, true))
463 launch_info.AppendFileAction(action);
464 break;
465 }
466
467 case 'w':
468 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
469 break;
470
471 case 't': // Open process in new terminal window
472 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
473 break;
474
475 case 'a': {
476 TargetSP target_sp =
477 execution_context ? execution_context->GetTargetSP() : TargetSP();
478 PlatformSP platform_sp =
479 target_sp ? target_sp->GetPlatform() : PlatformSP();
480 if (!launch_info.GetArchitecture().SetTriple(option_arg, platform_sp.get()))
481 launch_info.GetArchitecture().SetTriple(option_arg);
482 } break;
483
484 case 'A': // Disable ASLR.
485 {
486 bool success;
487 const bool disable_aslr_arg =
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000488 Args::StringToBoolean(option_strref, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 if (success)
490 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000491 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 error.SetErrorStringWithFormat(
493 "Invalid boolean value for disable-aslr option: '%s'",
494 option_arg ? option_arg : "<null>");
495 break;
496 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000497
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498 case 'X': // shell expand args.
499 {
500 bool success;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000501 const bool expand_args =
502 Args::StringToBoolean(option_strref, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 if (success)
504 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000505 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506 error.SetErrorStringWithFormat(
507 "Invalid boolean value for shell-expand-args option: '%s'",
508 option_arg ? option_arg : "<null>");
509 break;
510 }
511
512 case 'c':
513 if (option_arg && option_arg[0])
514 launch_info.SetShell(FileSpec(option_arg, false));
515 else
516 launch_info.SetShell(HostInfo::GetDefaultShell());
517 break;
518
519 case 'v':
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000520 launch_info.GetEnvironmentEntries().AppendArgument(
521 llvm::StringRef::withNullAsEmpty(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 break;
523
524 default:
525 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
526 short_option);
527 break;
528 }
529 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000530}
531
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000532static OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
534 nullptr, nullptr, 0, eArgTypeNone,
535 "Stop at the entry point of the program when launching a process."},
536 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
537 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
538 "Set whether to disable address space layout randomization when launching "
539 "a process."},
540 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
541 nullptr, nullptr, 0, eArgTypePlugin,
542 "Name of the process plugin you want to use."},
543 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
544 OptionParser::eRequiredArgument, nullptr, nullptr, 0,
545 eArgTypeDirectoryName,
546 "Set the current working directory to <path> when running the inferior."},
547 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
548 nullptr, nullptr, 0, eArgTypeArchitecture,
549 "Set the architecture for the process to launch when ambiguous."},
550 {LLDB_OPT_SET_ALL, false, "environment", 'v',
551 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone,
552 "Specify an environment variable name/value string (--environment "
553 "NAME=VALUE). Can be specified multiple times for subsequent environment "
554 "entries."},
555 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
556 OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeFilename,
557 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000558
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
560 nullptr, nullptr, 0, eArgTypeFilename,
561 "Redirect stdin for the process to <filename>."},
562 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
563 nullptr, nullptr, 0, eArgTypeFilename,
564 "Redirect stdout for the process to <filename>."},
565 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
566 nullptr, nullptr, 0, eArgTypeFilename,
567 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000568
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
570 nullptr, 0, eArgTypeNone,
571 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000572
Kate Stoneb9c1b512016-09-06 20:57:50 +0000573 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
574 nullptr, 0, eArgTypeNone,
575 "Do not set up for terminal I/O to go to running process."},
576 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
577 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
578 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000579};
580
581llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000582 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000583}
Greg Clayton32e0a752011-03-30 18:16:51 +0000584
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
586 if (m_name_match_type == eNameMatchIgnore || process_name == nullptr)
Greg Clayton32e0a752011-03-30 18:16:51 +0000587 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588 const char *match_name = m_match_info.GetName();
589 if (!match_name)
Greg Clayton32e0a752011-03-30 18:16:51 +0000590 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591
592 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
Greg Clayton32e0a752011-03-30 18:16:51 +0000593}
594
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595bool ProcessInstanceInfoMatch::Matches(
596 const ProcessInstanceInfo &proc_info) const {
597 if (!NameMatches(proc_info.GetName()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000598 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599
600 if (m_match_info.ProcessIDIsValid() &&
601 m_match_info.GetProcessID() != proc_info.GetProcessID())
602 return false;
603
604 if (m_match_info.ParentProcessIDIsValid() &&
605 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
606 return false;
607
608 if (m_match_info.UserIDIsValid() &&
609 m_match_info.GetUserID() != proc_info.GetUserID())
610 return false;
611
612 if (m_match_info.GroupIDIsValid() &&
613 m_match_info.GetGroupID() != proc_info.GetGroupID())
614 return false;
615
616 if (m_match_info.EffectiveUserIDIsValid() &&
617 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
618 return false;
619
620 if (m_match_info.EffectiveGroupIDIsValid() &&
621 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
622 return false;
623
624 if (m_match_info.GetArchitecture().IsValid() &&
625 !m_match_info.GetArchitecture().IsCompatibleMatch(
626 proc_info.GetArchitecture()))
627 return false;
628 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000629}
630
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
632 if (m_name_match_type != eNameMatchIgnore)
633 return false;
634
635 if (m_match_info.ProcessIDIsValid())
636 return false;
637
638 if (m_match_info.ParentProcessIDIsValid())
639 return false;
640
641 if (m_match_info.UserIDIsValid())
642 return false;
643
644 if (m_match_info.GroupIDIsValid())
645 return false;
646
647 if (m_match_info.EffectiveUserIDIsValid())
648 return false;
649
650 if (m_match_info.EffectiveGroupIDIsValid())
651 return false;
652
653 if (m_match_info.GetArchitecture().IsValid())
654 return false;
655
656 if (m_match_all_users)
657 return false;
658
659 return true;
660}
661
662void ProcessInstanceInfoMatch::Clear() {
663 m_match_info.Clear();
664 m_name_match_type = eNameMatchIgnore;
665 m_match_all_users = false;
666}
667
668ProcessSP Process::FindPlugin(lldb::TargetSP target_sp, const char *plugin_name,
669 ListenerSP listener_sp,
670 const FileSpec *crash_file_path) {
671 static uint32_t g_process_unique_id = 0;
672
673 ProcessSP process_sp;
674 ProcessCreateInstance create_callback = nullptr;
675 if (plugin_name) {
676 ConstString const_plugin_name(plugin_name);
677 create_callback =
678 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
679 if (create_callback) {
680 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
681 if (process_sp) {
682 if (process_sp->CanDebug(target_sp, true)) {
683 process_sp->m_process_unique_id = ++g_process_unique_id;
684 } else
685 process_sp.reset();
686 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000687 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 } else {
689 for (uint32_t idx = 0;
690 (create_callback =
691 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
692 ++idx) {
693 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
694 if (process_sp) {
695 if (process_sp->CanDebug(target_sp, false)) {
696 process_sp->m_process_unique_id = ++g_process_unique_id;
697 break;
698 } else
699 process_sp.reset();
700 }
701 }
702 }
703 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704}
705
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706ConstString &Process::GetStaticBroadcasterClass() {
707 static ConstString class_name("lldb.process");
708 return class_name;
709}
710
711Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
712 : Process(target_sp, listener_sp,
713 UnixSignals::Create(HostInfo::GetArchitecture())) {
714 // This constructor just delegates to the full Process constructor,
715 // defaulting to using the Host's UnixSignals.
716}
717
718Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
719 const UnixSignalsSP &unix_signals_sp)
720 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
721 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
722 Process::GetStaticBroadcasterClass().AsCString()),
723 m_target_sp(target_sp), m_public_state(eStateUnloaded),
724 m_private_state(eStateUnloaded),
725 m_private_state_broadcaster(nullptr,
726 "lldb.process.internal_state_broadcaster"),
727 m_private_state_control_broadcaster(
728 nullptr, "lldb.process.internal_state_control_broadcaster"),
729 m_private_state_listener_sp(
730 Listener::MakeListener("lldb.process.internal_state_listener")),
731 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
732 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
733 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
734 m_thread_list(this), m_extended_thread_list(this),
735 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
736 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
737 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
738 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
739 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
740 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
741 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
742 m_memory_cache(*this), m_allocated_memory_cache(*this),
743 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
744 m_private_run_lock(), m_stop_info_override_callback(nullptr),
745 m_finalizing(false), m_finalize_called(false),
746 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
747 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
748 m_can_interpret_function_calls(false), m_warnings_issued(),
749 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
750 CheckInWithManager();
751
752 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
753 if (log)
754 log->Printf("%p Process::Process()", static_cast<void *>(this));
755
756 if (!m_unix_signals_sp)
757 m_unix_signals_sp = std::make_shared<UnixSignals>();
758
759 SetEventName(eBroadcastBitStateChanged, "state-changed");
760 SetEventName(eBroadcastBitInterrupt, "interrupt");
761 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
762 SetEventName(eBroadcastBitSTDERR, "stderr-available");
763 SetEventName(eBroadcastBitProfileData, "profile-data-available");
764 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
765
766 m_private_state_control_broadcaster.SetEventName(
767 eBroadcastInternalStateControlStop, "control-stop");
768 m_private_state_control_broadcaster.SetEventName(
769 eBroadcastInternalStateControlPause, "control-pause");
770 m_private_state_control_broadcaster.SetEventName(
771 eBroadcastInternalStateControlResume, "control-resume");
772
773 m_listener_sp->StartListeningForEvents(
774 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
775 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
776 eBroadcastBitProfileData | eBroadcastBitStructuredData);
777
778 m_private_state_listener_sp->StartListeningForEvents(
779 &m_private_state_broadcaster,
780 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
781
782 m_private_state_listener_sp->StartListeningForEvents(
783 &m_private_state_control_broadcaster,
784 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
785 eBroadcastInternalStateControlResume);
786 // We need something valid here, even if just the default UnixSignalsSP.
787 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
788
789 // Allow the platform to override the default cache line size
790 OptionValueSP value_sp =
791 m_collection_sp
792 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
793 ->GetValue();
794 uint32_t platform_cache_line_size =
795 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
796 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
797 value_sp->SetUInt64Value(platform_cache_line_size);
798}
799
800Process::~Process() {
801 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
802 if (log)
803 log->Printf("%p Process::~Process()", static_cast<void *>(this));
804 StopPrivateStateThread();
805
806 // ThreadList::Clear() will try to acquire this process's mutex, so
807 // explicitly clear the thread list here to ensure that the mutex
808 // is not destroyed before the thread list.
809 m_thread_list.Clear();
810}
811
812const ProcessPropertiesSP &Process::GetGlobalProperties() {
813 // NOTE: intentional leak so we don't crash if global destructor chain gets
814 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000815 static ProcessPropertiesSP *g_settings_sp_ptr =
816 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000817 return *g_settings_sp_ptr;
818}
819
820void Process::Finalize() {
821 m_finalizing = true;
822
823 // Destroy this process if needed
824 switch (GetPrivateState()) {
825 case eStateConnected:
826 case eStateAttaching:
827 case eStateLaunching:
828 case eStateStopped:
829 case eStateRunning:
830 case eStateStepping:
831 case eStateCrashed:
832 case eStateSuspended:
833 Destroy(false);
834 break;
835
836 case eStateInvalid:
837 case eStateUnloaded:
838 case eStateDetached:
839 case eStateExited:
840 break;
841 }
842
843 // Clear our broadcaster before we proceed with destroying
844 Broadcaster::Clear();
845
846 // Do any cleanup needed prior to being destructed... Subclasses
847 // that override this method should call this superclass method as well.
848
849 // We need to destroy the loader before the derived Process class gets
850 // destroyed
851 // since it is very likely that undoing the loader will require access to the
852 // real process.
853 m_dynamic_checkers_ap.reset();
854 m_abi_sp.reset();
855 m_os_ap.reset();
856 m_system_runtime_ap.reset();
857 m_dyld_ap.reset();
858 m_jit_loaders_ap.reset();
859 m_thread_list_real.Destroy();
860 m_thread_list.Destroy();
861 m_extended_thread_list.Destroy();
862 m_queue_list.Clear();
863 m_queue_list_stop_id = 0;
864 std::vector<Notifications> empty_notifications;
865 m_notifications.swap(empty_notifications);
866 m_image_tokens.clear();
867 m_memory_cache.Clear();
868 m_allocated_memory_cache.Clear();
869 m_language_runtimes.clear();
870 m_instrumentation_runtimes.clear();
871 m_next_event_action_ap.reset();
872 m_stop_info_override_callback = nullptr;
873 // Clear the last natural stop ID since it has a strong
874 // reference to this process
875 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
876 //#ifdef LLDB_CONFIGURATION_DEBUG
877 // StreamFile s(stdout, false);
878 // EventSP event_sp;
879 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
880 // {
881 // event_sp->Dump (&s);
882 // s.EOL();
883 // }
884 //#endif
885 // We have to be very careful here as the m_private_state_listener might
886 // contain events that have ProcessSP values in them which can keep this
887 // process around forever. These events need to be cleared out.
888 m_private_state_listener_sp->Clear();
889 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
890 m_public_run_lock.SetStopped();
891 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
892 m_private_run_lock.SetStopped();
893 m_finalize_called = true;
894}
895
896void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
897 m_notifications.push_back(callbacks);
898 if (callbacks.initialize != nullptr)
899 callbacks.initialize(callbacks.baton, this);
900}
901
902bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
903 std::vector<Notifications>::iterator pos, end = m_notifications.end();
904 for (pos = m_notifications.begin(); pos != end; ++pos) {
905 if (pos->baton == callbacks.baton &&
906 pos->initialize == callbacks.initialize &&
907 pos->process_state_changed == callbacks.process_state_changed) {
908 m_notifications.erase(pos);
909 return true;
910 }
911 }
912 return false;
913}
914
915void Process::SynchronouslyNotifyStateChanged(StateType state) {
916 std::vector<Notifications>::iterator notification_pos,
917 notification_end = m_notifications.end();
918 for (notification_pos = m_notifications.begin();
919 notification_pos != notification_end; ++notification_pos) {
920 if (notification_pos->process_state_changed)
921 notification_pos->process_state_changed(notification_pos->baton, this,
922 state);
923 }
924}
925
926// FIXME: We need to do some work on events before the general Listener sees
927// them.
928// For instance if we are continuing from a breakpoint, we need to ensure that
929// we do
930// the little "insert real insn, step & stop" trick. But we can't do that when
931// the
932// event is delivered by the broadcaster - since that is done on the thread that
933// is
934// waiting for new events, so if we needed more than one event for our handling,
935// we would
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000936// stall. So instead we do it when we fetch the event off of the queue.
937//
938
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939StateType Process::GetNextEvent(EventSP &event_sp) {
940 StateType state = eStateInvalid;
941
942 if (m_listener_sp->GetNextEventForBroadcaster(this, event_sp) && event_sp)
943 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
944
945 return state;
946}
947
948void Process::SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec) {
949 // don't sync (potentially context switch) in case where there is no process
950 // IO
951 if (!m_process_input_reader)
952 return;
953
954 uint32_t new_iohandler_id = 0;
955 m_iohandler_sync.WaitForValueNotEqualTo(
956 iohandler_id, new_iohandler_id, std::chrono::milliseconds(timeout_msec));
957
958 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
959 if (log)
960 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, "
961 "new value is %u",
962 __FUNCTION__, iohandler_id, new_iohandler_id);
963}
964
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000965StateType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966Process::WaitForProcessToStop(const std::chrono::microseconds &timeout,
967 EventSP *event_sp_ptr, bool wait_always,
968 ListenerSP hijack_listener_sp, Stream *stream,
969 bool use_run_lock) {
970 // We can't just wait for a "stopped" event, because the stopped event may
971 // have restarted the target.
972 // We have to actually check each event, and in the case of a stopped event
973 // check the restarted flag
974 // on the event.
975 if (event_sp_ptr)
976 event_sp_ptr->reset();
977 StateType state = GetState();
978 // If we are exited or detached, we won't ever get back to any
979 // other valid state...
980 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000981 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000982
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
984 if (log)
985 log->Printf("Process::%s (timeout = %llu)", __FUNCTION__,
986 static_cast<unsigned long long>(timeout.count()));
Todd Fialaa3b89e22014-08-12 14:33:19 +0000987
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 if (!wait_always && StateIsStoppedState(state, true) &&
989 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000990 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991 log->Printf("Process::%s returning without waiting for events; process "
992 "private and public states are already 'stopped'.",
993 __FUNCTION__);
994 // We need to toggle the run lock as this won't get done in
995 // SetPublicState() if the process is hijacked.
996 if (hijack_listener_sp && use_run_lock)
997 m_public_run_lock.SetStopped();
998 return state;
999 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 while (state != eStateInvalid) {
1002 EventSP event_sp;
1003 state = WaitForStateChangedEvents(timeout, event_sp, hijack_listener_sp);
1004 if (event_sp_ptr && event_sp)
1005 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001006
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1008 Process::HandleProcessStateChangedEvent(event_sp, stream,
1009 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +00001010
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 switch (state) {
1012 case eStateCrashed:
1013 case eStateDetached:
1014 case eStateExited:
1015 case eStateUnloaded:
1016 // We need to toggle the run lock as this won't get done in
1017 // SetPublicState() if the process is hijacked.
1018 if (hijack_listener_sp && use_run_lock)
1019 m_public_run_lock.SetStopped();
1020 return state;
1021 case eStateStopped:
1022 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1023 continue;
1024 else {
Pavel Labath78521ef2015-03-06 10:52:47 +00001025 // We need to toggle the run lock as this won't get done in
1026 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001027 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028 m_public_run_lock.SetStopped();
1029 return state;
1030 }
1031 default:
1032 continue;
1033 }
1034 }
1035 return state;
1036}
1037
1038bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1039 Stream *stream,
1040 bool &pop_process_io_handler) {
1041 const bool handle_pop = pop_process_io_handler;
1042
1043 pop_process_io_handler = false;
1044 ProcessSP process_sp =
1045 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1046
1047 if (!process_sp)
1048 return false;
1049
1050 StateType event_state =
1051 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1052 if (event_state == eStateInvalid)
1053 return false;
1054
1055 switch (event_state) {
1056 case eStateInvalid:
1057 case eStateUnloaded:
1058 case eStateAttaching:
1059 case eStateLaunching:
1060 case eStateStepping:
1061 case eStateDetached:
1062 if (stream)
1063 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1064 StateAsCString(event_state));
1065 if (event_state == eStateDetached)
1066 pop_process_io_handler = true;
1067 break;
1068
1069 case eStateConnected:
1070 case eStateRunning:
1071 // Don't be chatty when we run...
1072 break;
1073
1074 case eStateExited:
1075 if (stream)
1076 process_sp->GetStatus(*stream);
1077 pop_process_io_handler = true;
1078 break;
1079
1080 case eStateStopped:
1081 case eStateCrashed:
1082 case eStateSuspended:
1083 // Make sure the program hasn't been auto-restarted:
1084 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1085 if (stream) {
1086 size_t num_reasons =
1087 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1088 if (num_reasons > 0) {
1089 // FIXME: Do we want to report this, or would that just be annoyingly
1090 // chatty?
1091 if (num_reasons == 1) {
1092 const char *reason =
1093 Process::ProcessEventData::GetRestartedReasonAtIndex(
1094 event_sp.get(), 0);
1095 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1096 process_sp->GetID(),
1097 reason ? reason : "<UNKNOWN REASON>");
1098 } else {
1099 stream->Printf("Process %" PRIu64
1100 " stopped and restarted, reasons:\n",
1101 process_sp->GetID());
1102
1103 for (size_t i = 0; i < num_reasons; i++) {
1104 const char *reason =
1105 Process::ProcessEventData::GetRestartedReasonAtIndex(
1106 event_sp.get(), i);
1107 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1108 }
1109 }
1110 }
1111 }
1112 } else {
1113 StopInfoSP curr_thread_stop_info_sp;
1114 // Lock the thread list so it doesn't change on us, this is the scope for
1115 // the locker:
1116 {
1117 ThreadList &thread_list = process_sp->GetThreadList();
1118 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1119
1120 ThreadSP curr_thread(thread_list.GetSelectedThread());
1121 ThreadSP thread;
1122 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1123 if (curr_thread) {
1124 curr_thread_stop_reason = curr_thread->GetStopReason();
1125 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1126 }
1127 if (!curr_thread || !curr_thread->IsValid() ||
1128 curr_thread_stop_reason == eStopReasonInvalid ||
1129 curr_thread_stop_reason == eStopReasonNone) {
1130 // Prefer a thread that has just completed its plan over another
1131 // thread as current thread.
1132 ThreadSP plan_thread;
1133 ThreadSP other_thread;
1134
1135 const size_t num_threads = thread_list.GetSize();
1136 size_t i;
1137 for (i = 0; i < num_threads; ++i) {
1138 thread = thread_list.GetThreadAtIndex(i);
1139 StopReason thread_stop_reason = thread->GetStopReason();
1140 switch (thread_stop_reason) {
1141 case eStopReasonInvalid:
1142 case eStopReasonNone:
1143 break;
1144
1145 case eStopReasonSignal: {
1146 // Don't select a signal thread if we weren't going to stop at
1147 // that
1148 // signal. We have to have had another reason for stopping here,
1149 // and
1150 // the user doesn't want to see this thread.
1151 uint64_t signo = thread->GetStopInfo()->GetValue();
1152 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1153 if (!other_thread)
1154 other_thread = thread;
1155 }
1156 break;
1157 }
1158 case eStopReasonTrace:
1159 case eStopReasonBreakpoint:
1160 case eStopReasonWatchpoint:
1161 case eStopReasonException:
1162 case eStopReasonExec:
1163 case eStopReasonThreadExiting:
1164 case eStopReasonInstrumentation:
1165 if (!other_thread)
1166 other_thread = thread;
1167 break;
1168 case eStopReasonPlanComplete:
1169 if (!plan_thread)
1170 plan_thread = thread;
1171 break;
1172 }
1173 }
1174 if (plan_thread)
1175 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1176 else if (other_thread)
1177 thread_list.SetSelectedThreadByID(other_thread->GetID());
1178 else {
1179 if (curr_thread && curr_thread->IsValid())
1180 thread = curr_thread;
1181 else
1182 thread = thread_list.GetThreadAtIndex(0);
1183
1184 if (thread)
1185 thread_list.SetSelectedThreadByID(thread->GetID());
1186 }
1187 }
1188 }
1189 // Drop the ThreadList mutex by here, since GetThreadStatus below might
1190 // have to run code,
1191 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the
1192 // process is going to
1193 // have a hard time restarting the process.
1194 if (stream) {
1195 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1196 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1197 &process_sp->GetTarget()) {
1198 const bool only_threads_with_stop_reason = true;
1199 const uint32_t start_frame = 0;
1200 const uint32_t num_frames = 1;
1201 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001202 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203 process_sp->GetStatus(*stream);
1204 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1205 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001206 num_frames_with_source,
1207 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001208 if (curr_thread_stop_info_sp) {
1209 lldb::addr_t crashing_address;
1210 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1211 curr_thread_stop_info_sp, &crashing_address);
1212 if (valobj_sp) {
1213 const bool qualify_cxx_base_classes = false;
1214
1215 const ValueObject::GetExpressionPathFormat format =
1216 ValueObject::GetExpressionPathFormat::
1217 eGetExpressionPathFormatHonorPointers;
1218 stream->PutCString("Likely cause: ");
1219 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1220 format);
1221 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1222 }
1223 }
1224 } else {
1225 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1226 process_sp->GetTarget().shared_from_this());
1227 if (target_idx != UINT32_MAX)
1228 stream->Printf("Target %d: (", target_idx);
1229 else
1230 stream->Printf("Target <unknown index>: (");
1231 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1232 stream->Printf(") stopped.\n");
1233 }
1234 }
1235
1236 // Pop the process IO handler
1237 pop_process_io_handler = true;
1238 }
1239 break;
1240 }
1241
1242 if (handle_pop && pop_process_io_handler)
1243 process_sp->PopProcessIOHandler();
1244
1245 return true;
1246}
1247
1248StateType Process::WaitForState(const std::chrono::microseconds &timeout,
1249 const StateType *match_states,
1250 const uint32_t num_match_states) {
1251 EventSP event_sp;
1252 StateType state = GetState();
1253 while (state != eStateInvalid) {
1254 // If we are exited or detached, we won't ever get back to any
1255 // other valid state...
1256 if (state == eStateDetached || state == eStateExited)
1257 return state;
1258
1259 state = WaitForStateChangedEvents(timeout, event_sp, nullptr);
1260
1261 for (uint32_t i = 0; i < num_match_states; ++i) {
1262 if (match_states[i] == state)
Daniel Malea9e9919f2013-10-09 16:56:28 +00001263 return state;
1264 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 }
1266 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001267}
1268
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1270 if (listener_sp) {
1271 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1272 eBroadcastBitInterrupt);
1273 } else
1274 return false;
1275}
Greg Claytondc6224e2014-10-21 01:00:42 +00001276
Kate Stoneb9c1b512016-09-06 20:57:50 +00001277void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001278
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279StateType
1280Process::WaitForStateChangedEvents(const std::chrono::microseconds &timeout,
1281 EventSP &event_sp,
1282 ListenerSP hijack_listener_sp) {
1283 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001284
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285 if (log)
1286 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1287 static_cast<unsigned long long>(timeout.count()));
Greg Claytondc6224e2014-10-21 01:00:42 +00001288
Kate Stoneb9c1b512016-09-06 20:57:50 +00001289 ListenerSP listener_sp = hijack_listener_sp;
1290 if (!listener_sp)
1291 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001292
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293 StateType state = eStateInvalid;
1294 if (listener_sp->WaitForEventForBroadcasterWithType(
1295 timeout, this, eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1296 event_sp)) {
1297 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1298 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1299 else if (log)
1300 log->Printf("Process::%s got no event or was interrupted.", __FUNCTION__);
1301 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001302
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 if (log)
1304 log->Printf("Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1305 static_cast<unsigned long long>(timeout.count()),
1306 StateAsCString(state));
1307 return state;
1308}
Greg Claytondc6224e2014-10-21 01:00:42 +00001309
Kate Stoneb9c1b512016-09-06 20:57:50 +00001310Event *Process::PeekAtStateChangedEvents() {
1311 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001312
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313 if (log)
1314 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001315
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 Event *event_ptr;
1317 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1318 this, eBroadcastBitStateChanged);
1319 if (log) {
1320 if (event_ptr) {
1321 log->Printf(
1322 "Process::%s (event_ptr) => %s", __FUNCTION__,
1323 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1324 } else {
1325 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001326 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001327 }
1328 return event_ptr;
1329}
Greg Claytondc6224e2014-10-21 01:00:42 +00001330
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331StateType Process::WaitForStateChangedEventsPrivate(
1332 const std::chrono::microseconds &timeout, EventSP &event_sp) {
1333 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001334
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335 if (log)
1336 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1337 static_cast<unsigned long long>(timeout.count()));
1338
1339 StateType state = eStateInvalid;
1340 if (m_private_state_listener_sp->WaitForEventForBroadcasterWithType(
1341 timeout, &m_private_state_broadcaster,
1342 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp))
1343 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1344 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1345
1346 // This is a bit of a hack, but when we wait here we could very well return
1347 // to the command-line, and that could disable the log, which would render the
1348 // log we got above invalid.
1349 if (log)
1350 log->Printf("Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1351 static_cast<unsigned long long>(timeout.count()),
1352 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1353 return state;
1354}
1355
1356bool Process::WaitForEventsPrivate(const std::chrono::microseconds &timeout,
1357 EventSP &event_sp, bool control_only) {
1358 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1359
1360 if (log)
1361 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1362 static_cast<unsigned long long>(timeout.count()));
1363
1364 if (control_only)
1365 return m_private_state_listener_sp->WaitForEventForBroadcaster(
1366 timeout, &m_private_state_control_broadcaster, event_sp);
1367 else
1368 return m_private_state_listener_sp->WaitForEvent(timeout, event_sp);
1369}
1370
1371bool Process::IsRunning() const {
1372 return StateIsRunningState(m_public_state.GetValue());
1373}
1374
1375int Process::GetExitStatus() {
1376 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1377
1378 if (m_public_state.GetValue() == eStateExited)
1379 return m_exit_status;
1380 return -1;
1381}
1382
1383const char *Process::GetExitDescription() {
1384 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1385
1386 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1387 return m_exit_string.c_str();
1388 return nullptr;
1389}
1390
1391bool Process::SetExitStatus(int status, const char *cstr) {
1392 // Use a mutex to protect setting the exit status.
1393 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1394
1395 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1396 LIBLLDB_LOG_PROCESS));
1397 if (log)
1398 log->Printf(
1399 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1400 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1401 cstr ? "\"" : "");
1402
1403 // We were already in the exited state
1404 if (m_private_state.GetValue() == eStateExited) {
1405 if (log)
1406 log->Printf("Process::SetExitStatus () ignoring exit status because "
1407 "state was already set to eStateExited");
1408 return false;
1409 }
1410
1411 m_exit_status = status;
1412 if (cstr)
1413 m_exit_string = cstr;
1414 else
1415 m_exit_string.clear();
1416
1417 // Clear the last natural stop ID since it has a strong
1418 // reference to this process
1419 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1420
1421 SetPrivateState(eStateExited);
1422
1423 // Allow subclasses to do some cleanup
1424 DidExit();
1425
1426 return true;
1427}
1428
1429bool Process::IsAlive() {
1430 switch (m_private_state.GetValue()) {
1431 case eStateConnected:
1432 case eStateAttaching:
1433 case eStateLaunching:
1434 case eStateStopped:
1435 case eStateRunning:
1436 case eStateStepping:
1437 case eStateCrashed:
1438 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001439 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 default:
1441 return false;
1442 }
Jason Molendaa814f702015-11-05 23:03:44 +00001443}
1444
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001445// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001446// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001447// found in the global target list (we want to be completely sure that the
1448// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449bool Process::SetProcessExitStatus(
1450 lldb::pid_t pid, bool exited,
1451 int signo, // Zero for no signal
1452 int exit_status // Exit value of process if signal is zero
1453 ) {
1454 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1455 if (log)
1456 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1457 ", exited=%i, signal=%i, exit_status=%i)\n",
1458 pid, exited, signo, exit_status);
1459
1460 if (exited) {
1461 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1462 if (target_sp) {
1463 ProcessSP process_sp(target_sp->GetProcessSP());
1464 if (process_sp) {
1465 const char *signal_cstr = nullptr;
1466 if (signo)
1467 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1468
1469 process_sp->SetExitStatus(exit_status, signal_cstr);
1470 }
1471 }
1472 return true;
1473 }
1474 return false;
1475}
1476
1477void Process::UpdateThreadListIfNeeded() {
1478 const uint32_t stop_id = GetStopID();
1479 if (m_thread_list.GetSize(false) == 0 ||
1480 stop_id != m_thread_list.GetStopID()) {
1481 const StateType state = GetPrivateState();
1482 if (StateIsStoppedState(state, true)) {
1483 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1484 // m_thread_list does have its own mutex, but we need to
1485 // hold onto the mutex between the call to UpdateThreadList(...)
1486 // and the os->UpdateThreadList(...) so it doesn't change on us
1487 ThreadList &old_thread_list = m_thread_list;
1488 ThreadList real_thread_list(this);
1489 ThreadList new_thread_list(this);
1490 // Always update the thread list with the protocol specific
1491 // thread list, but only update if "true" is returned
1492 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1493 // Don't call into the OperatingSystem to update the thread list if we
1494 // are shutting down, since
1495 // that may call back into the SBAPI's, requiring the API lock which is
1496 // already held by whoever is
1497 // shutting us down, causing a deadlock.
1498 OperatingSystem *os = GetOperatingSystem();
1499 if (os && !m_destroy_in_process) {
1500 // Clear any old backing threads where memory threads might have been
1501 // backed by actual threads from the lldb_private::Process subclass
1502 size_t num_old_threads = old_thread_list.GetSize(false);
1503 for (size_t i = 0; i < num_old_threads; ++i)
1504 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1505
1506 // Turn off dynamic types to ensure we don't run any expressions.
1507 // Objective C
1508 // can run an expression to determine if a SBValue is a dynamic type
1509 // or not
1510 // and we need to avoid this. OperatingSystem plug-ins can't run
1511 // expressions
1512 // that require running code...
1513
1514 Target &target = GetTarget();
1515 const lldb::DynamicValueType saved_prefer_dynamic =
1516 target.GetPreferDynamicValue();
1517 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1518 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1519
1520 // Now let the OperatingSystem plug-in update the thread list
1521
1522 os->UpdateThreadList(
1523 old_thread_list, // Old list full of threads created by OS plug-in
1524 real_thread_list, // The actual thread list full of threads
1525 // created by each lldb_private::Process
1526 // subclass
1527 new_thread_list); // The new thread list that we will show to the
1528 // user that gets filled in
1529
1530 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1531 target.SetPreferDynamicValue(saved_prefer_dynamic);
1532 } else {
1533 // No OS plug-in, the new thread list is the same as the real thread
1534 // list
1535 new_thread_list = real_thread_list;
1536 }
1537
1538 m_thread_list_real.Update(real_thread_list);
1539 m_thread_list.Update(new_thread_list);
1540 m_thread_list.SetStopID(stop_id);
1541
1542 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1543 // Clear any extended threads that we may have accumulated previously
1544 m_extended_thread_list.Clear();
1545 m_extended_thread_stop_id = GetLastNaturalStopID();
1546
1547 m_queue_list.Clear();
1548 m_queue_list_stop_id = GetLastNaturalStopID();
1549 }
1550 }
1551 }
1552 }
1553}
1554
1555void Process::UpdateQueueListIfNeeded() {
1556 if (m_system_runtime_ap) {
1557 if (m_queue_list.GetSize() == 0 ||
1558 m_queue_list_stop_id != GetLastNaturalStopID()) {
1559 const StateType state = GetPrivateState();
1560 if (StateIsStoppedState(state, true)) {
1561 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1562 m_queue_list_stop_id = GetLastNaturalStopID();
1563 }
1564 }
1565 }
1566}
1567
1568ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1569 OperatingSystem *os = GetOperatingSystem();
1570 if (os)
1571 return os->CreateThread(tid, context);
1572 return ThreadSP();
1573}
1574
1575uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1576 return AssignIndexIDToThread(thread_id);
1577}
1578
1579bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1580 return (m_thread_id_to_index_id_map.find(thread_id) !=
1581 m_thread_id_to_index_id_map.end());
1582}
1583
1584uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1585 uint32_t result = 0;
1586 std::map<uint64_t, uint32_t>::iterator iterator =
1587 m_thread_id_to_index_id_map.find(thread_id);
1588 if (iterator == m_thread_id_to_index_id_map.end()) {
1589 result = ++m_thread_index_id;
1590 m_thread_id_to_index_id_map[thread_id] = result;
1591 } else {
1592 result = iterator->second;
1593 }
1594
1595 return result;
1596}
1597
1598StateType Process::GetState() {
1599 // If any other threads access this we will need a mutex for it
1600 return m_public_state.GetValue();
1601}
1602
1603bool Process::StateChangedIsExternallyHijacked() {
1604 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1605 const char *hijacking_name = GetHijackingListenerName();
1606 if (hijacking_name &&
1607 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1608 return true;
1609 }
1610 return false;
1611}
1612
1613void Process::SetPublicState(StateType new_state, bool restarted) {
1614 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1615 LIBLLDB_LOG_PROCESS));
1616 if (log)
1617 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1618 StateAsCString(new_state), restarted);
1619 const StateType old_state = m_public_state.GetValue();
1620 m_public_state.SetValue(new_state);
1621
1622 // On the transition from Run to Stopped, we unlock the writer end of the
1623 // run lock. The lock gets locked in Resume, which is the public API
1624 // to tell the program to run.
1625 if (!StateChangedIsExternallyHijacked()) {
1626 if (new_state == eStateDetached) {
1627 if (log)
1628 log->Printf(
1629 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1630 StateAsCString(new_state));
1631 m_public_run_lock.SetStopped();
1632 } else {
1633 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1634 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1635 if ((old_state_is_stopped != new_state_is_stopped)) {
1636 if (new_state_is_stopped && !restarted) {
1637 if (log)
1638 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1639 StateAsCString(new_state));
1640 m_public_run_lock.SetStopped();
1641 }
1642 }
1643 }
1644 }
1645}
1646
1647Error Process::Resume() {
1648 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1649 LIBLLDB_LOG_PROCESS));
1650 if (log)
1651 log->Printf("Process::Resume -- locking run lock");
1652 if (!m_public_run_lock.TrySetRunning()) {
1653 Error error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001654 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001656 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657 }
1658 return PrivateResume();
Greg Claytondc6224e2014-10-21 01:00:42 +00001659}
1660
Kate Stoneb9c1b512016-09-06 20:57:50 +00001661Error Process::ResumeSynchronous(Stream *stream) {
1662 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1663 LIBLLDB_LOG_PROCESS));
1664 if (log)
1665 log->Printf("Process::ResumeSynchronous -- locking run lock");
1666 if (!m_public_run_lock.TrySetRunning()) {
1667 Error error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001668 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001669 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1670 return error;
1671 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001672
Kate Stoneb9c1b512016-09-06 20:57:50 +00001673 ListenerSP listener_sp(
1674 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1675 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001676
Kate Stoneb9c1b512016-09-06 20:57:50 +00001677 Error error = PrivateResume();
1678 if (error.Success()) {
1679 StateType state = WaitForProcessToStop(std::chrono::microseconds(0), NULL,
1680 true, listener_sp, stream);
1681 const bool must_be_alive =
1682 false; // eStateExited is ok, so this must be false
1683 if (!StateIsStoppedState(state, must_be_alive))
1684 error.SetErrorStringWithFormat(
1685 "process not in stopped state after synchronous resume: %s",
1686 StateAsCString(state));
1687 }
Ed Mastec29693f2013-07-02 16:35:47 +00001688
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 // Undo the hijacking of process events...
1690 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001691
Kate Stoneb9c1b512016-09-06 20:57:50 +00001692 return error;
1693}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001694
Kate Stoneb9c1b512016-09-06 20:57:50 +00001695StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001696
Kate Stoneb9c1b512016-09-06 20:57:50 +00001697void Process::SetPrivateState(StateType new_state) {
1698 if (m_finalize_called)
1699 return;
1700
1701 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1702 LIBLLDB_LOG_PROCESS));
1703 bool state_changed = false;
1704
1705 if (log)
1706 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1707
1708 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1709 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1710
1711 const StateType old_state = m_private_state.GetValueNoLock();
1712 state_changed = old_state != new_state;
1713
1714 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1715 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1716 if (old_state_is_stopped != new_state_is_stopped) {
1717 if (new_state_is_stopped)
1718 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001719 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720 m_private_run_lock.SetRunning();
1721 }
1722
1723 if (state_changed) {
1724 m_private_state.SetValueNoLock(new_state);
1725 EventSP event_sp(
1726 new Event(eBroadcastBitStateChanged,
1727 new ProcessEventData(shared_from_this(), new_state)));
1728 if (StateIsStoppedState(new_state, false)) {
1729 // Note, this currently assumes that all threads in the list
1730 // stop when the process stops. In the future we will want to
1731 // support a debugging model where some threads continue to run
1732 // while others are stopped. When that happens we will either need
1733 // a way for the thread list to identify which threads are stopping
1734 // or create a special thread list containing only threads which
1735 // actually stopped.
1736 //
1737 // The process plugin is responsible for managing the actual
1738 // behavior of the threads and should have stopped any threads
1739 // that are going to stop before we get here.
1740 m_thread_list.DidStop();
1741
1742 m_mod_id.BumpStopID();
1743 if (!m_mod_id.IsLastResumeForUserExpression())
1744 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1745 m_memory_cache.Clear();
1746 if (log)
1747 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1748 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001749 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001750
Kate Stoneb9c1b512016-09-06 20:57:50 +00001751 // Use our target to get a shared pointer to ourselves...
1752 if (m_finalize_called && !PrivateStateThreadIsValid())
1753 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001754 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755 m_private_state_broadcaster.BroadcastEvent(event_sp);
1756 } else {
1757 if (log)
1758 log->Printf(
1759 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1760 StateAsCString(new_state));
1761 }
Jim Ingham22777012010-09-23 02:01:19 +00001762}
1763
Kate Stoneb9c1b512016-09-06 20:57:50 +00001764void Process::SetRunningUserExpression(bool on) {
1765 m_mod_id.SetRunningUserExpression(on);
1766}
1767
1768addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1769
1770const lldb::ABISP &Process::GetABI() {
1771 if (!m_abi_sp)
1772 m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture());
1773 return m_abi_sp;
1774}
1775
1776LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1777 bool retry_if_null) {
1778 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001779 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001780
1781 LanguageRuntimeCollection::iterator pos;
1782 pos = m_language_runtimes.find(language);
1783 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1784 lldb::LanguageRuntimeSP runtime_sp(
1785 LanguageRuntime::FindPlugin(this, language));
1786
1787 m_language_runtimes[language] = runtime_sp;
1788 return runtime_sp.get();
1789 } else
1790 return (*pos).second.get();
Jim Ingham22777012010-09-23 02:01:19 +00001791}
1792
Kate Stoneb9c1b512016-09-06 20:57:50 +00001793CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1794 LanguageRuntime *runtime =
1795 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1796 if (runtime != nullptr &&
1797 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1798 return static_cast<CPPLanguageRuntime *>(runtime);
1799 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001800}
1801
Kate Stoneb9c1b512016-09-06 20:57:50 +00001802ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1803 LanguageRuntime *runtime =
1804 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1805 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1806 return static_cast<ObjCLanguageRuntime *>(runtime);
1807 return nullptr;
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001808}
1809
Kate Stoneb9c1b512016-09-06 20:57:50 +00001810bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1811 if (m_finalizing)
1812 return false;
1813
1814 if (in_value.IsDynamic())
1815 return false;
1816 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1817
1818 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1819 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1820 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1821 }
1822
1823 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1824 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1825 return true;
1826
1827 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1828 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001829}
1830
Kate Stoneb9c1b512016-09-06 20:57:50 +00001831void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1832 m_dynamic_checkers_ap.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001833}
1834
Kate Stoneb9c1b512016-09-06 20:57:50 +00001835BreakpointSiteList &Process::GetBreakpointSiteList() {
1836 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837}
1838
Kate Stoneb9c1b512016-09-06 20:57:50 +00001839const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1840 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001841}
1842
Kate Stoneb9c1b512016-09-06 20:57:50 +00001843void Process::DisableAllBreakpointSites() {
1844 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1845 // bp_site->SetEnabled(true);
1846 DisableBreakpointSite(bp_site);
1847 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001848}
1849
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850Error Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1851 Error error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001852
Kate Stoneb9c1b512016-09-06 20:57:50 +00001853 if (error.Success())
1854 m_breakpoint_site_list.Remove(break_id);
1855
1856 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001857}
1858
Kate Stoneb9c1b512016-09-06 20:57:50 +00001859Error Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1860 Error error;
1861 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1862 if (bp_site_sp) {
1863 if (bp_site_sp->IsEnabled())
1864 error = DisableBreakpointSite(bp_site_sp.get());
1865 } else {
1866 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1867 break_id);
1868 }
1869
1870 return error;
1871}
1872
1873Error Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1874 Error error;
1875 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1876 if (bp_site_sp) {
1877 if (!bp_site_sp->IsEnabled())
1878 error = EnableBreakpointSite(bp_site_sp.get());
1879 } else {
1880 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1881 break_id);
1882 }
1883 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001884}
1885
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001886lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001887Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1888 bool use_hardware) {
1889 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001890
Kate Stoneb9c1b512016-09-06 20:57:50 +00001891 bool show_error = true;
1892 switch (GetState()) {
1893 case eStateInvalid:
1894 case eStateUnloaded:
1895 case eStateConnected:
1896 case eStateAttaching:
1897 case eStateLaunching:
1898 case eStateDetached:
1899 case eStateExited:
1900 show_error = false;
1901 break;
1902
1903 case eStateStopped:
1904 case eStateRunning:
1905 case eStateStepping:
1906 case eStateCrashed:
1907 case eStateSuspended:
1908 show_error = IsAlive();
1909 break;
1910 }
1911
1912 // Reset the IsIndirect flag here, in case the location changes from
1913 // pointing to a indirect symbol to a regular symbol.
1914 owner->SetIsIndirect(false);
1915
1916 if (owner->ShouldResolveIndirectFunctions()) {
1917 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1918 if (symbol && symbol->IsIndirect()) {
1919 Error error;
1920 Address symbol_address = symbol->GetAddress();
1921 load_addr = ResolveIndirectFunction(&symbol_address, error);
1922 if (!error.Success() && show_error) {
1923 GetTarget().GetDebugger().GetErrorFile()->Printf(
1924 "warning: failed to resolve indirect function at 0x%" PRIx64
1925 " for breakpoint %i.%i: %s\n",
1926 symbol->GetLoadAddress(&GetTarget()),
1927 owner->GetBreakpoint().GetID(), owner->GetID(),
1928 error.AsCString() ? error.AsCString() : "unknown error");
1929 return LLDB_INVALID_BREAK_ID;
1930 }
1931 Address resolved_address(load_addr);
1932 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1933 owner->SetIsIndirect(true);
1934 } else
1935 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1936 } else
1937 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1938
1939 if (load_addr != LLDB_INVALID_ADDRESS) {
1940 BreakpointSiteSP bp_site_sp;
1941
1942 // Look up this breakpoint site. If it exists, then add this new owner,
1943 // otherwise
1944 // create a new breakpoint site and add it.
1945
1946 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1947
1948 if (bp_site_sp) {
1949 bp_site_sp->AddOwner(owner);
1950 owner->SetBreakpointSite(bp_site_sp);
1951 return bp_site_sp->GetID();
1952 } else {
1953 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1954 load_addr, use_hardware));
1955 if (bp_site_sp) {
1956 Error error = EnableBreakpointSite(bp_site_sp.get());
1957 if (error.Success()) {
1958 owner->SetBreakpointSite(bp_site_sp);
1959 return m_breakpoint_site_list.Add(bp_site_sp);
1960 } else {
1961 if (show_error) {
1962 // Report error for setting breakpoint...
1963 GetTarget().GetDebugger().GetErrorFile()->Printf(
1964 "warning: failed to set breakpoint site at 0x%" PRIx64
1965 " for breakpoint %i.%i: %s\n",
1966 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1967 error.AsCString() ? error.AsCString() : "unknown error");
1968 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001969 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001970 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001971 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001972 }
1973 // We failed to enable the breakpoint
1974 return LLDB_INVALID_BREAK_ID;
1975}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001976
Kate Stoneb9c1b512016-09-06 20:57:50 +00001977void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1978 lldb::user_id_t owner_loc_id,
1979 BreakpointSiteSP &bp_site_sp) {
1980 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1981 if (num_owners == 0) {
1982 // Don't try to disable the site if we don't have a live process anymore.
1983 if (IsAlive())
1984 DisableBreakpointSite(bp_site_sp.get());
1985 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1986 }
1987}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001988
Kate Stoneb9c1b512016-09-06 20:57:50 +00001989size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1990 uint8_t *buf) const {
1991 size_t bytes_removed = 0;
1992 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001993
Kate Stoneb9c1b512016-09-06 20:57:50 +00001994 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1995 bp_sites_in_range)) {
1996 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](
1997 BreakpointSite *bp_site) -> void {
1998 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1999 addr_t intersect_addr;
2000 size_t intersect_size;
2001 size_t opcode_offset;
2002 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
2003 &intersect_size, &opcode_offset)) {
2004 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2005 assert(bp_addr < intersect_addr + intersect_size &&
2006 intersect_addr + intersect_size <= bp_addr + size);
2007 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
2008 size_t buf_offset = intersect_addr - bp_addr;
2009 ::memcpy(buf + buf_offset,
2010 bp_site->GetSavedOpcodeBytes() + opcode_offset,
2011 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002013 }
2014 });
2015 }
2016 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002017}
2018
Kate Stoneb9c1b512016-09-06 20:57:50 +00002019size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
2020 PlatformSP platform_sp(GetTarget().GetPlatform());
2021 if (platform_sp)
2022 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
2023 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002024}
2025
Kate Stoneb9c1b512016-09-06 20:57:50 +00002026Error Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
2027 Error error;
2028 assert(bp_site != nullptr);
2029 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2030 const addr_t bp_addr = bp_site->GetLoadAddress();
2031 if (log)
2032 log->Printf(
2033 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
2034 bp_site->GetID(), (uint64_t)bp_addr);
2035 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002036 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002037 log->Printf(
2038 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2039 " -- already enabled",
2040 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002041 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002042 }
2043
2044 if (bp_addr == LLDB_INVALID_ADDRESS) {
2045 error.SetErrorString("BreakpointSite contains an invalid load address.");
2046 return error;
2047 }
2048 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2049 // trap for the breakpoint site
2050 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2051
2052 if (bp_opcode_size == 0) {
2053 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2054 "returned zero, unable to get breakpoint "
2055 "trap for address 0x%" PRIx64,
2056 bp_addr);
2057 } else {
2058 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2059
2060 if (bp_opcode_bytes == nullptr) {
2061 error.SetErrorString(
2062 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2063 return error;
2064 }
2065
2066 // Save the original opcode by reading it
2067 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2068 error) == bp_opcode_size) {
2069 // Write a software breakpoint in place of the original opcode
2070 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2071 bp_opcode_size) {
2072 uint8_t verify_bp_opcode_bytes[64];
2073 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2074 error) == bp_opcode_size) {
2075 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2076 bp_opcode_size) == 0) {
2077 bp_site->SetEnabled(true);
2078 bp_site->SetType(BreakpointSite::eSoftware);
2079 if (log)
2080 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2081 "addr = 0x%" PRIx64 " -- SUCCESS",
2082 bp_site->GetID(), (uint64_t)bp_addr);
2083 } else
2084 error.SetErrorString(
2085 "failed to verify the breakpoint trap in memory.");
2086 } else
2087 error.SetErrorString(
2088 "Unable to read memory to verify breakpoint trap.");
2089 } else
2090 error.SetErrorString("Unable to write breakpoint trap to memory.");
2091 } else
2092 error.SetErrorString("Unable to read memory at breakpoint address.");
2093 }
2094 if (log && error.Fail())
2095 log->Printf(
2096 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2097 " -- FAILED: %s",
2098 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2099 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002100}
2101
Kate Stoneb9c1b512016-09-06 20:57:50 +00002102Error Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2103 Error error;
2104 assert(bp_site != nullptr);
2105 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2106 addr_t bp_addr = bp_site->GetLoadAddress();
2107 lldb::user_id_t breakID = bp_site->GetID();
2108 if (log)
2109 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2110 ") addr = 0x%" PRIx64,
2111 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002112
Kate Stoneb9c1b512016-09-06 20:57:50 +00002113 if (bp_site->IsHardware()) {
2114 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2115 } else if (bp_site->IsEnabled()) {
2116 const size_t break_op_size = bp_site->GetByteSize();
2117 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2118 if (break_op_size > 0) {
2119 // Clear a software breakpoint instruction
2120 uint8_t curr_break_op[8];
2121 assert(break_op_size <= sizeof(curr_break_op));
2122 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002123
Kate Stoneb9c1b512016-09-06 20:57:50 +00002124 // Read the breakpoint opcode
2125 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2126 break_op_size) {
2127 bool verify = false;
2128 // Make sure the breakpoint opcode exists at this address
2129 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2130 break_op_found = true;
2131 // We found a valid breakpoint opcode at this address, now restore
2132 // the saved opcode.
2133 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2134 break_op_size, error) == break_op_size) {
2135 verify = true;
2136 } else
2137 error.SetErrorString(
2138 "Memory write failed when restoring original opcode.");
2139 } else {
2140 error.SetErrorString(
2141 "Original breakpoint trap is no longer in memory.");
2142 // Set verify to true and so we can check if the original opcode has
2143 // already been restored
2144 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002146
Kate Stoneb9c1b512016-09-06 20:57:50 +00002147 if (verify) {
2148 uint8_t verify_opcode[8];
2149 assert(break_op_size < sizeof(verify_opcode));
2150 // Verify that our original opcode made it back to the inferior
2151 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2152 break_op_size) {
2153 // compare the memory we just read with the original opcode
2154 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2155 break_op_size) == 0) {
2156 // SUCCESS
2157 bp_site->SetEnabled(false);
2158 if (log)
2159 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2160 "addr = 0x%" PRIx64 " -- SUCCESS",
2161 bp_site->GetID(), (uint64_t)bp_addr);
2162 return error;
2163 } else {
2164 if (break_op_found)
2165 error.SetErrorString("Failed to restore original opcode.");
2166 }
2167 } else
2168 error.SetErrorString("Failed to read memory to verify that "
2169 "breakpoint trap was restored.");
2170 }
2171 } else
2172 error.SetErrorString(
2173 "Unable to read memory that should contain the breakpoint trap.");
2174 }
2175 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002176 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002177 log->Printf(
2178 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2179 " -- already disabled",
2180 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002181 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002182 }
2183
2184 if (log)
2185 log->Printf(
2186 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2187 " -- FAILED: %s",
2188 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2189 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002190}
2191
Greg Clayton58be07b2011-01-07 06:08:19 +00002192// Uncomment to verify memory caching works after making changes to caching code
2193//#define VERIFY_MEMORY_READS
2194
Kate Stoneb9c1b512016-09-06 20:57:50 +00002195size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Error &error) {
2196 error.Clear();
2197 if (!GetDisableMemoryCache()) {
2198#if defined(VERIFY_MEMORY_READS)
2199 // Memory caching is enabled, with debug verification
2200
2201 if (buf && size) {
2202 // Uncomment the line below to make sure memory caching is working.
2203 // I ran this through the test suite and got no assertions, so I am
2204 // pretty confident this is working well. If any changes are made to
2205 // memory caching, uncomment the line below and test your changes!
2206
2207 // Verify all memory reads by using the cache first, then redundantly
2208 // reading the same memory from the inferior and comparing to make sure
2209 // everything is exactly the same.
2210 std::string verify_buf(size, '\0');
2211 assert(verify_buf.size() == size);
2212 const size_t cache_bytes_read =
2213 m_memory_cache.Read(this, addr, buf, size, error);
2214 Error verify_error;
2215 const size_t verify_bytes_read =
2216 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2217 verify_buf.size(), verify_error);
2218 assert(cache_bytes_read == verify_bytes_read);
2219 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2220 assert(verify_error.Success() == error.Success());
2221 return cache_bytes_read;
2222 }
2223 return 0;
2224#else // !defined(VERIFY_MEMORY_READS)
2225 // Memory caching is enabled, without debug verification
2226
2227 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002228#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002229 } else {
2230 // Memory caching is disabled
2231
2232 return ReadMemoryFromInferior(addr, buf, size, error);
2233 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002234}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235
2236size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2237 Error &error) {
2238 char buf[256];
2239 out_str.clear();
2240 addr_t curr_addr = addr;
2241 while (true) {
2242 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2243 if (length == 0)
2244 break;
2245 out_str.append(buf, length);
2246 // If we got "length - 1" bytes, we didn't get the whole C string, we
2247 // need to read some more characters
2248 if (length == sizeof(buf) - 1)
2249 curr_addr += length;
2250 else
2251 break;
2252 }
2253 return out_str.size();
2254}
2255
2256size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
2257 Error &error, size_t type_width) {
2258 size_t total_bytes_read = 0;
2259 if (dst && max_bytes && type_width && max_bytes >= type_width) {
2260 // Ensure a null terminator independent of the number of bytes that is read.
2261 memset(dst, 0, max_bytes);
2262 size_t bytes_left = max_bytes - type_width;
2263
2264 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2265 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2266 "string with more than 4 bytes "
2267 "per character!");
2268
Greg Clayton4c82d422012-05-18 23:20:01 +00002269 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2271 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002272
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273 error.Clear();
2274 while (bytes_left > 0 && error.Success()) {
2275 addr_t cache_line_bytes_left =
2276 cache_line_size - (curr_addr % cache_line_size);
2277 addr_t bytes_to_read =
2278 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2279 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002280
Kate Stoneb9c1b512016-09-06 20:57:50 +00002281 if (bytes_read == 0)
2282 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002283
Kate Stoneb9c1b512016-09-06 20:57:50 +00002284 // Search for a null terminator of correct size and alignment in
2285 // bytes_read
2286 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2287 for (size_t i = aligned_start;
2288 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2289 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2290 error.Clear();
2291 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002292 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002293
2294 total_bytes_read += bytes_read;
2295 curr_dst += bytes_read;
2296 curr_addr += bytes_read;
2297 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002298 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002299 } else {
2300 if (max_bytes)
2301 error.SetErrorString("invalid arguments");
2302 }
2303 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002304}
2305
Kate Stoneb9c1b512016-09-06 20:57:50 +00002306// Deprecated in favor of ReadStringFromMemory which has wchar support and
2307// correct code to find
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002308// null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002309size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
2310 size_t dst_max_len, Error &result_error) {
2311 size_t total_cstr_len = 0;
2312 if (dst && dst_max_len) {
2313 result_error.Clear();
2314 // NULL out everything just to be safe
2315 memset(dst, 0, dst_max_len);
2316 Error error;
2317 addr_t curr_addr = addr;
2318 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2319 size_t bytes_left = dst_max_len - 1;
2320 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002321
Kate Stoneb9c1b512016-09-06 20:57:50 +00002322 while (bytes_left > 0) {
2323 addr_t cache_line_bytes_left =
2324 cache_line_size - (curr_addr % cache_line_size);
2325 addr_t bytes_to_read =
2326 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2327 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002328
Kate Stoneb9c1b512016-09-06 20:57:50 +00002329 if (bytes_read == 0) {
2330 result_error = error;
2331 dst[total_cstr_len] = '\0';
2332 break;
2333 }
2334 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002335
Kate Stoneb9c1b512016-09-06 20:57:50 +00002336 total_cstr_len += len;
2337
2338 if (len < bytes_to_read)
2339 break;
2340
2341 curr_dst += bytes_read;
2342 curr_addr += bytes_read;
2343 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002344 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002345 } else {
2346 if (dst == nullptr)
2347 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002348 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002349 result_error.Clear();
2350 }
2351 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002352}
2353
Kate Stoneb9c1b512016-09-06 20:57:50 +00002354size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2355 Error &error) {
2356 if (buf == nullptr || size == 0)
2357 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002358
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359 size_t bytes_read = 0;
2360 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002361
Kate Stoneb9c1b512016-09-06 20:57:50 +00002362 while (bytes_read < size) {
2363 const size_t curr_size = size - bytes_read;
2364 const size_t curr_bytes_read =
2365 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2366 bytes_read += curr_bytes_read;
2367 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2368 break;
2369 }
2370
2371 // Replace any software breakpoint opcodes that fall into this range back
2372 // into "buf" before we return
2373 if (bytes_read > 0)
2374 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2375 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376}
2377
Kate Stoneb9c1b512016-09-06 20:57:50 +00002378uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2379 size_t integer_byte_size,
2380 uint64_t fail_value,
2381 Error &error) {
2382 Scalar scalar;
2383 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2384 error))
2385 return scalar.ULongLong(fail_value);
2386 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002387}
2388
Kate Stoneb9c1b512016-09-06 20:57:50 +00002389int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2390 size_t integer_byte_size,
2391 int64_t fail_value, Error &error) {
2392 Scalar scalar;
2393 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2394 error))
2395 return scalar.SLongLong(fail_value);
2396 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002397}
2398
Kate Stoneb9c1b512016-09-06 20:57:50 +00002399addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error) {
2400 Scalar scalar;
2401 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2402 error))
2403 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2404 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002405}
2406
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
2408 Error &error) {
2409 Scalar scalar;
2410 const uint32_t addr_byte_size = GetAddressByteSize();
2411 if (addr_byte_size <= 4)
2412 scalar = (uint32_t)ptr_value;
2413 else
2414 scalar = ptr_value;
2415 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2416 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002417}
2418
Kate Stoneb9c1b512016-09-06 20:57:50 +00002419size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2420 Error &error) {
2421 size_t bytes_written = 0;
2422 const uint8_t *bytes = (const uint8_t *)buf;
2423
2424 while (bytes_written < size) {
2425 const size_t curr_size = size - bytes_written;
2426 const size_t curr_bytes_written = DoWriteMemory(
2427 addr + bytes_written, bytes + bytes_written, curr_size, error);
2428 bytes_written += curr_bytes_written;
2429 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2430 break;
2431 }
2432 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433}
2434
Kate Stoneb9c1b512016-09-06 20:57:50 +00002435size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2436 Error &error) {
2437#if defined(ENABLE_MEMORY_CACHING)
2438 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002439#endif
2440
Kate Stoneb9c1b512016-09-06 20:57:50 +00002441 if (buf == nullptr || size == 0)
2442 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002443
Kate Stoneb9c1b512016-09-06 20:57:50 +00002444 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002445
Kate Stoneb9c1b512016-09-06 20:57:50 +00002446 // We need to write any data that would go where any current software traps
2447 // (enabled software breakpoints) any software traps (breakpoints) that we
2448 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002449
Kate Stoneb9c1b512016-09-06 20:57:50 +00002450 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451
Kate Stoneb9c1b512016-09-06 20:57:50 +00002452 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2453 bp_sites_in_range)) {
2454 // No breakpoint sites overlap
2455 if (bp_sites_in_range.IsEmpty())
2456 return WriteMemoryPrivate(addr, buf, size, error);
2457 else {
2458 const uint8_t *ubuf = (const uint8_t *)buf;
2459 uint64_t bytes_written = 0;
2460
2461 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2462 &error](BreakpointSite *bp) -> void {
2463
2464 if (error.Success()) {
2465 addr_t intersect_addr;
2466 size_t intersect_size;
2467 size_t opcode_offset;
2468 const bool intersects = bp->IntersectsRange(
2469 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2470 UNUSED_IF_ASSERT_DISABLED(intersects);
2471 assert(intersects);
2472 assert(addr <= intersect_addr && intersect_addr < addr + size);
2473 assert(addr < intersect_addr + intersect_size &&
2474 intersect_addr + intersect_size <= addr + size);
2475 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2476
2477 // Check for bytes before this breakpoint
2478 const addr_t curr_addr = addr + bytes_written;
2479 if (intersect_addr > curr_addr) {
2480 // There are some bytes before this breakpoint that we need to
2481 // just write to memory
2482 size_t curr_size = intersect_addr - curr_addr;
2483 size_t curr_bytes_written = WriteMemoryPrivate(
2484 curr_addr, ubuf + bytes_written, curr_size, error);
2485 bytes_written += curr_bytes_written;
2486 if (curr_bytes_written != curr_size) {
2487 // We weren't able to write all of the requested bytes, we
2488 // are done looping and will return the number of bytes that
2489 // we have written so far.
2490 if (error.Success())
2491 error.SetErrorToGenericError();
2492 }
2493 }
2494 // Now write any bytes that would cover up any software breakpoints
2495 // directly into the breakpoint opcode buffer
2496 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2497 ubuf + bytes_written, intersect_size);
2498 bytes_written += intersect_size;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002499 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501
Kate Stoneb9c1b512016-09-06 20:57:50 +00002502 if (bytes_written < size)
2503 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2504 size - bytes_written, error);
2505 }
2506 } else {
2507 return WriteMemoryPrivate(addr, buf, size, error);
2508 }
2509
2510 // Write any remaining bytes after the last breakpoint if we have any left
2511 return 0; // bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002512}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002513
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2515 size_t byte_size, Error &error) {
2516 if (byte_size == UINT32_MAX)
2517 byte_size = scalar.GetByteSize();
2518 if (byte_size > 0) {
2519 uint8_t buf[32];
2520 const size_t mem_size =
2521 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2522 if (mem_size > 0)
2523 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002524 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002525 error.SetErrorString("failed to get scalar as memory data");
2526 } else {
2527 error.SetErrorString("invalid scalar value");
2528 }
2529 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002530}
2531
Kate Stoneb9c1b512016-09-06 20:57:50 +00002532size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2533 bool is_signed, Scalar &scalar,
2534 Error &error) {
2535 uint64_t uval = 0;
2536 if (byte_size == 0) {
2537 error.SetErrorString("byte size is zero");
2538 } else if (byte_size & (byte_size - 1)) {
2539 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2540 byte_size);
2541 } else if (byte_size <= sizeof(uval)) {
2542 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2543 if (bytes_read == byte_size) {
2544 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2545 GetAddressByteSize());
2546 lldb::offset_t offset = 0;
2547 if (byte_size <= 4)
2548 scalar = data.GetMaxU32(&offset, byte_size);
2549 else
2550 scalar = data.GetMaxU64(&offset, byte_size);
2551 if (is_signed)
2552 scalar.SignExtend(byte_size * 8);
2553 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002554 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002555 } else {
2556 error.SetErrorStringWithFormat(
2557 "byte size of %u is too large for integer scalar type", byte_size);
2558 }
2559 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002560}
2561
Greg Claytond495c532011-05-17 03:37:42 +00002562#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002563addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2564 Error &error) {
2565 if (GetPrivateState() != eStateStopped)
2566 return LLDB_INVALID_ADDRESS;
2567
2568#if defined(USE_ALLOCATE_MEMORY_CACHE)
2569 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002570#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002571 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2572 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2573 if (log)
2574 log->Printf("Process::AllocateMemory(size=%" PRIu64
2575 ", permissions=%s) => 0x%16.16" PRIx64
2576 " (m_stop_id = %u m_memory_id = %u)",
2577 (uint64_t)size, GetPermissionsAsCString(permissions),
2578 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2579 m_mod_id.GetMemoryID());
2580 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002581#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002582}
2583
Kate Stoneb9c1b512016-09-06 20:57:50 +00002584addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2585 Error &error) {
2586 addr_t return_addr = AllocateMemory(size, permissions, error);
2587 if (error.Success()) {
2588 std::string buffer(size, 0);
2589 WriteMemory(return_addr, buffer.c_str(), size, error);
2590 }
2591 return return_addr;
2592}
2593
2594bool Process::CanJIT() {
2595 if (m_can_jit == eCanJITDontKnow) {
2596 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2597 Error err;
2598
2599 uint64_t allocated_memory = AllocateMemory(
2600 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2601 err);
2602
2603 if (err.Success()) {
2604 m_can_jit = eCanJITYes;
2605 if (log)
2606 log->Printf("Process::%s pid %" PRIu64
2607 " allocation test passed, CanJIT () is true",
2608 __FUNCTION__, GetID());
2609 } else {
2610 m_can_jit = eCanJITNo;
2611 if (log)
2612 log->Printf("Process::%s pid %" PRIu64
2613 " allocation test failed, CanJIT () is false: %s",
2614 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002615 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002616
2617 DeallocateMemory(allocated_memory);
2618 }
2619
2620 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002621}
2622
Kate Stoneb9c1b512016-09-06 20:57:50 +00002623void Process::SetCanJIT(bool can_jit) {
2624 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002625}
2626
Kate Stoneb9c1b512016-09-06 20:57:50 +00002627void Process::SetCanRunCode(bool can_run_code) {
2628 SetCanJIT(can_run_code);
2629 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002630}
2631
Kate Stoneb9c1b512016-09-06 20:57:50 +00002632Error Process::DeallocateMemory(addr_t ptr) {
2633 Error error;
2634#if defined(USE_ALLOCATE_MEMORY_CACHE)
2635 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2636 error.SetErrorStringWithFormat(
2637 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2638 }
Greg Claytond495c532011-05-17 03:37:42 +00002639#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002640 error = DoDeallocateMemory(ptr);
2641
2642 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2643 if (log)
2644 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2645 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2646 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2647 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002648#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002649 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002650}
2651
Kate Stoneb9c1b512016-09-06 20:57:50 +00002652ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2653 lldb::addr_t header_addr,
2654 size_t size_to_read) {
2655 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2656 if (log) {
2657 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2658 file_spec.GetPath().c_str());
2659 }
2660 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2661 if (module_sp) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002662 Error error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002663 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2664 shared_from_this(), header_addr, error, size_to_read);
2665 if (objfile)
2666 return module_sp;
2667 }
2668 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002669}
2670
Kate Stoneb9c1b512016-09-06 20:57:50 +00002671bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2672 uint32_t &permissions) {
2673 MemoryRegionInfo range_info;
2674 permissions = 0;
2675 Error error(GetMemoryRegionInfo(load_addr, range_info));
2676 if (!error.Success())
2677 return false;
2678 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2679 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2680 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2681 return false;
2682 }
2683
2684 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2685 permissions |= lldb::ePermissionsReadable;
2686
2687 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2688 permissions |= lldb::ePermissionsWritable;
2689
2690 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2691 permissions |= lldb::ePermissionsExecutable;
2692
2693 return true;
2694}
2695
2696Error Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2697 Error error;
2698 error.SetErrorString("watchpoints are not supported");
2699 return error;
2700}
2701
2702Error Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2703 Error error;
2704 error.SetErrorString("watchpoints are not supported");
2705 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002706}
2707
2708StateType
Kate Stoneb9c1b512016-09-06 20:57:50 +00002709Process::WaitForProcessStopPrivate(const std::chrono::microseconds &timeout,
2710 EventSP &event_sp) {
2711 StateType state;
2712 // Now wait for the process to launch and return control to us, and then
2713 // call DidLaunch:
2714 while (true) {
2715 event_sp.reset();
2716 state = WaitForStateChangedEventsPrivate(timeout, event_sp);
Greg Clayton6779606a2011-01-22 23:43:18 +00002717
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718 if (StateIsStoppedState(state, false))
2719 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002720
Kate Stoneb9c1b512016-09-06 20:57:50 +00002721 // If state is invalid, then we timed out
2722 if (state == eStateInvalid)
2723 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002724
Kate Stoneb9c1b512016-09-06 20:57:50 +00002725 if (event_sp)
2726 HandlePrivateEvent(event_sp);
2727 }
2728 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002729}
2730
Kate Stoneb9c1b512016-09-06 20:57:50 +00002731void Process::LoadOperatingSystemPlugin(bool flush) {
2732 if (flush)
2733 m_thread_list.Clear();
2734 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2735 if (flush)
2736 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002737}
2738
Kate Stoneb9c1b512016-09-06 20:57:50 +00002739Error Process::Launch(ProcessLaunchInfo &launch_info) {
2740 Error error;
2741 m_abi_sp.reset();
2742 m_dyld_ap.reset();
2743 m_jit_loaders_ap.reset();
2744 m_system_runtime_ap.reset();
2745 m_os_ap.reset();
2746 m_process_input_reader.reset();
2747 m_stop_info_override_callback = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002748
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749 Module *exe_module = GetTarget().GetExecutableModulePointer();
2750 if (exe_module) {
2751 char local_exec_file_path[PATH_MAX];
2752 char platform_exec_file_path[PATH_MAX];
2753 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2754 sizeof(local_exec_file_path));
2755 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2756 sizeof(platform_exec_file_path));
2757 if (exe_module->GetFileSpec().Exists()) {
2758 // Install anything that might need to be installed prior to launching.
2759 // For host systems, this will do nothing, but if we are connected to a
2760 // remote platform it will install any needed binaries
2761 error = GetTarget().Install(&launch_info);
2762 if (error.Fail())
2763 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002764
Kate Stoneb9c1b512016-09-06 20:57:50 +00002765 if (PrivateStateThreadIsValid())
2766 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002767
Kate Stoneb9c1b512016-09-06 20:57:50 +00002768 error = WillLaunch(exe_module);
2769 if (error.Success()) {
2770 const bool restarted = false;
2771 SetPublicState(eStateLaunching, restarted);
2772 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773
Kate Stoneb9c1b512016-09-06 20:57:50 +00002774 if (m_public_run_lock.TrySetRunning()) {
2775 // Now launch using these arguments.
2776 error = DoLaunch(exe_module, launch_info);
2777 } else {
2778 // This shouldn't happen
2779 error.SetErrorString("failed to acquire process run lock");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002780 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002781
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782 if (error.Fail()) {
2783 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2784 SetID(LLDB_INVALID_PROCESS_ID);
2785 const char *error_string = error.AsCString();
2786 if (error_string == nullptr)
2787 error_string = "launch failed";
2788 SetExitStatus(-1, error_string);
2789 }
2790 } else {
2791 EventSP event_sp;
2792 StateType state =
2793 WaitForProcessStopPrivate(std::chrono::seconds(10), event_sp);
Greg Clayton35824e32015-02-20 20:59:47 +00002794
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 if (state == eStateInvalid || !event_sp) {
2796 // We were able to launch the process, but we failed to
2797 // catch the initial stop.
2798 error.SetErrorString("failed to catch stop after launch");
2799 SetExitStatus(0, "failed to catch stop after launch");
2800 Destroy(false);
2801 } else if (state == eStateStopped || state == eStateCrashed) {
2802 DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002803
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 DynamicLoader *dyld = GetDynamicLoader();
2805 if (dyld)
2806 dyld->DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002807
Kate Stoneb9c1b512016-09-06 20:57:50 +00002808 GetJITLoaders().DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002809
Kate Stoneb9c1b512016-09-06 20:57:50 +00002810 SystemRuntime *system_runtime = GetSystemRuntime();
2811 if (system_runtime)
2812 system_runtime->DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002813
Kate Stoneb9c1b512016-09-06 20:57:50 +00002814 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002815
Kate Stoneb9c1b512016-09-06 20:57:50 +00002816 // Note, the stop event was consumed above, but not handled. This
2817 // was done
2818 // to give DidLaunch a chance to run. The target is either stopped
2819 // or crashed.
2820 // Directly set the state. This is done to prevent a stop message
2821 // with a bunch
2822 // of spurious output on thread status, as well as not pop a
2823 // ProcessIOHandler.
2824 SetPublicState(state, false);
Greg Claytonc3776bf2012-02-09 06:16:32 +00002825
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 if (PrivateStateThreadIsValid())
2827 ResumePrivateStateThread();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002828 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002829 StartPrivateStateThread();
Todd Fiala76e0fc92014-08-27 22:58:26 +00002830
Kate Stoneb9c1b512016-09-06 20:57:50 +00002831 m_stop_info_override_callback =
2832 GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002833
Kate Stoneb9c1b512016-09-06 20:57:50 +00002834 // Target was stopped at entry as was intended. Need to notify the
2835 // listeners
2836 // about it.
2837 if (state == eStateStopped &&
2838 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2839 HandlePrivateEvent(event_sp);
2840 } else if (state == eStateExited) {
2841 // We exited while trying to launch somehow. Don't call DidLaunch
2842 // as that's
2843 // not likely to work, and return an invalid pid.
2844 HandlePrivateEvent(event_sp);
2845 }
2846 }
2847 }
2848 } else {
2849 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2850 local_exec_file_path);
Jim Inghambb3a2832011-01-29 01:49:25 +00002851 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002852 }
2853 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002854}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002855
Kate Stoneb9c1b512016-09-06 20:57:50 +00002856Error Process::LoadCore() {
2857 Error error = DoLoadCore();
2858 if (error.Success()) {
2859 ListenerSP listener_sp(
2860 Listener::MakeListener("lldb.process.load_core_listener"));
2861 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002862
Kate Stoneb9c1b512016-09-06 20:57:50 +00002863 if (PrivateStateThreadIsValid())
2864 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002865 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002867
Kate Stoneb9c1b512016-09-06 20:57:50 +00002868 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002869 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002870 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002871
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002872 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002873
Kate Stoneb9c1b512016-09-06 20:57:50 +00002874 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002875 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002877
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002878 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002879 // We successfully loaded a core file, now pretend we stopped so we can
2880 // show all of the threads in the core file and explore the crashed
2881 // state.
2882 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002883
Kate Stoneb9c1b512016-09-06 20:57:50 +00002884 // Wait indefinitely for a stopped event since we just posted one above...
2885 lldb::EventSP event_sp;
2886 listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp);
2887 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2888
2889 if (!StateIsStoppedState(state, false)) {
2890 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2891 if (log)
2892 log->Printf("Process::Halt() failed to stop, state is: %s",
2893 StateAsCString(state));
2894 error.SetErrorString(
2895 "Did not get stopped event after loading the core file.");
2896 }
2897 RestoreProcessEvents();
2898 }
2899 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002900}
2901
Kate Stoneb9c1b512016-09-06 20:57:50 +00002902DynamicLoader *Process::GetDynamicLoader() {
2903 if (!m_dyld_ap)
2904 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2905 return m_dyld_ap.get();
2906}
2907
2908const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2909
2910JITLoaderList &Process::GetJITLoaders() {
2911 if (!m_jit_loaders_ap) {
2912 m_jit_loaders_ap.reset(new JITLoaderList());
2913 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2914 }
2915 return *m_jit_loaders_ap;
2916}
2917
2918SystemRuntime *Process::GetSystemRuntime() {
2919 if (!m_system_runtime_ap)
2920 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2921 return m_system_runtime_ap.get();
2922}
2923
2924Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2925 uint32_t exec_count)
2926 : NextEventAction(process), m_exec_count(exec_count) {
2927 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2928 if (log)
2929 log->Printf(
2930 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2931 __FUNCTION__, static_cast<void *>(process), exec_count);
2932}
2933
2934Process::NextEventAction::EventActionResult
2935Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2936 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2937
2938 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2939 if (log)
2940 log->Printf(
2941 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2942 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2943
2944 switch (state) {
2945 case eStateAttaching:
2946 return eEventActionSuccess;
2947
2948 case eStateRunning:
2949 case eStateConnected:
2950 return eEventActionRetry;
2951
2952 case eStateStopped:
2953 case eStateCrashed:
2954 // During attach, prior to sending the eStateStopped event,
2955 // lldb_private::Process subclasses must set the new process ID.
2956 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2957 // We don't want these events to be reported, so go set the ShouldReportStop
2958 // here:
2959 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2960
2961 if (m_exec_count > 0) {
2962 --m_exec_count;
2963
2964 if (log)
2965 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2966 "remaining exec count to %" PRIu32 ", requesting resume",
2967 __FUNCTION__, StateAsCString(state), m_exec_count);
2968
2969 RequestResume();
2970 return eEventActionRetry;
2971 } else {
2972 if (log)
2973 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2974 "execs expected to start, continuing with attach",
2975 __FUNCTION__, StateAsCString(state));
2976
2977 m_process->CompleteAttach();
2978 return eEventActionSuccess;
2979 }
2980 break;
2981
2982 default:
2983 case eStateExited:
2984 case eStateInvalid:
2985 break;
2986 }
2987
2988 m_exit_string.assign("No valid Process");
2989 return eEventActionExit;
2990}
2991
2992Process::NextEventAction::EventActionResult
2993Process::AttachCompletionHandler::HandleBeingInterrupted() {
2994 return eEventActionSuccess;
2995}
2996
2997const char *Process::AttachCompletionHandler::GetExitString() {
2998 return m_exit_string.c_str();
2999}
3000
3001ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
3002 if (m_listener_sp)
3003 return m_listener_sp;
3004 else
3005 return debugger.GetListener();
3006}
3007
3008Error Process::Attach(ProcessAttachInfo &attach_info) {
3009 m_abi_sp.reset();
3010 m_process_input_reader.reset();
3011 m_dyld_ap.reset();
3012 m_jit_loaders_ap.reset();
3013 m_system_runtime_ap.reset();
3014 m_os_ap.reset();
3015 m_stop_info_override_callback = nullptr;
3016
3017 lldb::pid_t attach_pid = attach_info.GetProcessID();
3018 Error error;
3019 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
3020 char process_name[PATH_MAX];
3021
3022 if (attach_info.GetExecutableFile().GetPath(process_name,
3023 sizeof(process_name))) {
3024 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3025
3026 if (wait_for_launch) {
3027 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3028 if (error.Success()) {
3029 if (m_public_run_lock.TrySetRunning()) {
3030 m_should_detach = true;
3031 const bool restarted = false;
3032 SetPublicState(eStateAttaching, restarted);
3033 // Now attach using these arguments.
3034 error = DoAttachToProcessWithName(process_name, attach_info);
3035 } else {
3036 // This shouldn't happen
3037 error.SetErrorString("failed to acquire process run lock");
3038 }
3039
3040 if (error.Fail()) {
3041 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3042 SetID(LLDB_INVALID_PROCESS_ID);
3043 if (error.AsCString() == nullptr)
3044 error.SetErrorString("attach failed");
3045
3046 SetExitStatus(-1, error.AsCString());
3047 }
3048 } else {
3049 SetNextEventAction(new Process::AttachCompletionHandler(
3050 this, attach_info.GetResumeCount()));
3051 StartPrivateStateThread();
3052 }
3053 return error;
3054 }
3055 } else {
3056 ProcessInstanceInfoList process_infos;
3057 PlatformSP platform_sp(GetTarget().GetPlatform());
3058
3059 if (platform_sp) {
3060 ProcessInstanceInfoMatch match_info;
3061 match_info.GetProcessInfo() = attach_info;
3062 match_info.SetNameMatchType(eNameMatchEquals);
3063 platform_sp->FindProcesses(match_info, process_infos);
3064 const uint32_t num_matches = process_infos.GetSize();
3065 if (num_matches == 1) {
3066 attach_pid = process_infos.GetProcessIDAtIndex(0);
3067 // Fall through and attach using the above process ID
3068 } else {
3069 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3070 process_name, sizeof(process_name));
3071 if (num_matches > 1) {
3072 StreamString s;
3073 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3074 false);
3075 for (size_t i = 0; i < num_matches; i++) {
3076 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3077 s, platform_sp.get(), true, false);
3078 }
3079 error.SetErrorStringWithFormat(
3080 "more than one process named %s:\n%s", process_name,
3081 s.GetData());
3082 } else
3083 error.SetErrorStringWithFormat(
3084 "could not find a process named %s", process_name);
3085 }
3086 } else {
3087 error.SetErrorString(
3088 "invalid platform, can't find processes by name");
3089 return error;
3090 }
3091 }
3092 } else {
3093 error.SetErrorString("invalid process name");
3094 }
3095 }
3096
3097 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3098 error = WillAttachToProcessWithID(attach_pid);
3099 if (error.Success()) {
3100
3101 if (m_public_run_lock.TrySetRunning()) {
3102 // Now attach using these arguments.
3103 m_should_detach = true;
3104 const bool restarted = false;
3105 SetPublicState(eStateAttaching, restarted);
3106 error = DoAttachToProcessWithID(attach_pid, attach_info);
3107 } else {
3108 // This shouldn't happen
3109 error.SetErrorString("failed to acquire process run lock");
3110 }
3111
3112 if (error.Success()) {
3113 SetNextEventAction(new Process::AttachCompletionHandler(
3114 this, attach_info.GetResumeCount()));
3115 StartPrivateStateThread();
3116 } else {
Greg Clayton71337622011-02-24 22:24:29 +00003117 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003118 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003119
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120 const char *error_string = error.AsCString();
3121 if (error_string == nullptr)
3122 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00003123
Kate Stoneb9c1b512016-09-06 20:57:50 +00003124 SetExitStatus(-1, error_string);
3125 }
Greg Claytonb766a732011-02-04 01:58:07 +00003126 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003127 }
3128 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00003129}
3130
Kate Stoneb9c1b512016-09-06 20:57:50 +00003131void Process::CompleteAttach() {
3132 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3133 LIBLLDB_LOG_TARGET));
3134 if (log)
3135 log->Printf("Process::%s()", __FUNCTION__);
3136
3137 // Let the process subclass figure out at much as it can about the process
3138 // before we go looking for a dynamic loader plug-in.
3139 ArchSpec process_arch;
3140 DidAttach(process_arch);
3141
3142 if (process_arch.IsValid()) {
3143 GetTarget().SetArchitecture(process_arch);
3144 if (log) {
3145 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3146 log->Printf("Process::%s replacing process architecture with DidAttach() "
3147 "architecture: %s",
3148 __FUNCTION__, triple_str ? triple_str : "<null>");
3149 }
3150 }
3151
3152 // We just attached. If we have a platform, ask it for the process
3153 // architecture, and if it isn't
3154 // the same as the one we've already set, switch architectures.
3155 PlatformSP platform_sp(GetTarget().GetPlatform());
3156 assert(platform_sp);
3157 if (platform_sp) {
3158 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3159 if (target_arch.IsValid() &&
3160 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3161 ArchSpec platform_arch;
3162 platform_sp =
3163 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3164 if (platform_sp) {
3165 GetTarget().SetPlatform(platform_sp);
3166 GetTarget().SetArchitecture(platform_arch);
3167 if (log)
3168 log->Printf("Process::%s switching platform to %s and architecture "
3169 "to %s based on info from attach",
3170 __FUNCTION__, platform_sp->GetName().AsCString(""),
3171 platform_arch.GetTriple().getTriple().c_str());
3172 }
3173 } else if (!process_arch.IsValid()) {
3174 ProcessInstanceInfo process_info;
3175 GetProcessInfo(process_info);
3176 const ArchSpec &process_arch = process_info.GetArchitecture();
3177 if (process_arch.IsValid() &&
3178 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3179 GetTarget().SetArchitecture(process_arch);
3180 if (log)
3181 log->Printf("Process::%s switching architecture to %s based on info "
3182 "the platform retrieved for pid %" PRIu64,
3183 __FUNCTION__,
3184 process_arch.GetTriple().getTriple().c_str(), GetID());
3185 }
3186 }
3187 }
3188
3189 // We have completed the attach, now it is time to find the dynamic loader
3190 // plug-in
3191 DynamicLoader *dyld = GetDynamicLoader();
3192 if (dyld) {
3193 dyld->DidAttach();
3194 if (log) {
3195 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3196 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3197 "executable is %s (using %s plugin)",
3198 __FUNCTION__,
3199 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3200 : "<none>",
3201 dyld->GetPluginName().AsCString("<unnamed>"));
3202 }
3203 }
3204
3205 GetJITLoaders().DidAttach();
3206
3207 SystemRuntime *system_runtime = GetSystemRuntime();
3208 if (system_runtime) {
3209 system_runtime->DidAttach();
3210 if (log) {
3211 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3212 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3213 "executable is %s (using %s plugin)",
3214 __FUNCTION__,
3215 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3216 : "<none>",
3217 system_runtime->GetPluginName().AsCString("<unnamed>"));
3218 }
3219 }
3220
3221 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
3222 // Figure out which one is the executable, and set that in our target:
3223 const ModuleList &target_modules = GetTarget().GetImages();
3224 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3225 size_t num_modules = target_modules.GetSize();
3226 ModuleSP new_executable_module_sp;
3227
3228 for (size_t i = 0; i < num_modules; i++) {
3229 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3230 if (module_sp && module_sp->IsExecutable()) {
3231 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3232 new_executable_module_sp = module_sp;
3233 break;
3234 }
3235 }
3236 if (new_executable_module_sp) {
3237 GetTarget().SetExecutableModule(new_executable_module_sp, false);
3238 if (log) {
3239 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3240 log->Printf(
3241 "Process::%s after looping through modules, target executable is %s",
3242 __FUNCTION__,
3243 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3244 : "<none>");
3245 }
3246 }
3247
3248 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
3249}
3250
3251Error Process::ConnectRemote(Stream *strm, const char *remote_url) {
3252 m_abi_sp.reset();
3253 m_process_input_reader.reset();
3254
3255 // Find the process and its architecture. Make sure it matches the
3256 // architecture
3257 // of the current Target, and if not adjust it.
3258
3259 Error error(DoConnectRemote(strm, remote_url));
3260 if (error.Success()) {
3261 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3262 EventSP event_sp;
3263 StateType state =
3264 WaitForProcessStopPrivate(std::chrono::microseconds(0), event_sp);
3265
3266 if (state == eStateStopped || state == eStateCrashed) {
3267 // If we attached and actually have a process on the other end, then
3268 // this ended up being the equivalent of an attach.
3269 CompleteAttach();
3270
3271 // This delays passing the stopped event to listeners till
3272 // CompleteAttach gets a chance to complete...
3273 HandlePrivateEvent(event_sp);
3274 }
3275 }
3276
3277 if (PrivateStateThreadIsValid())
3278 ResumePrivateStateThread();
3279 else
3280 StartPrivateStateThread();
3281 }
3282 return error;
3283}
3284
3285Error Process::PrivateResume() {
3286 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3287 LIBLLDB_LOG_STEP));
3288 if (log)
3289 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3290 "private state: %s",
3291 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3292 StateAsCString(m_private_state.GetValue()));
3293
3294 Error error(WillResume());
3295 // Tell the process it is about to resume before the thread list
3296 if (error.Success()) {
3297 // Now let the thread list know we are about to resume so it
3298 // can let all of our threads know that they are about to be
3299 // resumed. Threads will each be called with
3300 // Thread::WillResume(StateType) where StateType contains the state
3301 // that they are supposed to have when the process is resumed
3302 // (suspended/running/stepping). Threads should also check
3303 // their resume signal in lldb::Thread::GetResumeSignal()
3304 // to see if they are supposed to start back up with a signal.
3305 if (m_thread_list.WillResume()) {
3306 // Last thing, do the PreResumeActions.
3307 if (!RunPreResumeActions()) {
3308 error.SetErrorStringWithFormat(
3309 "Process::PrivateResume PreResumeActions failed, not resuming.");
3310 } else {
3311 m_mod_id.BumpResumeID();
3312 error = DoResume();
3313 if (error.Success()) {
3314 DidResume();
3315 m_thread_list.DidResume();
3316 if (log)
3317 log->Printf("Process thinks the process has resumed.");
3318 }
3319 }
3320 } else {
3321 // Somebody wanted to run without running (e.g. we were faking a step from
3322 // one frame of a set of inlined
3323 // frames that share the same PC to another.) So generate a continue & a
3324 // stopped event,
3325 // and let the world handle them.
3326 if (log)
3327 log->Printf(
3328 "Process::PrivateResume() asked to simulate a start & stop.");
3329
3330 SetPrivateState(eStateRunning);
3331 SetPrivateState(eStateStopped);
3332 }
3333 } else if (log)
3334 log->Printf("Process::PrivateResume() got an error \"%s\".",
3335 error.AsCString("<unknown error>"));
3336 return error;
3337}
3338
3339Error Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3340 if (!StateIsRunningState(m_public_state.GetValue()))
3341 return Error("Process is not running.");
3342
3343 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3344 // in case it was already set and some thread plan logic calls halt on its
3345 // own.
3346 m_clear_thread_plans_on_stop |= clear_thread_plans;
3347
3348 ListenerSP halt_listener_sp(
3349 Listener::MakeListener("lldb.process.halt_listener"));
3350 HijackProcessEvents(halt_listener_sp);
3351
3352 EventSP event_sp;
3353
3354 SendAsyncInterrupt();
3355
3356 if (m_public_state.GetValue() == eStateAttaching) {
3357 // Don't hijack and eat the eStateExited as the code that was doing
3358 // the attach will be waiting for this event...
3359 RestoreProcessEvents();
3360 SetExitStatus(SIGKILL, "Cancelled async attach.");
3361 Destroy(false);
3362 return Error();
3363 }
3364
3365 // Wait for 10 second for the process to stop.
3366 StateType state =
3367 WaitForProcessToStop(std::chrono::seconds(10), &event_sp, true,
3368 halt_listener_sp, nullptr, use_run_lock);
3369 RestoreProcessEvents();
3370
3371 if (state == eStateInvalid || !event_sp) {
3372 // We timed out and didn't get a stop event...
3373 return Error("Halt timed out. State = %s", StateAsCString(GetState()));
3374 }
3375
3376 BroadcastEvent(event_sp);
3377
3378 return Error();
3379}
3380
3381Error Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3382 Error error;
3383
3384 // Check both the public & private states here. If we're hung evaluating an
3385 // expression, for instance, then
3386 // the public state will be stopped, but we still need to interrupt.
3387 if (m_public_state.GetValue() == eStateRunning ||
3388 m_private_state.GetValue() == eStateRunning) {
3389 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003390 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003391 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003392
Kate Stoneb9c1b512016-09-06 20:57:50 +00003393 ListenerSP listener_sp(
3394 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3395 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003396
Pavel Labath19da1f12015-12-07 12:36:52 +00003397 SendAsyncInterrupt();
3398
Kate Stoneb9c1b512016-09-06 20:57:50 +00003399 // Consume the interrupt event.
3400 StateType state = WaitForProcessToStop(std::chrono::seconds(10),
3401 &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003402
Pavel Labath19da1f12015-12-07 12:36:52 +00003403 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003404
Kate Stoneb9c1b512016-09-06 20:57:50 +00003405 // If the process exited while we were waiting for it to stop, put the
3406 // exited event into
3407 // the shared pointer passed in and return. Our caller doesn't need to do
3408 // anything else, since
3409 // they don't have a process anymore...
3410
3411 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3412 if (log)
3413 log->Printf("Process::%s() Process exited while waiting to stop.",
3414 __FUNCTION__);
3415 return error;
3416 } else
3417 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3418
3419 if (state != eStateStopped) {
3420 if (log)
3421 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3422 StateAsCString(state));
3423 // If we really couldn't stop the process then we should just error out
3424 // here, but if the
3425 // lower levels just bobbled sending the event and we really are stopped,
3426 // then continue on.
3427 StateType private_state = m_private_state.GetValue();
3428 if (private_state != eStateStopped) {
3429 return Error("Attempt to stop the target in order to detach timed out. "
3430 "State = %s",
3431 StateAsCString(GetState()));
3432 }
3433 }
3434 }
3435 return error;
3436}
3437
3438Error Process::Detach(bool keep_stopped) {
3439 EventSP exit_event_sp;
3440 Error error;
3441 m_destroy_in_process = true;
3442
3443 error = WillDetach();
3444
3445 if (error.Success()) {
3446 if (DetachRequiresHalt()) {
3447 error = StopForDestroyOrDetach(exit_event_sp);
3448 if (!error.Success()) {
3449 m_destroy_in_process = false;
3450 return error;
3451 } else if (exit_event_sp) {
3452 // We shouldn't need to do anything else here. There's no process left
3453 // to detach from...
3454 StopPrivateStateThread();
3455 m_destroy_in_process = false;
3456 return error;
3457 }
3458 }
3459
3460 m_thread_list.DiscardThreadPlans();
3461 DisableAllBreakpointSites();
3462
3463 error = DoDetach(keep_stopped);
3464 if (error.Success()) {
3465 DidDetach();
3466 StopPrivateStateThread();
3467 } else {
3468 return error;
3469 }
3470 }
3471 m_destroy_in_process = false;
3472
3473 // If we exited when we were waiting for a process to stop, then
3474 // forward the event here so we don't lose the event
3475 if (exit_event_sp) {
3476 // Directly broadcast our exited event because we shut down our
3477 // private state thread above
3478 BroadcastEvent(exit_event_sp);
3479 }
3480
3481 // If we have been interrupted (to kill us) in the middle of running, we may
3482 // not end up propagating
3483 // the last events through the event system, in which case we might strand the
3484 // write lock. Unlock
3485 // it here so when we do to tear down the process we don't get an error
3486 // destroying the lock.
3487
3488 m_public_run_lock.SetStopped();
3489 return error;
3490}
3491
3492Error Process::Destroy(bool force_kill) {
3493
3494 // Tell ourselves we are in the process of destroying the process, so that we
3495 // don't do any unnecessary work
3496 // that might hinder the destruction. Remember to set this back to false when
3497 // we are done. That way if the attempt
3498 // failed and the process stays around for some reason it won't be in a
3499 // confused state.
3500
3501 if (force_kill)
3502 m_should_detach = false;
3503
3504 if (GetShouldDetach()) {
3505 // FIXME: This will have to be a process setting:
3506 bool keep_stopped = false;
3507 Detach(keep_stopped);
3508 }
3509
3510 m_destroy_in_process = true;
3511
3512 Error error(WillDestroy());
3513 if (error.Success()) {
3514 EventSP exit_event_sp;
3515 if (DestroyRequiresHalt()) {
3516 error = StopForDestroyOrDetach(exit_event_sp);
3517 }
3518
3519 if (m_public_state.GetValue() != eStateRunning) {
3520 // Ditch all thread plans, and remove all our breakpoints: in case we have
3521 // to restart the target to
3522 // kill it, we don't want it hitting a breakpoint...
3523 // Only do this if we've stopped, however, since if we didn't manage to
3524 // halt it above, then
3525 // we're not going to have much luck doing this now.
3526 m_thread_list.DiscardThreadPlans();
3527 DisableAllBreakpointSites();
3528 }
3529
3530 error = DoDestroy();
3531 if (error.Success()) {
3532 DidDestroy();
3533 StopPrivateStateThread();
3534 }
3535 m_stdio_communication.Disconnect();
3536 m_stdio_communication.StopReadThread();
3537 m_stdin_forward = false;
3538
3539 if (m_process_input_reader) {
3540 m_process_input_reader->SetIsDone(true);
3541 m_process_input_reader->Cancel();
3542 m_process_input_reader.reset();
3543 }
3544
3545 // If we exited when we were waiting for a process to stop, then
3546 // forward the event here so we don't lose the event
3547 if (exit_event_sp) {
3548 // Directly broadcast our exited event because we shut down our
3549 // private state thread above
3550 BroadcastEvent(exit_event_sp);
3551 }
3552
3553 // If we have been interrupted (to kill us) in the middle of running, we may
3554 // not end up propagating
3555 // the last events through the event system, in which case we might strand
3556 // the write lock. Unlock
3557 // it here so when we do to tear down the process we don't get an error
3558 // destroying the lock.
3559 m_public_run_lock.SetStopped();
3560 }
3561
3562 m_destroy_in_process = false;
3563
3564 return error;
3565}
3566
3567Error Process::Signal(int signal) {
3568 Error error(WillSignal());
3569 if (error.Success()) {
3570 error = DoSignal(signal);
3571 if (error.Success())
3572 DidSignal();
3573 }
3574 return error;
3575}
3576
3577void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3578 assert(signals_sp && "null signals_sp");
3579 m_unix_signals_sp = signals_sp;
3580}
3581
3582const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3583 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3584 return m_unix_signals_sp;
3585}
3586
3587lldb::ByteOrder Process::GetByteOrder() const {
3588 return GetTarget().GetArchitecture().GetByteOrder();
3589}
3590
3591uint32_t Process::GetAddressByteSize() const {
3592 return GetTarget().GetArchitecture().GetAddressByteSize();
3593}
3594
3595bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3596 const StateType state =
3597 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3598 bool return_value = true;
3599 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3600 LIBLLDB_LOG_PROCESS));
3601
3602 switch (state) {
3603 case eStateDetached:
3604 case eStateExited:
3605 case eStateUnloaded:
3606 m_stdio_communication.SynchronizeWithReadThread();
3607 m_stdio_communication.Disconnect();
3608 m_stdio_communication.StopReadThread();
3609 m_stdin_forward = false;
3610
3611 LLVM_FALLTHROUGH;
3612 case eStateConnected:
3613 case eStateAttaching:
3614 case eStateLaunching:
3615 // These events indicate changes in the state of the debugging session,
3616 // always report them.
3617 return_value = true;
3618 break;
3619 case eStateInvalid:
3620 // We stopped for no apparent reason, don't report it.
3621 return_value = false;
3622 break;
3623 case eStateRunning:
3624 case eStateStepping:
3625 // If we've started the target running, we handle the cases where we
3626 // are already running and where there is a transition from stopped to
3627 // running differently.
3628 // running -> running: Automatically suppress extra running events
3629 // stopped -> running: Report except when there is one or more no votes
3630 // and no yes votes.
3631 SynchronouslyNotifyStateChanged(state);
3632 if (m_force_next_event_delivery)
3633 return_value = true;
3634 else {
3635 switch (m_last_broadcast_state) {
3636 case eStateRunning:
3637 case eStateStepping:
3638 // We always suppress multiple runnings with no PUBLIC stop in between.
3639 return_value = false;
3640 break;
3641 default:
3642 // TODO: make this work correctly. For now always report
3643 // run if we aren't running so we don't miss any running
3644 // events. If I run the lldb/test/thread/a.out file and
3645 // break at main.cpp:58, run and hit the breakpoints on
3646 // multiple threads, then somehow during the stepping over
3647 // of all breakpoints no run gets reported.
3648
3649 // This is a transition from stop to run.
3650 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3651 case eVoteYes:
3652 case eVoteNoOpinion:
3653 return_value = true;
3654 break;
3655 case eVoteNo:
3656 return_value = false;
3657 break;
3658 }
3659 break;
3660 }
3661 }
3662 break;
3663 case eStateStopped:
3664 case eStateCrashed:
3665 case eStateSuspended:
3666 // We've stopped. First see if we're going to restart the target.
3667 // If we are going to stop, then we always broadcast the event.
3668 // If we aren't going to stop, let the thread plans decide if we're going to
3669 // report this event.
3670 // If no thread has an opinion, we don't report it.
3671
3672 m_stdio_communication.SynchronizeWithReadThread();
3673 RefreshStateAfterStop();
3674 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3675 if (log)
3676 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3677 "interrupt, state: %s",
3678 static_cast<void *>(event_ptr), StateAsCString(state));
3679 // Even though we know we are going to stop, we should let the threads
3680 // have a look at the stop,
3681 // so they can properly set their state.
3682 m_thread_list.ShouldStop(event_ptr);
3683 return_value = true;
3684 } else {
3685 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3686 bool should_resume = false;
3687
3688 // It makes no sense to ask "ShouldStop" if we've already been
3689 // restarted...
3690 // Asking the thread list is also not likely to go well, since we are
3691 // running again.
3692 // So in that case just report the event.
3693
3694 if (!was_restarted)
3695 should_resume = !m_thread_list.ShouldStop(event_ptr);
3696
3697 if (was_restarted || should_resume || m_resume_requested) {
3698 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3699 if (log)
3700 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3701 "%s was_restarted: %i stop_vote: %d.",
3702 should_resume, StateAsCString(state), was_restarted,
3703 stop_vote);
3704
3705 switch (stop_vote) {
3706 case eVoteYes:
3707 return_value = true;
3708 break;
3709 case eVoteNoOpinion:
3710 case eVoteNo:
3711 return_value = false;
3712 break;
3713 }
3714
3715 if (!was_restarted) {
3716 if (log)
3717 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3718 "from state: %s",
3719 static_cast<void *>(event_ptr), StateAsCString(state));
3720 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3721 PrivateResume();
3722 }
3723 } else {
3724 return_value = true;
3725 SynchronouslyNotifyStateChanged(state);
3726 }
3727 }
3728 break;
3729 }
3730
3731 // Forcing the next event delivery is a one shot deal. So reset it here.
3732 m_force_next_event_delivery = false;
3733
3734 // We do some coalescing of events (for instance two consecutive running
3735 // events get coalesced.)
3736 // But we only coalesce against events we actually broadcast. So we use
3737 // m_last_broadcast_state
3738 // to track that. NB - you can't use "m_public_state.GetValue()" for that
3739 // purpose, as was originally done,
3740 // because the PublicState reflects the last event pulled off the queue, and
3741 // there may be several
3742 // events stacked up on the queue unserviced. So the PublicState may not
3743 // reflect the last broadcasted event
3744 // yet. m_last_broadcast_state gets updated here.
3745
3746 if (return_value)
3747 m_last_broadcast_state = state;
3748
3749 if (log)
3750 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3751 "broadcast state: %s - %s",
3752 static_cast<void *>(event_ptr), StateAsCString(state),
3753 StateAsCString(m_last_broadcast_state),
3754 return_value ? "YES" : "NO");
3755 return return_value;
3756}
3757
3758bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3759 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3760
3761 bool already_running = PrivateStateThreadIsValid();
3762 if (log)
3763 log->Printf("Process::%s()%s ", __FUNCTION__,
3764 already_running ? " already running"
3765 : " starting private state thread");
3766
3767 if (!is_secondary_thread && already_running)
3768 return true;
3769
3770 // Create a thread that watches our internal state and controls which
3771 // events make it to clients (into the DCProcess event queue).
3772 char thread_name[1024];
3773
3774 if (HostInfo::GetMaxThreadNameLength() <= 30) {
3775 // On platforms with abbreviated thread name lengths, choose thread names
3776 // that fit within the limit.
3777 if (already_running)
3778 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3779 else
3780 snprintf(thread_name, sizeof(thread_name), "intern-state");
3781 } else {
3782 if (already_running)
3783 snprintf(thread_name, sizeof(thread_name),
3784 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3785 GetID());
3786 else
3787 snprintf(thread_name, sizeof(thread_name),
3788 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3789 }
3790
3791 // Create the private state thread, and start it running.
3792 PrivateStateThreadArgs *args_ptr =
3793 new PrivateStateThreadArgs(this, is_secondary_thread);
3794 m_private_state_thread =
3795 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3796 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3797 if (m_private_state_thread.IsJoinable()) {
3798 ResumePrivateStateThread();
3799 return true;
3800 } else
3801 return false;
3802}
3803
3804void Process::PausePrivateStateThread() {
3805 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3806}
3807
3808void Process::ResumePrivateStateThread() {
3809 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3810}
3811
3812void Process::StopPrivateStateThread() {
3813 if (m_private_state_thread.IsJoinable())
3814 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3815 else {
3816 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3817 if (log)
3818 log->Printf(
3819 "Went to stop the private state thread, but it was already invalid.");
3820 }
3821}
3822
3823void Process::ControlPrivateStateThread(uint32_t signal) {
3824 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3825
3826 assert(signal == eBroadcastInternalStateControlStop ||
3827 signal == eBroadcastInternalStateControlPause ||
3828 signal == eBroadcastInternalStateControlResume);
3829
3830 if (log)
3831 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3832
3833 // Signal the private state thread
3834 if (m_private_state_thread.IsJoinable()) {
3835 // Broadcast the event.
3836 // It is important to do this outside of the if below, because
3837 // it's possible that the thread state is invalid but that the
3838 // thread is waiting on a control event instead of simply being
3839 // on its way out (this should not happen, but it apparently can).
3840 if (log)
3841 log->Printf("Sending control event of type: %d.", signal);
3842 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3843 m_private_state_control_broadcaster.BroadcastEvent(signal,
3844 event_receipt_sp);
3845
3846 // Wait for the event receipt or for the private state thread to exit
3847 bool receipt_received = false;
3848 if (PrivateStateThreadIsValid()) {
3849 while (!receipt_received) {
3850 bool timed_out = false;
3851 // Check for a receipt for 2 seconds and then check if the private state
3852 // thread is still around.
3853 receipt_received = event_receipt_sp->WaitForEventReceived(
3854 std::chrono::seconds(2), &timed_out);
3855 if (!receipt_received) {
3856 // Check if the private state thread is still around. If it isn't then
3857 // we are done waiting
3858 if (!PrivateStateThreadIsValid())
3859 break; // Private state thread exited or is exiting, we are done
3860 }
3861 }
3862 }
3863
3864 if (signal == eBroadcastInternalStateControlStop) {
3865 thread_result_t result = NULL;
3866 m_private_state_thread.Join(&result);
3867 m_private_state_thread.Reset();
3868 }
3869 } else {
3870 if (log)
3871 log->Printf(
3872 "Private state thread already dead, no need to signal it to stop.");
3873 }
3874}
3875
3876void Process::SendAsyncInterrupt() {
3877 if (PrivateStateThreadIsValid())
3878 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3879 nullptr);
3880 else
3881 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3882}
3883
3884void Process::HandlePrivateEvent(EventSP &event_sp) {
3885 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3886 m_resume_requested = false;
3887
3888 const StateType new_state =
3889 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3890
3891 // First check to see if anybody wants a shot at this event:
3892 if (m_next_event_action_ap) {
3893 NextEventAction::EventActionResult action_result =
3894 m_next_event_action_ap->PerformAction(event_sp);
3895 if (log)
3896 log->Printf("Ran next event action, result was %d.", action_result);
3897
3898 switch (action_result) {
3899 case NextEventAction::eEventActionSuccess:
3900 SetNextEventAction(nullptr);
3901 break;
3902
3903 case NextEventAction::eEventActionRetry:
3904 break;
3905
3906 case NextEventAction::eEventActionExit:
3907 // Handle Exiting Here. If we already got an exited event,
3908 // we should just propagate it. Otherwise, swallow this event,
3909 // and set our state to exit so the next event will kill us.
3910 if (new_state != eStateExited) {
3911 // FIXME: should cons up an exited event, and discard this one.
3912 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3913 SetNextEventAction(nullptr);
3914 return;
3915 }
3916 SetNextEventAction(nullptr);
3917 break;
3918 }
3919 }
3920
3921 // See if we should broadcast this state to external clients?
3922 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3923
3924 if (should_broadcast) {
3925 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3926 if (log) {
3927 log->Printf("Process::%s (pid = %" PRIu64
3928 ") broadcasting new state %s (old state %s) to %s",
3929 __FUNCTION__, GetID(), StateAsCString(new_state),
3930 StateAsCString(GetState()),
3931 is_hijacked ? "hijacked" : "public");
3932 }
3933 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3934 if (StateIsRunningState(new_state)) {
3935 // Only push the input handler if we aren't fowarding events,
3936 // as this means the curses GUI is in use...
3937 // Or don't push it if we are launching since it will come up stopped.
3938 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3939 new_state != eStateLaunching && new_state != eStateAttaching) {
3940 PushProcessIOHandler();
3941 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3942 eBroadcastAlways);
3943 if (log)
3944 log->Printf("Process::%s updated m_iohandler_sync to %d",
3945 __FUNCTION__, m_iohandler_sync.GetValue());
3946 }
3947 } else if (StateIsStoppedState(new_state, false)) {
3948 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3949 // If the lldb_private::Debugger is handling the events, we don't
3950 // want to pop the process IOHandler here, we want to do it when
3951 // we receive the stopped event so we can carefully control when
3952 // the process IOHandler is popped because when we stop we want to
3953 // display some text stating how and why we stopped, then maybe some
3954 // process/thread/frame info, and then we want the "(lldb) " prompt
3955 // to show up. If we pop the process IOHandler here, then we will
3956 // cause the command interpreter to become the top IOHandler after
3957 // the process pops off and it will update its prompt right away...
3958 // See the Debugger.cpp file where it calls the function as
3959 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3960 // Otherwise we end up getting overlapping "(lldb) " prompts and
3961 // garbled output.
3962 //
3963 // If we aren't handling the events in the debugger (which is indicated
3964 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3965 // are hijacked, then we always pop the process IO handler manually.
3966 // Hijacking happens when the internal process state thread is running
3967 // thread plans, or when commands want to run in synchronous mode
3968 // and they call "process->WaitForProcessToStop()". An example of
3969 // something
3970 // that will hijack the events is a simple expression:
3971 //
3972 // (lldb) expr (int)puts("hello")
3973 //
3974 // This will cause the internal process state thread to resume and halt
3975 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3976 // events) and we do need the IO handler to be pushed and popped
3977 // correctly.
3978
3979 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3980 PopProcessIOHandler();
3981 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003982 }
3983
3984 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003985 } else {
3986 if (log) {
3987 log->Printf(
3988 "Process::%s (pid = %" PRIu64
3989 ") suppressing state %s (old state %s): should_broadcast == false",
3990 __FUNCTION__, GetID(), StateAsCString(new_state),
3991 StateAsCString(GetState()));
3992 }
3993 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003994}
3995
Kate Stoneb9c1b512016-09-06 20:57:50 +00003996Error Process::HaltPrivate() {
3997 EventSP event_sp;
3998 Error error(WillHalt());
3999 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004000 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004001
4002 // Ask the process subclass to actually halt our process
4003 bool caused_stop;
4004 error = DoHalt(caused_stop);
4005
4006 DidHalt();
4007 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004008}
4009
Kate Stoneb9c1b512016-09-06 20:57:50 +00004010thread_result_t Process::PrivateStateThread(void *arg) {
4011 std::unique_ptr<PrivateStateThreadArgs> args_up(
4012 static_cast<PrivateStateThreadArgs *>(arg));
4013 thread_result_t result =
4014 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
4015 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004016}
4017
Kate Stoneb9c1b512016-09-06 20:57:50 +00004018thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
4019 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00004020
Kate Stoneb9c1b512016-09-06 20:57:50 +00004021 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4022 if (log)
4023 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4024 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00004025
Kate Stoneb9c1b512016-09-06 20:57:50 +00004026 bool exit_now = false;
4027 bool interrupt_requested = false;
4028 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00004029 EventSP event_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004030 WaitForEventsPrivate(std::chrono::microseconds(0), event_sp, control_only);
4031 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4032 if (log)
4033 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4034 ") got a control event: %d",
4035 __FUNCTION__, static_cast<void *>(this), GetID(),
4036 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00004037
Kate Stoneb9c1b512016-09-06 20:57:50 +00004038 switch (event_sp->GetType()) {
4039 case eBroadcastInternalStateControlStop:
4040 exit_now = true;
4041 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00004042
Kate Stoneb9c1b512016-09-06 20:57:50 +00004043 case eBroadcastInternalStateControlPause:
4044 control_only = true;
4045 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004046
Kate Stoneb9c1b512016-09-06 20:57:50 +00004047 case eBroadcastInternalStateControlResume:
4048 control_only = false;
4049 break;
4050 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004051
Kate Stoneb9c1b512016-09-06 20:57:50 +00004052 continue;
4053 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4054 if (m_public_state.GetValue() == eStateAttaching) {
4055 if (log)
4056 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4057 ") woke up with an interrupt while attaching - "
4058 "forwarding interrupt.",
4059 __FUNCTION__, static_cast<void *>(this), GetID());
4060 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4061 } else if (StateIsRunningState(m_last_broadcast_state)) {
4062 if (log)
4063 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4064 ") woke up with an interrupt - Halting.",
4065 __FUNCTION__, static_cast<void *>(this), GetID());
4066 Error error = HaltPrivate();
4067 if (error.Fail() && log)
4068 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4069 ") failed to halt the process: %s",
4070 __FUNCTION__, static_cast<void *>(this), GetID(),
4071 error.AsCString());
4072 // Halt should generate a stopped event. Make a note of the fact that we
4073 // were
4074 // doing the interrupt, so we can set the interrupted flag after we
4075 // receive the
4076 // event. We deliberately set this to true even if HaltPrivate failed,
4077 // so that we
4078 // can interrupt on the next natural stop.
4079 interrupt_requested = true;
4080 } else {
4081 // This can happen when someone (e.g. Process::Halt) sees that we are
4082 // running and
4083 // sends an interrupt request, but the process actually stops before we
4084 // receive
4085 // it. In that case, we can just ignore the request. We use
4086 // m_last_broadcast_state, because the Stopped event may not have been
4087 // popped of
4088 // the event queue yet, which is when the public state gets updated.
4089 if (log)
4090 log->Printf(
4091 "Process::%s ignoring interrupt as we have already stopped.",
4092 __FUNCTION__);
4093 }
4094 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004095 }
4096
Kate Stoneb9c1b512016-09-06 20:57:50 +00004097 const StateType internal_state =
4098 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004099
Kate Stoneb9c1b512016-09-06 20:57:50 +00004100 if (internal_state != eStateInvalid) {
4101 if (m_clear_thread_plans_on_stop &&
4102 StateIsStoppedState(internal_state, true)) {
4103 m_clear_thread_plans_on_stop = false;
4104 m_thread_list.DiscardThreadPlans();
4105 }
4106
4107 if (interrupt_requested) {
4108 if (StateIsStoppedState(internal_state, true)) {
4109 // We requested the interrupt, so mark this as such in the stop event
4110 // so
4111 // clients can tell an interrupted process from a natural stop
4112 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4113 interrupt_requested = false;
4114 } else if (log) {
4115 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4116 "state '%s' received.",
4117 __FUNCTION__, StateAsCString(internal_state));
4118 }
4119 }
4120
4121 HandlePrivateEvent(event_sp);
4122 }
4123
4124 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4125 internal_state == eStateDetached) {
4126 if (log)
4127 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4128 ") about to exit with internal state %s...",
4129 __FUNCTION__, static_cast<void *>(this), GetID(),
4130 StateAsCString(internal_state));
4131
4132 break;
4133 }
4134 }
4135
4136 // Verify log is still enabled before attempting to write to it...
4137 if (log)
4138 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4139 __FUNCTION__, static_cast<void *>(this), GetID());
4140
4141 // If we are a secondary thread, then the primary thread we are working for
4142 // will have already
4143 // acquired the public_run_lock, and isn't done with what it was doing yet, so
4144 // don't
4145 // try to change it on the way out.
4146 if (!is_secondary_thread)
4147 m_public_run_lock.SetStopped();
4148 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004149}
4150
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004151//------------------------------------------------------------------
4152// Process Event Data
4153//------------------------------------------------------------------
4154
Kate Stoneb9c1b512016-09-06 20:57:50 +00004155Process::ProcessEventData::ProcessEventData()
4156 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4157 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004158
Kate Stoneb9c1b512016-09-06 20:57:50 +00004159Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4160 StateType state)
4161 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4162 m_update_state(0), m_interrupted(false) {
4163 if (process_sp)
4164 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004165}
4166
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004167Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004168
Kate Stoneb9c1b512016-09-06 20:57:50 +00004169const ConstString &Process::ProcessEventData::GetFlavorString() {
4170 static ConstString g_flavor("Process::ProcessEventData");
4171 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004172}
4173
Kate Stoneb9c1b512016-09-06 20:57:50 +00004174const ConstString &Process::ProcessEventData::GetFlavor() const {
4175 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004176}
4177
Kate Stoneb9c1b512016-09-06 20:57:50 +00004178void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4179 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004180
Kate Stoneb9c1b512016-09-06 20:57:50 +00004181 if (!process_sp)
4182 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004183
Kate Stoneb9c1b512016-09-06 20:57:50 +00004184 // This function gets called twice for each event, once when the event gets
4185 // pulled
4186 // off of the private process event queue, and then any number of times, first
4187 // when it gets pulled off of
4188 // the public event queue, then other times when we're pretending that this is
4189 // where we stopped at the
4190 // end of expression evaluation. m_update_state is used to distinguish these
4191 // three cases; it is 0 when we're just pulling it off for private handling,
4192 // and > 1 for expression evaluation, and we don't want to do the breakpoint
4193 // command handling then.
4194 if (m_update_state != 1)
4195 return;
4196
4197 process_sp->SetPublicState(
4198 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4199
4200 // If this is a halt event, even if the halt stopped with some reason other
4201 // than a plain interrupt (e.g. we had
4202 // already stopped for a breakpoint when the halt request came through) don't
4203 // do the StopInfo actions, as they may
4204 // end up restarting the process.
4205 if (m_interrupted)
4206 return;
4207
4208 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4209 if (m_state == eStateStopped && !m_restarted) {
4210 // Let process subclasses know we are about to do a public stop and
4211 // do anything they might need to in order to speed up register and
4212 // memory accesses.
4213 process_sp->WillPublicStop();
4214
4215 ThreadList &curr_thread_list = process_sp->GetThreadList();
4216 uint32_t num_threads = curr_thread_list.GetSize();
4217 uint32_t idx;
4218
4219 // The actions might change one of the thread's stop_info's opinions about
4220 // whether we should
4221 // stop the process, so we need to query that as we go.
4222
4223 // One other complication here, is that we try to catch any case where the
4224 // target has run (except for expressions)
4225 // and immediately exit, but if we get that wrong (which is possible) then
4226 // the thread list might have changed, and
4227 // that would cause our iteration here to crash. We could make a copy of
4228 // the thread list, but we'd really like
4229 // to also know if it has changed at all, so we make up a vector of the
4230 // thread ID's and check what we get back
4231 // against this list & bag out if anything differs.
4232 std::vector<uint32_t> thread_index_array(num_threads);
4233 for (idx = 0; idx < num_threads; ++idx)
4234 thread_index_array[idx] =
4235 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4236
4237 // Use this to track whether we should continue from here. We will only
4238 // continue the target running if
4239 // no thread says we should stop. Of course if some thread's PerformAction
4240 // actually sets the target running,
4241 // then it doesn't matter what the other threads say...
4242
4243 bool still_should_stop = false;
4244
4245 // Sometimes - for instance if we have a bug in the stub we are talking to,
4246 // we stop but no thread has a
4247 // valid stop reason. In that case we should just stop, because we have no
4248 // way of telling what the right
4249 // thing to do is, and it's better to let the user decide than continue
4250 // behind their backs.
4251
4252 bool does_anybody_have_an_opinion = false;
4253
4254 for (idx = 0; idx < num_threads; ++idx) {
4255 curr_thread_list = process_sp->GetThreadList();
4256 if (curr_thread_list.GetSize() != num_threads) {
4257 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4258 LIBLLDB_LOG_PROCESS));
4259 if (log)
4260 log->Printf(
4261 "Number of threads changed from %u to %u while processing event.",
4262 num_threads, curr_thread_list.GetSize());
4263 break;
4264 }
4265
4266 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4267
4268 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4269 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4270 LIBLLDB_LOG_PROCESS));
4271 if (log)
4272 log->Printf("The thread at position %u changed from %u to %u while "
4273 "processing event.",
4274 idx, thread_index_array[idx], thread_sp->GetIndexID());
4275 break;
4276 }
4277
4278 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4279 if (stop_info_sp && stop_info_sp->IsValid()) {
4280 does_anybody_have_an_opinion = true;
4281 bool this_thread_wants_to_stop;
4282 if (stop_info_sp->GetOverrideShouldStop()) {
4283 this_thread_wants_to_stop =
4284 stop_info_sp->GetOverriddenShouldStopValue();
4285 } else {
4286 stop_info_sp->PerformAction(event_ptr);
4287 // The stop action might restart the target. If it does, then we want
4288 // to mark that in the
4289 // event so that whoever is receiving it will know to wait for the
4290 // running event and reflect
4291 // that state appropriately.
4292 // We also need to stop processing actions, since they aren't
4293 // expecting the target to be running.
4294
4295 // FIXME: we might have run.
4296 if (stop_info_sp->HasTargetRunSinceMe()) {
4297 SetRestarted(true);
4298 break;
4299 }
4300
4301 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004302 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004303
4304 if (!still_should_stop)
4305 still_should_stop = this_thread_wants_to_stop;
4306 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004307 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004308
4309 if (!GetRestarted()) {
4310 if (!still_should_stop && does_anybody_have_an_opinion) {
4311 // We've been asked to continue, so do that here.
4312 SetRestarted(true);
4313 // Use the public resume method here, since this is just
4314 // extending a public resume.
4315 process_sp->PrivateResume();
4316 } else {
4317 // If we didn't restart, run the Stop Hooks here:
4318 // They might also restart the target, so watch for that.
4319 process_sp->GetTarget().RunStopHooks();
4320 if (process_sp->GetPrivateState() == eStateRunning)
4321 SetRestarted(true);
4322 }
4323 }
4324 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004325}
4326
Kate Stoneb9c1b512016-09-06 20:57:50 +00004327void Process::ProcessEventData::Dump(Stream *s) const {
4328 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004329
Kate Stoneb9c1b512016-09-06 20:57:50 +00004330 if (process_sp)
4331 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4332 static_cast<void *>(process_sp.get()), process_sp->GetID());
4333 else
4334 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004335
Kate Stoneb9c1b512016-09-06 20:57:50 +00004336 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004337}
4338
4339const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004340Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4341 if (event_ptr) {
4342 const EventData *event_data = event_ptr->GetData();
4343 if (event_data &&
4344 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4345 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4346 }
4347 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004348}
4349
4350ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004351Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4352 ProcessSP process_sp;
4353 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4354 if (data)
4355 process_sp = data->GetProcessSP();
4356 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004357}
4358
Kate Stoneb9c1b512016-09-06 20:57:50 +00004359StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4360 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4361 if (data == nullptr)
4362 return eStateInvalid;
4363 else
4364 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004365}
4366
Kate Stoneb9c1b512016-09-06 20:57:50 +00004367bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4368 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4369 if (data == nullptr)
4370 return false;
4371 else
4372 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004373}
4374
Kate Stoneb9c1b512016-09-06 20:57:50 +00004375void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4376 bool new_value) {
4377 ProcessEventData *data =
4378 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4379 if (data != nullptr)
4380 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004381}
4382
Jim Ingham0161b492013-02-09 01:29:05 +00004383size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004384Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4385 ProcessEventData *data =
4386 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4387 if (data != nullptr)
4388 return data->GetNumRestartedReasons();
4389 else
4390 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004391}
4392
4393const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004394Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4395 size_t idx) {
4396 ProcessEventData *data =
4397 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4398 if (data != nullptr)
4399 return data->GetRestartedReasonAtIndex(idx);
4400 else
4401 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004402}
4403
Kate Stoneb9c1b512016-09-06 20:57:50 +00004404void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4405 const char *reason) {
4406 ProcessEventData *data =
4407 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4408 if (data != nullptr)
4409 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004410}
4411
Kate Stoneb9c1b512016-09-06 20:57:50 +00004412bool Process::ProcessEventData::GetInterruptedFromEvent(
4413 const Event *event_ptr) {
4414 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4415 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004416 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004417 else
4418 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004419}
4420
Kate Stoneb9c1b512016-09-06 20:57:50 +00004421void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4422 bool new_value) {
4423 ProcessEventData *data =
4424 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4425 if (data != nullptr)
4426 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004427}
4428
Kate Stoneb9c1b512016-09-06 20:57:50 +00004429bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4430 ProcessEventData *data =
4431 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4432 if (data) {
4433 data->SetUpdateStateOnRemoval();
4434 return true;
4435 }
4436 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004437}
4438
Kate Stoneb9c1b512016-09-06 20:57:50 +00004439lldb::TargetSP Process::CalculateTarget() { return m_target_sp.lock(); }
4440
4441void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4442 exe_ctx.SetTargetPtr(&GetTarget());
4443 exe_ctx.SetProcessPtr(this);
4444 exe_ctx.SetThreadPtr(nullptr);
4445 exe_ctx.SetFramePtr(nullptr);
4446}
4447
4448// uint32_t
4449// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4450// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004451//{
4452// return 0;
4453//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004454//
4455// ArchSpec
4456// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004457//{
4458// return Host::GetArchSpecForExistingProcess (pid);
4459//}
4460//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004461// ArchSpec
4462// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004463//{
4464// return Host::GetArchSpecForExistingProcess (process_name);
4465//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004466
Kate Stoneb9c1b512016-09-06 20:57:50 +00004467void Process::AppendSTDOUT(const char *s, size_t len) {
4468 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4469 m_stdout_data.append(s, len);
4470 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4471 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004472}
4473
Kate Stoneb9c1b512016-09-06 20:57:50 +00004474void Process::AppendSTDERR(const char *s, size_t len) {
4475 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4476 m_stderr_data.append(s, len);
4477 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4478 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004479}
4480
Kate Stoneb9c1b512016-09-06 20:57:50 +00004481void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4482 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4483 m_profile_data.push_back(one_profile_data);
4484 BroadcastEventIfUnique(eBroadcastBitProfileData,
4485 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004486}
4487
Kate Stoneb9c1b512016-09-06 20:57:50 +00004488void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4489 const StructuredDataPluginSP &plugin_sp) {
4490 BroadcastEvent(
4491 eBroadcastBitStructuredData,
4492 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004493}
4494
4495StructuredDataPluginSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004496Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4497 auto find_it = m_structured_data_plugin_map.find(type_name);
4498 if (find_it != m_structured_data_plugin_map.end())
4499 return find_it->second;
4500 else
4501 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004502}
4503
Kate Stoneb9c1b512016-09-06 20:57:50 +00004504size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Error &error) {
4505 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4506 if (m_profile_data.empty())
4507 return 0;
4508
4509 std::string &one_profile_data = m_profile_data.front();
4510 size_t bytes_available = one_profile_data.size();
4511 if (bytes_available > 0) {
4512 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4513 if (log)
4514 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4515 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4516 if (bytes_available > buf_size) {
4517 memcpy(buf, one_profile_data.c_str(), buf_size);
4518 one_profile_data.erase(0, buf_size);
4519 bytes_available = buf_size;
4520 } else {
4521 memcpy(buf, one_profile_data.c_str(), bytes_available);
4522 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004523 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004524 }
4525 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004526}
4527
Greg Clayton93e86192011-11-13 04:45:22 +00004528//------------------------------------------------------------------
4529// Process STDIO
4530//------------------------------------------------------------------
4531
Kate Stoneb9c1b512016-09-06 20:57:50 +00004532size_t Process::GetSTDOUT(char *buf, size_t buf_size, Error &error) {
4533 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4534 size_t bytes_available = m_stdout_data.size();
4535 if (bytes_available > 0) {
4536 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4537 if (log)
4538 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4539 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4540 if (bytes_available > buf_size) {
4541 memcpy(buf, m_stdout_data.c_str(), buf_size);
4542 m_stdout_data.erase(0, buf_size);
4543 bytes_available = buf_size;
4544 } else {
4545 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4546 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004547 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004548 }
4549 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004550}
4551
Kate Stoneb9c1b512016-09-06 20:57:50 +00004552size_t Process::GetSTDERR(char *buf, size_t buf_size, Error &error) {
4553 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4554 size_t bytes_available = m_stderr_data.size();
4555 if (bytes_available > 0) {
4556 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4557 if (log)
4558 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4559 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4560 if (bytes_available > buf_size) {
4561 memcpy(buf, m_stderr_data.c_str(), buf_size);
4562 m_stderr_data.erase(0, buf_size);
4563 bytes_available = buf_size;
4564 } else {
4565 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4566 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004567 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004568 }
4569 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004570}
4571
Kate Stoneb9c1b512016-09-06 20:57:50 +00004572void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4573 size_t src_len) {
4574 Process *process = (Process *)baton;
4575 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004576}
4577
Kate Stoneb9c1b512016-09-06 20:57:50 +00004578class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004579public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004580 IOHandlerProcessSTDIO(Process *process, int write_fd)
4581 : IOHandler(process->GetTarget().GetDebugger(),
4582 IOHandler::Type::ProcessIO),
4583 m_process(process), m_read_file(), m_write_file(write_fd, false),
4584 m_pipe() {
4585 m_pipe.CreateNew(false);
4586 m_read_file.SetDescriptor(GetInputFD(), false);
4587 }
4588
4589 ~IOHandlerProcessSTDIO() override = default;
4590
4591 // Each IOHandler gets to run until it is done. It should read data
4592 // from the "in" and place output into "out" and "err and return
4593 // when done.
4594 void Run() override {
4595 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4596 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4597 SetIsDone(true);
4598 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004599 }
4600
Kate Stoneb9c1b512016-09-06 20:57:50 +00004601 SetIsDone(false);
4602 const int read_fd = m_read_file.GetDescriptor();
4603 TerminalState terminal_state;
4604 terminal_state.Save(read_fd, false);
4605 Terminal terminal(read_fd);
4606 terminal.SetCanonical(false);
4607 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004608// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004609#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004610 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4611 m_is_running = true;
4612 while (!GetIsDone()) {
4613 SelectHelper select_helper;
4614 select_helper.FDSetRead(read_fd);
4615 select_helper.FDSetRead(pipe_read_fd);
4616 Error error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004617
Kate Stoneb9c1b512016-09-06 20:57:50 +00004618 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004619 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004620 } else {
4621 char ch = 0;
4622 size_t n;
4623 if (select_helper.FDIsSetRead(read_fd)) {
4624 n = 1;
4625 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4626 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4627 SetIsDone(true);
4628 } else
4629 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004630 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004631 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4632 size_t bytes_read;
4633 // Consume the interrupt byte
4634 Error error = m_pipe.Read(&ch, 1, bytes_read);
4635 if (error.Success()) {
4636 switch (ch) {
4637 case 'q':
4638 SetIsDone(true);
4639 break;
4640 case 'i':
4641 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004642 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004643 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004644 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004645 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004646 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004647 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004648 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004649 m_is_running = false;
4650#endif
4651 terminal_state.Restore();
4652 }
4653
4654 void Cancel() override {
4655 SetIsDone(true);
4656 // Only write to our pipe to cancel if we are in
4657 // IOHandlerProcessSTDIO::Run().
4658 // We can end up with a python command that is being run from the command
4659 // interpreter:
4660 //
4661 // (lldb) step_process_thousands_of_times
4662 //
4663 // In this case the command interpreter will be in the middle of handling
4664 // the command and if the process pushes and pops the IOHandler thousands
4665 // of times, we can end up writing to m_pipe without ever consuming the
4666 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4667 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4668 if (m_is_running) {
4669 char ch = 'q'; // Send 'q' for quit
4670 size_t bytes_written = 0;
4671 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004672 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004673 }
4674
4675 bool Interrupt() override {
4676 // Do only things that are safe to do in an interrupt context (like in
4677 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4678 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4679 // that was written to the pipe and then call
4680 // m_process->SendAsyncInterrupt()
4681 // from a much safer location in code.
4682 if (m_active) {
4683 char ch = 'i'; // Send 'i' for interrupt
4684 size_t bytes_written = 0;
4685 Error result = m_pipe.Write(&ch, 1, bytes_written);
4686 return result.Success();
4687 } else {
4688 // This IOHandler might be pushed on the stack, but not being run
4689 // currently
4690 // so do the right thing if we aren't actively watching for STDIN by
4691 // sending
4692 // the interrupt to the process. Otherwise the write to the pipe above
4693 // would
4694 // do nothing. This can happen when the command interpreter is running and
4695 // gets a "expression ...". It will be on the IOHandler thread and sending
4696 // the input is complete to the delegate which will cause the expression
4697 // to
4698 // run, which will push the process IO handler, but not run it.
4699
4700 if (StateIsRunningState(m_process->GetState())) {
4701 m_process->SendAsyncInterrupt();
4702 return true;
4703 }
4704 }
4705 return false;
4706 }
4707
4708 void GotEOF() override {}
4709
Greg Clayton44d93782014-01-27 23:43:24 +00004710protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004711 Process *m_process;
4712 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4713 File m_write_file; // Write to this file (usually the master pty for getting
4714 // io to debuggee)
4715 Pipe m_pipe;
4716 std::atomic<bool> m_is_running;
Greg Clayton44d93782014-01-27 23:43:24 +00004717};
4718
Kate Stoneb9c1b512016-09-06 20:57:50 +00004719void Process::SetSTDIOFileDescriptor(int fd) {
4720 // First set up the Read Thread for reading/handling process I/O
4721
4722 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4723 new ConnectionFileDescriptor(fd, true));
4724
4725 if (conn_ap) {
4726 m_stdio_communication.SetConnection(conn_ap.release());
4727 if (m_stdio_communication.IsConnected()) {
4728 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4729 STDIOReadThreadBytesReceived, this);
4730 m_stdio_communication.StartReadThread();
4731
4732 // Now read thread is set up, set up input reader.
4733
4734 if (!m_process_input_reader)
4735 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004736 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004737 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004738}
4739
Kate Stoneb9c1b512016-09-06 20:57:50 +00004740bool Process::ProcessIOHandlerIsActive() {
4741 IOHandlerSP io_handler_sp(m_process_input_reader);
4742 if (io_handler_sp)
4743 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4744 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004745}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004746bool Process::PushProcessIOHandler() {
4747 IOHandlerSP io_handler_sp(m_process_input_reader);
4748 if (io_handler_sp) {
4749 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4750 if (log)
4751 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004752
Kate Stoneb9c1b512016-09-06 20:57:50 +00004753 io_handler_sp->SetIsDone(false);
4754 GetTarget().GetDebugger().PushIOHandler(io_handler_sp);
4755 return true;
4756 }
4757 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004758}
4759
Kate Stoneb9c1b512016-09-06 20:57:50 +00004760bool Process::PopProcessIOHandler() {
4761 IOHandlerSP io_handler_sp(m_process_input_reader);
4762 if (io_handler_sp)
4763 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4764 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004765}
4766
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004767// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004768void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004769
Kate Stoneb9c1b512016-09-06 20:57:50 +00004770void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004771
Kate Stoneb9c1b512016-09-06 20:57:50 +00004772namespace {
4773// RestorePlanState is used to record the "is private", "is master" and "okay to
4774// discard" fields of
4775// the plan we are running, and reset it on Clean or on destruction.
4776// It will only reset the state once, so you can call Clean and then monkey with
4777// the state and it
4778// won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004779
Kate Stoneb9c1b512016-09-06 20:57:50 +00004780class RestorePlanState {
4781public:
4782 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4783 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4784 if (m_thread_plan_sp) {
4785 m_private = m_thread_plan_sp->GetPrivate();
4786 m_is_master = m_thread_plan_sp->IsMasterPlan();
4787 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4788 }
4789 }
4790
4791 ~RestorePlanState() { Clean(); }
4792
4793 void Clean() {
4794 if (!m_already_reset && m_thread_plan_sp) {
4795 m_already_reset = true;
4796 m_thread_plan_sp->SetPrivate(m_private);
4797 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4798 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4799 }
4800 }
4801
4802private:
4803 lldb::ThreadPlanSP m_thread_plan_sp;
4804 bool m_already_reset;
4805 bool m_private;
4806 bool m_is_master;
4807 bool m_okay_to_discard;
4808};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004809} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004810
Jim Ingham1624a2d2014-05-05 02:26:40 +00004811ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004812Process::RunThreadPlan(ExecutionContext &exe_ctx,
4813 lldb::ThreadPlanSP &thread_plan_sp,
4814 const EvaluateExpressionOptions &options,
4815 DiagnosticManager &diagnostic_manager) {
4816 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004817
Kate Stoneb9c1b512016-09-06 20:57:50 +00004818 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4819
4820 if (!thread_plan_sp) {
4821 diagnostic_manager.PutCString(
4822 eDiagnosticSeverityError,
4823 "RunThreadPlan called with empty thread plan.");
4824 return eExpressionSetupError;
4825 }
4826
4827 if (!thread_plan_sp->ValidatePlan(nullptr)) {
4828 diagnostic_manager.PutCString(
4829 eDiagnosticSeverityError,
4830 "RunThreadPlan called with an invalid thread plan.");
4831 return eExpressionSetupError;
4832 }
4833
4834 if (exe_ctx.GetProcessPtr() != this) {
4835 diagnostic_manager.PutCString(eDiagnosticSeverityError,
4836 "RunThreadPlan called on wrong process.");
4837 return eExpressionSetupError;
4838 }
4839
4840 Thread *thread = exe_ctx.GetThreadPtr();
4841 if (thread == nullptr) {
4842 diagnostic_manager.PutCString(eDiagnosticSeverityError,
4843 "RunThreadPlan called with invalid thread.");
4844 return eExpressionSetupError;
4845 }
4846
4847 // We need to change some of the thread plan attributes for the thread plan
4848 // runner. This will restore them
4849 // when we are done:
4850
4851 RestorePlanState thread_plan_restorer(thread_plan_sp);
4852
4853 // We rely on the thread plan we are running returning "PlanCompleted" if when
4854 // it successfully completes.
4855 // For that to be true the plan can't be private - since private plans
4856 // suppress themselves in the
4857 // GetCompletedPlan call.
4858
4859 thread_plan_sp->SetPrivate(false);
4860
4861 // The plans run with RunThreadPlan also need to be terminal master plans or
4862 // when they are done we will end
4863 // up asking the plan above us whether we should stop, which may give the
4864 // wrong answer.
4865
4866 thread_plan_sp->SetIsMasterPlan(true);
4867 thread_plan_sp->SetOkayToDiscard(false);
4868
4869 if (m_private_state.GetValue() != eStateStopped) {
4870 diagnostic_manager.PutCString(
4871 eDiagnosticSeverityError,
4872 "RunThreadPlan called while the private state was not stopped.");
4873 return eExpressionSetupError;
4874 }
4875
4876 // Save the thread & frame from the exe_ctx for restoration after we run
4877 const uint32_t thread_idx_id = thread->GetIndexID();
4878 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4879 if (!selected_frame_sp) {
4880 thread->SetSelectedFrame(nullptr);
4881 selected_frame_sp = thread->GetSelectedFrame();
4882 if (!selected_frame_sp) {
4883 diagnostic_manager.Printf(
4884 eDiagnosticSeverityError,
4885 "RunThreadPlan called without a selected frame on thread %d",
4886 thread_idx_id);
4887 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004888 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004889 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004890
Kate Stoneb9c1b512016-09-06 20:57:50 +00004891 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004892
Kate Stoneb9c1b512016-09-06 20:57:50 +00004893 // N.B. Running the target may unset the currently selected thread and frame.
4894 // We don't want to do that either,
4895 // so we should arrange to reset them as well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004896
Kate Stoneb9c1b512016-09-06 20:57:50 +00004897 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004898
Kate Stoneb9c1b512016-09-06 20:57:50 +00004899 uint32_t selected_tid;
4900 StackID selected_stack_id;
4901 if (selected_thread_sp) {
4902 selected_tid = selected_thread_sp->GetIndexID();
4903 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4904 } else {
4905 selected_tid = LLDB_INVALID_THREAD_ID;
4906 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004907
Kate Stoneb9c1b512016-09-06 20:57:50 +00004908 HostThread backup_private_state_thread;
4909 lldb::StateType old_state = eStateInvalid;
4910 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004911
Kate Stoneb9c1b512016-09-06 20:57:50 +00004912 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4913 LIBLLDB_LOG_PROCESS));
4914 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4915 // Yikes, we are running on the private state thread! So we can't wait for
4916 // public events on this thread, since
4917 // we are the thread that is generating public events.
4918 // The simplest thing to do is to spin up a temporary thread to handle
4919 // private state thread events while
4920 // we are fielding public events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004921 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004922 log->Printf("Running thread plan on private state thread, spinning up "
4923 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004924
Kate Stoneb9c1b512016-09-06 20:57:50 +00004925 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004926
Kate Stoneb9c1b512016-09-06 20:57:50 +00004927 // One other bit of business: we want to run just this thread plan and
4928 // anything it pushes, and then stop,
4929 // returning control here.
4930 // But in the normal course of things, the plan above us on the stack would
4931 // be given a shot at the stop
4932 // event before deciding to stop, and we don't want that. So we insert a
4933 // "stopper" base plan on the stack
4934 // before the plan we want to run. Since base plans always stop and return
4935 // control to the user, that will
4936 // do just what we want.
4937 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4938 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4939 // Have to make sure our public state is stopped, since otherwise the
4940 // reporting logic below doesn't work correctly.
4941 old_state = m_public_state.GetValue();
4942 m_public_state.SetValueNoLock(eStateStopped);
4943
4944 // Now spin up the private state thread:
4945 StartPrivateStateThread(true);
4946 }
4947
4948 thread->QueueThreadPlan(
4949 thread_plan_sp, false); // This used to pass "true" does that make sense?
4950
4951 if (options.GetDebug()) {
4952 // In this case, we aren't actually going to run, we just want to stop right
4953 // away.
4954 // Flush this thread so we will refetch the stacks and show the correct
4955 // backtrace.
4956 // FIXME: To make this prettier we should invent some stop reason for this,
4957 // but that
4958 // is only cosmetic, and this functionality is only of use to lldb
4959 // developers who can
4960 // live with not pretty...
4961 thread->Flush();
4962 return eExpressionStoppedForDebug;
4963 }
4964
4965 ListenerSP listener_sp(
4966 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4967
4968 lldb::EventSP event_to_broadcast_sp;
4969
4970 {
4971 // This process event hijacker Hijacks the Public events and its destructor
4972 // makes sure that the process events get
4973 // restored on exit to the function.
4974 //
4975 // If the event needs to propagate beyond the hijacker (e.g., the process
4976 // exits during execution), then the event
4977 // is put into event_to_broadcast_sp for rebroadcasting.
4978
4979 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4980
4981 if (log) {
4982 StreamString s;
4983 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4984 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4985 " to run thread plan \"%s\".",
4986 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004987 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004988
4989 bool got_event;
4990 lldb::EventSP event_sp;
4991 lldb::StateType stop_state = lldb::eStateInvalid;
4992
4993 bool before_first_timeout = true; // This is set to false the first time
4994 // that we have to halt the target.
4995 bool do_resume = true;
4996 bool handle_running_event = true;
4997 const uint64_t default_one_thread_timeout_usec = 250000;
4998
4999 // This is just for accounting:
5000 uint32_t num_resumes = 0;
5001
5002 uint32_t timeout_usec = options.GetTimeoutUsec();
5003 uint32_t one_thread_timeout_usec;
5004 uint32_t all_threads_timeout_usec = 0;
5005
5006 // If we are going to run all threads the whole time, or if we are only
5007 // going to run one thread,
5008 // then we don't need the first timeout. So we set the final timeout, and
5009 // pretend we are after the
5010 // first timeout already.
5011
5012 if (!options.GetStopOthers() || !options.GetTryAllThreads()) {
5013 before_first_timeout = false;
5014 one_thread_timeout_usec = 0;
5015 all_threads_timeout_usec = timeout_usec;
5016 } else {
5017 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
5018
5019 // If the overall wait is forever, then we only need to set the one thread
5020 // timeout:
5021 if (timeout_usec == 0) {
5022 if (option_one_thread_timeout != 0)
5023 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005024 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005025 one_thread_timeout_usec = default_one_thread_timeout_usec;
5026 } else {
5027 // Otherwise, if the one thread timeout is set, make sure it isn't
5028 // longer than the overall timeout,
5029 // and use it, otherwise use half the total timeout, bounded by the
5030 // default_one_thread_timeout_usec.
5031 uint64_t computed_one_thread_timeout;
5032 if (option_one_thread_timeout != 0) {
5033 if (timeout_usec < option_one_thread_timeout) {
5034 diagnostic_manager.PutCString(eDiagnosticSeverityError,
5035 "RunThreadPlan called without one "
5036 "thread timeout greater than total "
5037 "timeout");
5038 return eExpressionSetupError;
5039 }
5040 computed_one_thread_timeout = option_one_thread_timeout;
5041 } else {
5042 computed_one_thread_timeout = timeout_usec / 2;
5043 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5044 computed_one_thread_timeout = default_one_thread_timeout_usec;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005045 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005046 one_thread_timeout_usec = computed_one_thread_timeout;
5047 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5048 }
Kuba Breckaafdf8422014-10-10 23:43:03 +00005049 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005050
Kate Stoneb9c1b512016-09-06 20:57:50 +00005051 if (log)
5052 log->Printf(
5053 "Stop others: %u, try all: %u, before_first: %u, one thread: %" PRIu32
5054 " - all threads: %" PRIu32 ".\n",
5055 options.GetStopOthers(), options.GetTryAllThreads(),
5056 before_first_timeout, one_thread_timeout_usec,
5057 all_threads_timeout_usec);
5058
5059 // This isn't going to work if there are unfetched events on the queue.
5060 // Are there cases where we might want to run the remaining events here, and
5061 // then try to
5062 // call the function? That's probably being too tricky for our own good.
5063
5064 Event *other_events = listener_sp->PeekAtNextEvent();
5065 if (other_events != nullptr) {
5066 diagnostic_manager.PutCString(
5067 eDiagnosticSeverityError,
5068 "RunThreadPlan called with pending events on the queue.");
5069 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00005070 }
5071
Kate Stoneb9c1b512016-09-06 20:57:50 +00005072 // We also need to make sure that the next event is delivered. We might be
5073 // calling a function as part of
5074 // a thread plan, in which case the last delivered event could be the
5075 // running event, and we don't want
5076 // event coalescing to cause us to lose OUR running event...
5077 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00005078
Kate Stoneb9c1b512016-09-06 20:57:50 +00005079// This while loop must exit out the bottom, there's cleanup that we need to do
5080// when we are done.
5081// So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00005082
Kate Stoneb9c1b512016-09-06 20:57:50 +00005083#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5084 // It's pretty much impossible to write test cases for things like:
5085 // One thread timeout expires, I go to halt, but the process already stopped
5086 // on the function call stop breakpoint. Turning on this define will make
5087 // us not
5088 // fetch the first event till after the halt. So if you run a quick
5089 // function, it will have
5090 // completed, and the completion event will be waiting, when you interrupt
5091 // for halt.
5092 // The expression evaluation should still succeed.
5093 bool miss_first_event = true;
5094#endif
5095 TimeValue one_thread_timeout;
5096 TimeValue final_timeout;
5097 std::chrono::microseconds timeout = std::chrono::microseconds(0);
Kuba Breckaa51ea382014-09-06 01:33:13 +00005098
Kate Stoneb9c1b512016-09-06 20:57:50 +00005099 while (true) {
5100 // We usually want to resume the process if we get to the top of the loop.
5101 // The only exception is if we get two running events with no intervening
5102 // stop, which can happen, we will just wait for then next stop event.
5103 if (log)
5104 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5105 "before_first_timeout: %i.",
5106 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00005107
Kate Stoneb9c1b512016-09-06 20:57:50 +00005108 if (do_resume || handle_running_event) {
5109 // Do the initial resume and wait for the running event before going
5110 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00005111
Kate Stoneb9c1b512016-09-06 20:57:50 +00005112 if (do_resume) {
5113 num_resumes++;
5114 Error resume_error = PrivateResume();
5115 if (!resume_error.Success()) {
5116 diagnostic_manager.Printf(
5117 eDiagnosticSeverityError,
5118 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5119 resume_error.AsCString());
5120 return_value = eExpressionSetupError;
5121 break;
5122 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005123 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005124
5125 got_event = listener_sp->WaitForEvent(std::chrono::microseconds(500000),
5126 event_sp);
5127 if (!got_event) {
5128 if (log)
5129 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5130 "resume %" PRIu32 ", exiting.",
5131 num_resumes);
5132
5133 diagnostic_manager.Printf(eDiagnosticSeverityError,
5134 "didn't get any event after resume %" PRIu32
5135 ", exiting.",
5136 num_resumes);
5137 return_value = eExpressionSetupError;
5138 break;
5139 }
5140
5141 stop_state =
5142 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5143
5144 if (stop_state != eStateRunning) {
5145 bool restarted = false;
5146
5147 if (stop_state == eStateStopped) {
5148 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5149 event_sp.get());
5150 if (log)
5151 log->Printf(
5152 "Process::RunThreadPlan(): didn't get running event after "
5153 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5154 "handle_running_event: %i).",
5155 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5156 handle_running_event);
5157 }
5158
5159 if (restarted) {
5160 // This is probably an overabundance of caution, I don't think I
5161 // should ever get a stopped & restarted
5162 // event here. But if I do, the best thing is to Halt and then get
5163 // out of here.
5164 const bool clear_thread_plans = false;
5165 const bool use_run_lock = false;
5166 Halt(clear_thread_plans, use_run_lock);
5167 }
5168
5169 diagnostic_manager.Printf(
5170 eDiagnosticSeverityError,
5171 "didn't get running event after initial resume, got %s instead.",
5172 StateAsCString(stop_state));
5173 return_value = eExpressionSetupError;
5174 break;
5175 }
5176
5177 if (log)
5178 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5179 // We need to call the function synchronously, so spin waiting for it to
5180 // return.
5181 // If we get interrupted while executing, we're going to lose our
5182 // context, and
5183 // won't be able to gather the result at this point.
5184 // We set the timeout AFTER the resume, since the resume takes some time
5185 // and we
5186 // don't want to charge that to the timeout.
5187 } else {
5188 if (log)
5189 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5190 }
5191
5192 if (before_first_timeout) {
5193 if (options.GetTryAllThreads())
5194 timeout = std::chrono::microseconds(one_thread_timeout_usec);
Jason Molendaef7d6412015-08-06 03:27:10 +00005195 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005196 timeout = std::chrono::microseconds(timeout_usec);
5197 } else {
5198 if (timeout_usec == 0)
5199 timeout = std::chrono::microseconds(0);
5200 else
5201 timeout = std::chrono::microseconds(all_threads_timeout_usec);
5202 }
5203
5204 do_resume = true;
5205 handle_running_event = true;
5206
5207 // Now wait for the process to stop again:
5208 event_sp.reset();
5209
5210 if (log) {
5211 if (timeout.count()) {
5212 log->Printf(
5213 "Process::RunThreadPlan(): about to wait - now is %llu - "
5214 "endpoint is %llu",
5215 static_cast<unsigned long long>(
5216 std::chrono::system_clock::now().time_since_epoch().count()),
5217 static_cast<unsigned long long>(
5218 std::chrono::time_point<std::chrono::system_clock,
5219 std::chrono::microseconds>(timeout)
5220 .time_since_epoch()
5221 .count()));
5222 } else {
5223 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005224 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005225 }
5226
5227#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5228 // See comment above...
5229 if (miss_first_event) {
5230 usleep(1000);
5231 miss_first_event = false;
5232 got_event = false;
5233 } else
5234#endif
5235 got_event = listener_sp->WaitForEvent(timeout, event_sp);
5236
5237 if (got_event) {
5238 if (event_sp) {
5239 bool keep_going = false;
5240 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5241 const bool clear_thread_plans = false;
5242 const bool use_run_lock = false;
5243 Halt(clear_thread_plans, use_run_lock);
5244 return_value = eExpressionInterrupted;
5245 diagnostic_manager.PutCString(
5246 eDiagnosticSeverityRemark,
5247 "execution halted by user interrupt.");
5248 if (log)
5249 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5250 "eBroadcastBitInterrupted, exiting.");
5251 break;
5252 } else {
5253 stop_state =
5254 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5255 if (log)
5256 log->Printf(
5257 "Process::RunThreadPlan(): in while loop, got event: %s.",
5258 StateAsCString(stop_state));
5259
5260 switch (stop_state) {
5261 case lldb::eStateStopped: {
5262 // We stopped, figure out what we are going to do now.
5263 ThreadSP thread_sp =
5264 GetThreadList().FindThreadByIndexID(thread_idx_id);
5265 if (!thread_sp) {
5266 // Ooh, our thread has vanished. Unlikely that this was
5267 // successful execution...
5268 if (log)
5269 log->Printf("Process::RunThreadPlan(): execution completed "
5270 "but our thread (index-id=%u) has vanished.",
5271 thread_idx_id);
5272 return_value = eExpressionInterrupted;
5273 } else {
5274 // If we were restarted, we just need to go back up to fetch
5275 // another event.
5276 if (Process::ProcessEventData::GetRestartedFromEvent(
5277 event_sp.get())) {
5278 if (log) {
5279 log->Printf("Process::RunThreadPlan(): Got a stop and "
5280 "restart, so we'll continue waiting.");
5281 }
5282 keep_going = true;
5283 do_resume = false;
5284 handle_running_event = true;
5285 } else {
5286 StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
5287 StopReason stop_reason = eStopReasonInvalid;
5288 if (stop_info_sp)
5289 stop_reason = stop_info_sp->GetStopReason();
5290
5291 // FIXME: We only check if the stop reason is plan complete,
5292 // should we make sure that
5293 // it is OUR plan that is complete?
5294 if (stop_reason == eStopReasonPlanComplete) {
5295 if (log)
5296 log->PutCString("Process::RunThreadPlan(): execution "
5297 "completed successfully.");
5298
5299 // Restore the plan state so it will get reported as
5300 // intended when we are done.
5301 thread_plan_restorer.Clean();
5302
5303 return_value = eExpressionCompleted;
5304 } else {
5305 // Something restarted the target, so just wait for it to
5306 // stop for real.
5307 if (stop_reason == eStopReasonBreakpoint) {
5308 if (log)
5309 log->Printf("Process::RunThreadPlan() stopped for "
5310 "breakpoint: %s.",
5311 stop_info_sp->GetDescription());
5312 return_value = eExpressionHitBreakpoint;
5313 if (!options.DoesIgnoreBreakpoints()) {
5314 // Restore the plan state and then force Private to
5315 // false. We are
5316 // going to stop because of this plan so we need it to
5317 // become a public
5318 // plan or it won't report correctly when we continue to
5319 // its termination
5320 // later on.
5321 thread_plan_restorer.Clean();
5322 if (thread_plan_sp)
5323 thread_plan_sp->SetPrivate(false);
5324 event_to_broadcast_sp = event_sp;
5325 }
5326 } else {
5327 if (log)
5328 log->PutCString("Process::RunThreadPlan(): thread plan "
5329 "didn't successfully complete.");
5330 if (!options.DoesUnwindOnError())
5331 event_to_broadcast_sp = event_sp;
5332 return_value = eExpressionInterrupted;
5333 }
5334 }
5335 }
5336 }
5337 } break;
5338
5339 case lldb::eStateRunning:
5340 // This shouldn't really happen, but sometimes we do get two
5341 // running events without an
5342 // intervening stop, and in that case we should just go back to
5343 // waiting for the stop.
5344 do_resume = false;
5345 keep_going = true;
5346 handle_running_event = false;
5347 break;
5348
5349 default:
5350 if (log)
5351 log->Printf("Process::RunThreadPlan(): execution stopped with "
5352 "unexpected state: %s.",
5353 StateAsCString(stop_state));
5354
5355 if (stop_state == eStateExited)
5356 event_to_broadcast_sp = event_sp;
5357
5358 diagnostic_manager.PutCString(
5359 eDiagnosticSeverityError,
5360 "execution stopped with unexpected state.");
5361 return_value = eExpressionInterrupted;
5362 break;
5363 }
5364 }
5365
5366 if (keep_going)
5367 continue;
5368 else
5369 break;
5370 } else {
5371 if (log)
5372 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5373 "the event pointer was null. How odd...");
5374 return_value = eExpressionInterrupted;
5375 break;
5376 }
5377 } else {
5378 // If we didn't get an event that means we've timed out...
5379 // We will interrupt the process here. Depending on what we were asked
5380 // to do we will
5381 // either exit, or try with all threads running for the same timeout.
5382
5383 if (log) {
5384 if (options.GetTryAllThreads()) {
5385 if (before_first_timeout) {
5386 if (timeout_usec != 0) {
5387 log->Printf("Process::RunThreadPlan(): Running function with "
5388 "one thread timeout timed out, "
5389 "running for %" PRIu32
5390 " usec with all threads enabled.",
5391 all_threads_timeout_usec);
5392 } else {
5393 log->Printf("Process::RunThreadPlan(): Running function with "
5394 "one thread timeout timed out, "
5395 "running forever with all threads enabled.");
5396 }
5397 } else
5398 log->Printf("Process::RunThreadPlan(): Restarting function with "
5399 "all threads enabled "
5400 "and timeout: %u timed out, abandoning execution.",
5401 timeout_usec);
5402 } else
5403 log->Printf("Process::RunThreadPlan(): Running function with "
5404 "timeout: %u timed out, "
5405 "abandoning execution.",
5406 timeout_usec);
5407 }
5408
5409 // It is possible that between the time we issued the Halt, and we get
5410 // around to calling Halt the target
5411 // could have stopped. That's fine, Halt will figure that out and send
5412 // the appropriate Stopped event.
5413 // BUT it is also possible that we stopped & restarted (e.g. hit a
5414 // signal with "stop" set to false.) In
5415 // that case, we'll get the stopped & restarted event, and we should go
5416 // back to waiting for the Halt's
5417 // stopped event. That's what this while loop does.
5418
5419 bool back_to_top = true;
5420 uint32_t try_halt_again = 0;
5421 bool do_halt = true;
5422 const uint32_t num_retries = 5;
5423 while (try_halt_again < num_retries) {
5424 Error halt_error;
5425 if (do_halt) {
5426 if (log)
5427 log->Printf("Process::RunThreadPlan(): Running Halt.");
5428 const bool clear_thread_plans = false;
5429 const bool use_run_lock = false;
5430 Halt(clear_thread_plans, use_run_lock);
5431 }
5432 if (halt_error.Success()) {
5433 if (log)
5434 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5435
5436 got_event = listener_sp->WaitForEvent(
5437 std::chrono::microseconds(500000), event_sp);
5438
5439 if (got_event) {
5440 stop_state =
5441 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5442 if (log) {
5443 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5444 StateAsCString(stop_state));
5445 if (stop_state == lldb::eStateStopped &&
5446 Process::ProcessEventData::GetInterruptedFromEvent(
5447 event_sp.get()))
5448 log->PutCString(" Event was the Halt interruption event.");
5449 }
5450
5451 if (stop_state == lldb::eStateStopped) {
5452 // Between the time we initiated the Halt and the time we
5453 // delivered it, the process could have
5454 // already finished its job. Check that here:
5455
5456 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5457 if (log)
5458 log->PutCString("Process::RunThreadPlan(): Even though we "
5459 "timed out, the call plan was done. "
5460 "Exiting wait loop.");
5461 return_value = eExpressionCompleted;
5462 back_to_top = false;
5463 break;
5464 }
5465
5466 if (Process::ProcessEventData::GetRestartedFromEvent(
5467 event_sp.get())) {
5468 if (log)
5469 log->PutCString("Process::RunThreadPlan(): Went to halt "
5470 "but got a restarted event, there must be "
5471 "an un-restarted stopped event so try "
5472 "again... "
5473 "Exiting wait loop.");
5474 try_halt_again++;
5475 do_halt = false;
5476 continue;
5477 }
5478
5479 if (!options.GetTryAllThreads()) {
5480 if (log)
5481 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5482 "was false, we stopped so now we're "
5483 "quitting.");
5484 return_value = eExpressionInterrupted;
5485 back_to_top = false;
5486 break;
5487 }
5488
5489 if (before_first_timeout) {
5490 // Set all the other threads to run, and return to the top of
5491 // the loop, which will continue;
5492 before_first_timeout = false;
5493 thread_plan_sp->SetStopOthers(false);
5494 if (log)
5495 log->PutCString(
5496 "Process::RunThreadPlan(): about to resume.");
5497
5498 back_to_top = true;
5499 break;
5500 } else {
5501 // Running all threads failed, so return Interrupted.
5502 if (log)
5503 log->PutCString("Process::RunThreadPlan(): running all "
5504 "threads timed out.");
5505 return_value = eExpressionInterrupted;
5506 back_to_top = false;
5507 break;
5508 }
5509 }
5510 } else {
5511 if (log)
5512 log->PutCString("Process::RunThreadPlan(): halt said it "
5513 "succeeded, but I got no event. "
5514 "I'm getting out of here passing Interrupted.");
5515 return_value = eExpressionInterrupted;
5516 back_to_top = false;
5517 break;
5518 }
5519 } else {
5520 try_halt_again++;
5521 continue;
5522 }
5523 }
5524
5525 if (!back_to_top || try_halt_again > num_retries)
5526 break;
5527 else
5528 continue;
5529 }
5530 } // END WAIT LOOP
5531
5532 // If we had to start up a temporary private state thread to run this thread
5533 // plan, shut it down now.
5534 if (backup_private_state_thread.IsJoinable()) {
5535 StopPrivateStateThread();
5536 Error error;
5537 m_private_state_thread = backup_private_state_thread;
5538 if (stopper_base_plan_sp) {
5539 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5540 }
5541 if (old_state != eStateInvalid)
5542 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005543 }
5544
Kate Stoneb9c1b512016-09-06 20:57:50 +00005545 if (return_value != eExpressionCompleted && log) {
5546 // Print a backtrace into the log so we can figure out where we are:
5547 StreamString s;
5548 s.PutCString("Thread state after unsuccessful completion: \n");
5549 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
5550 log->PutCString(s.GetData());
Jason Molendaef7d6412015-08-06 03:27:10 +00005551 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005552 // Restore the thread state if we are going to discard the plan execution.
5553 // There are three cases where this
5554 // could happen:
5555 // 1) The execution successfully completed
5556 // 2) We hit a breakpoint, and ignore_breakpoints was true
5557 // 3) We got some other error, and discard_on_error was true
5558 bool should_unwind = (return_value == eExpressionInterrupted &&
5559 options.DoesUnwindOnError()) ||
5560 (return_value == eExpressionHitBreakpoint &&
5561 options.DoesIgnoreBreakpoints());
5562
5563 if (return_value == eExpressionCompleted || should_unwind) {
5564 thread_plan_sp->RestoreThreadState();
5565 }
5566
5567 // Now do some processing on the results of the run:
5568 if (return_value == eExpressionInterrupted ||
5569 return_value == eExpressionHitBreakpoint) {
5570 if (log) {
5571 StreamString s;
5572 if (event_sp)
5573 event_sp->Dump(&s);
5574 else {
5575 log->PutCString("Process::RunThreadPlan(): Stop event that "
5576 "interrupted us is NULL.");
5577 }
5578
5579 StreamString ts;
5580
5581 const char *event_explanation = nullptr;
5582
5583 do {
5584 if (!event_sp) {
5585 event_explanation = "<no event>";
5586 break;
5587 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5588 event_explanation = "<user interrupt>";
5589 break;
5590 } else {
5591 const Process::ProcessEventData *event_data =
5592 Process::ProcessEventData::GetEventDataFromEvent(
5593 event_sp.get());
5594
5595 if (!event_data) {
5596 event_explanation = "<no event data>";
5597 break;
5598 }
5599
5600 Process *process = event_data->GetProcessSP().get();
5601
5602 if (!process) {
5603 event_explanation = "<no process>";
5604 break;
5605 }
5606
5607 ThreadList &thread_list = process->GetThreadList();
5608
5609 uint32_t num_threads = thread_list.GetSize();
5610 uint32_t thread_index;
5611
5612 ts.Printf("<%u threads> ", num_threads);
5613
5614 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5615 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5616
5617 if (!thread) {
5618 ts.Printf("<?> ");
5619 continue;
5620 }
5621
5622 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5623 RegisterContext *register_context =
5624 thread->GetRegisterContext().get();
5625
5626 if (register_context)
5627 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5628 else
5629 ts.Printf("[ip unknown] ");
5630
5631 // Show the private stop info here, the public stop info will be
5632 // from the last natural stop.
5633 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5634 if (stop_info_sp) {
5635 const char *stop_desc = stop_info_sp->GetDescription();
5636 if (stop_desc)
5637 ts.PutCString(stop_desc);
5638 }
5639 ts.Printf(">");
5640 }
5641
5642 event_explanation = ts.GetData();
5643 }
5644 } while (0);
5645
5646 if (event_explanation)
5647 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5648 s.GetData(), event_explanation);
5649 else
5650 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5651 s.GetData());
5652 }
5653
5654 if (should_unwind) {
5655 if (log)
5656 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5657 "discarding thread plans up to %p.",
5658 static_cast<void *>(thread_plan_sp.get()));
5659 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5660 } else {
5661 if (log)
5662 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5663 "plan: %p not discarding.",
5664 static_cast<void *>(thread_plan_sp.get()));
5665 }
5666 } else if (return_value == eExpressionSetupError) {
5667 if (log)
5668 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5669
5670 if (options.DoesUnwindOnError()) {
5671 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5672 }
5673 } else {
5674 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5675 if (log)
5676 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5677 return_value = eExpressionCompleted;
5678 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5679 if (log)
5680 log->PutCString(
5681 "Process::RunThreadPlan(): thread plan was discarded");
5682 return_value = eExpressionDiscarded;
5683 } else {
5684 if (log)
5685 log->PutCString(
5686 "Process::RunThreadPlan(): thread plan stopped in mid course");
5687 if (options.DoesUnwindOnError() && thread_plan_sp) {
5688 if (log)
5689 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5690 "'cause unwind_on_error is set.");
5691 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5692 }
5693 }
5694 }
5695
5696 // Thread we ran the function in may have gone away because we ran the
5697 // target
5698 // Check that it's still there, and if it is put it back in the context.
5699 // Also restore the
5700 // frame in the context if it is still present.
5701 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5702 if (thread) {
5703 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5704 }
5705
5706 // Also restore the current process'es selected frame & thread, since this
5707 // function calling may
5708 // be done behind the user's back.
5709
5710 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5711 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5712 selected_stack_id.IsValid()) {
5713 // We were able to restore the selected thread, now restore the frame:
5714 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5715 StackFrameSP old_frame_sp =
5716 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5717 selected_stack_id);
5718 if (old_frame_sp)
5719 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5720 old_frame_sp.get());
5721 }
5722 }
5723 }
5724
5725 // If the process exited during the run of the thread plan, notify everyone.
5726
5727 if (event_to_broadcast_sp) {
5728 if (log)
5729 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5730 BroadcastEvent(event_to_broadcast_sp);
5731 }
5732
5733 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005734}
5735
Kate Stoneb9c1b512016-09-06 20:57:50 +00005736const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5737 const char *result_name;
5738
5739 switch (result) {
5740 case eExpressionCompleted:
5741 result_name = "eExpressionCompleted";
5742 break;
5743 case eExpressionDiscarded:
5744 result_name = "eExpressionDiscarded";
5745 break;
5746 case eExpressionInterrupted:
5747 result_name = "eExpressionInterrupted";
5748 break;
5749 case eExpressionHitBreakpoint:
5750 result_name = "eExpressionHitBreakpoint";
5751 break;
5752 case eExpressionSetupError:
5753 result_name = "eExpressionSetupError";
5754 break;
5755 case eExpressionParseError:
5756 result_name = "eExpressionParseError";
5757 break;
5758 case eExpressionResultUnavailable:
5759 result_name = "eExpressionResultUnavailable";
5760 break;
5761 case eExpressionTimedOut:
5762 result_name = "eExpressionTimedOut";
5763 break;
5764 case eExpressionStoppedForDebug:
5765 result_name = "eExpressionStoppedForDebug";
5766 break;
5767 }
5768 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005769}
5770
Kate Stoneb9c1b512016-09-06 20:57:50 +00005771void Process::GetStatus(Stream &strm) {
5772 const StateType state = GetState();
5773 if (StateIsStoppedState(state, false)) {
5774 if (state == eStateExited) {
5775 int exit_status = GetExitStatus();
5776 const char *exit_description = GetExitDescription();
5777 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5778 GetID(), exit_status, exit_status,
5779 exit_description ? exit_description : "");
5780 } else {
5781 if (state == eStateConnected)
5782 strm.Printf("Connected to remote target.\n");
5783 else
5784 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5785 }
5786 } else {
5787 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5788 }
Pavel Labatha933d512016-04-05 13:07:16 +00005789}
5790
Kate Stoneb9c1b512016-09-06 20:57:50 +00005791size_t Process::GetThreadStatus(Stream &strm,
5792 bool only_threads_with_stop_reason,
5793 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005794 uint32_t num_frames_with_source,
5795 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005796 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005797
Kate Stoneb9c1b512016-09-06 20:57:50 +00005798 // You can't hold the thread list lock while calling Thread::GetStatus. That
5799 // very well might run code (e.g. if we need it
5800 // to get return values or arguments.) For that to work the process has to be
5801 // able to acquire it. So instead copy the thread
5802 // ID's, and look them up one by one:
5803
5804 uint32_t num_threads;
5805 std::vector<lldb::tid_t> thread_id_array;
5806 // Scope for thread list locker;
5807 {
5808 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5809 ThreadList &curr_thread_list = GetThreadList();
5810 num_threads = curr_thread_list.GetSize();
5811 uint32_t idx;
5812 thread_id_array.resize(num_threads);
5813 for (idx = 0; idx < num_threads; ++idx)
5814 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5815 }
5816
5817 for (uint32_t i = 0; i < num_threads; i++) {
5818 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5819 if (thread_sp) {
5820 if (only_threads_with_stop_reason) {
5821 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5822 if (!stop_info_sp || !stop_info_sp->IsValid())
5823 continue;
5824 }
5825 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005826 num_frames_with_source,
5827 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005828 ++num_thread_infos_dumped;
5829 } else {
5830 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5831 if (log)
5832 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5833 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005834 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005835 }
5836 return num_thread_infos_dumped;
5837}
5838
5839void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5840 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5841}
5842
5843bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5844 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5845 region.GetByteSize());
5846}
5847
5848void Process::AddPreResumeAction(PreResumeActionCallback callback,
5849 void *baton) {
5850 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5851}
5852
5853bool Process::RunPreResumeActions() {
5854 bool result = true;
5855 while (!m_pre_resume_actions.empty()) {
5856 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5857 m_pre_resume_actions.pop_back();
5858 bool this_result = action.callback(action.baton);
5859 if (result)
5860 result = this_result;
5861 }
5862 return result;
5863}
5864
5865void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5866
Jim Inghamffd91752016-10-20 22:50:00 +00005867void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5868{
5869 PreResumeCallbackAndBaton element(callback, baton);
5870 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5871 if (found_iter != m_pre_resume_actions.end())
5872 {
5873 m_pre_resume_actions.erase(found_iter);
5874 }
5875}
5876
Kate Stoneb9c1b512016-09-06 20:57:50 +00005877ProcessRunLock &Process::GetRunLock() {
5878 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5879 return m_private_run_lock;
5880 else
5881 return m_public_run_lock;
5882}
5883
5884void Process::Flush() {
5885 m_thread_list.Flush();
5886 m_extended_thread_list.Flush();
5887 m_extended_thread_stop_id = 0;
5888 m_queue_list.Clear();
5889 m_queue_list_stop_id = 0;
5890}
5891
5892void Process::DidExec() {
5893 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5894 if (log)
5895 log->Printf("Process::%s()", __FUNCTION__);
5896
5897 Target &target = GetTarget();
5898 target.CleanupProcess();
5899 target.ClearModules(false);
5900 m_dynamic_checkers_ap.reset();
5901 m_abi_sp.reset();
5902 m_system_runtime_ap.reset();
5903 m_os_ap.reset();
5904 m_dyld_ap.reset();
5905 m_jit_loaders_ap.reset();
5906 m_image_tokens.clear();
5907 m_allocated_memory_cache.Clear();
5908 m_language_runtimes.clear();
5909 m_instrumentation_runtimes.clear();
5910 m_thread_list.DiscardThreadPlans();
5911 m_memory_cache.Clear(true);
5912 m_stop_info_override_callback = nullptr;
5913 DoDidExec();
5914 CompleteAttach();
5915 // Flush the process (threads and all stack frames) after running
5916 // CompleteAttach()
5917 // in case the dynamic loader loaded things in new locations.
5918 Flush();
5919
5920 // After we figure out what was loaded/unloaded in CompleteAttach,
5921 // we need to let the target know so it can do any cleanup it needs to.
5922 target.DidExec();
5923}
5924
5925addr_t Process::ResolveIndirectFunction(const Address *address, Error &error) {
5926 if (address == nullptr) {
5927 error.SetErrorString("Invalid address argument");
5928 return LLDB_INVALID_ADDRESS;
5929 }
5930
5931 addr_t function_addr = LLDB_INVALID_ADDRESS;
5932
5933 addr_t addr = address->GetLoadAddress(&GetTarget());
5934 std::map<addr_t, addr_t>::const_iterator iter =
5935 m_resolved_indirect_addresses.find(addr);
5936 if (iter != m_resolved_indirect_addresses.end()) {
5937 function_addr = (*iter).second;
5938 } else {
5939 if (!InferiorCall(this, address, function_addr)) {
5940 Symbol *symbol = address->CalculateSymbolContextSymbol();
5941 error.SetErrorStringWithFormat(
5942 "Unable to call resolver for indirect function %s",
5943 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5944 function_addr = LLDB_INVALID_ADDRESS;
5945 } else {
5946 m_resolved_indirect_addresses.insert(
5947 std::pair<addr_t, addr_t>(addr, function_addr));
5948 }
5949 }
5950 return function_addr;
5951}
5952
5953void Process::ModulesDidLoad(ModuleList &module_list) {
5954 SystemRuntime *sys_runtime = GetSystemRuntime();
5955 if (sys_runtime) {
5956 sys_runtime->ModulesDidLoad(module_list);
5957 }
5958
5959 GetJITLoaders().ModulesDidLoad(module_list);
5960
5961 // Give runtimes a chance to be created.
5962 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5963 m_instrumentation_runtimes);
5964
5965 // Tell runtimes about new modules.
5966 for (auto pos = m_instrumentation_runtimes.begin();
5967 pos != m_instrumentation_runtimes.end(); ++pos) {
5968 InstrumentationRuntimeSP runtime = pos->second;
5969 runtime->ModulesDidLoad(module_list);
5970 }
5971
5972 // Let any language runtimes we have already created know
5973 // about the modules that loaded.
5974
5975 // Iterate over a copy of this language runtime list in case
5976 // the language runtime ModulesDidLoad somehow causes the language
5977 // riuntime to be unloaded.
5978 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5979 for (const auto &pair : language_runtimes) {
5980 // We must check language_runtime_sp to make sure it is not
5981 // nullptr as we might cache the fact that we didn't have a
5982 // language runtime for a language.
5983 LanguageRuntimeSP language_runtime_sp = pair.second;
5984 if (language_runtime_sp)
5985 language_runtime_sp->ModulesDidLoad(module_list);
5986 }
5987
5988 // If we don't have an operating system plug-in, try to load one since
5989 // loading shared libraries might cause a new one to try and load
5990 if (!m_os_ap)
5991 LoadOperatingSystemPlugin(false);
5992
5993 // Give structured-data plugins a chance to see the modified modules.
5994 for (auto pair : m_structured_data_plugin_map) {
5995 if (pair.second)
5996 pair.second->ModulesDidLoad(*this, module_list);
5997 }
5998}
5999
6000void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
6001 const char *fmt, ...) {
6002 bool print_warning = true;
6003
6004 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
6005 if (!stream_sp)
6006 return;
6007 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
6008 return;
6009 }
6010
6011 if (repeat_key != nullptr) {
6012 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
6013 if (it == m_warnings_issued.end()) {
6014 m_warnings_issued[warning_type] = WarningsPointerSet();
6015 m_warnings_issued[warning_type].insert(repeat_key);
6016 } else {
6017 if (it->second.find(repeat_key) != it->second.end()) {
6018 print_warning = false;
6019 } else {
6020 it->second.insert(repeat_key);
6021 }
6022 }
6023 }
6024
6025 if (print_warning) {
6026 va_list args;
6027 va_start(args, fmt);
6028 stream_sp->PrintfVarArg(fmt, args);
6029 va_end(args);
6030 }
6031}
6032
6033void Process::PrintWarningOptimization(const SymbolContext &sc) {
6034 if (GetWarningsOptimization() && sc.module_sp &&
6035 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
6036 sc.function->GetIsOptimized()) {
6037 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
6038 "%s was compiled with optimization - stepping may behave "
6039 "oddly; variables may not be available.\n",
6040 sc.module_sp->GetFileSpec().GetFilename().GetCString());
6041 }
6042}
6043
6044bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
6045 info.Clear();
6046
6047 PlatformSP platform_sp = GetTarget().GetPlatform();
6048 if (!platform_sp)
6049 return false;
6050
6051 return platform_sp->GetProcessInfo(GetID(), info);
6052}
6053
6054ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
6055 ThreadCollectionSP threads;
6056
6057 const MemoryHistorySP &memory_history =
6058 MemoryHistory::FindPlugin(shared_from_this());
6059
6060 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00006061 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006062 }
6063
6064 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6065
6066 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00006067}
Kuba Brecka63927542014-10-11 01:59:32 +00006068
6069InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00006070Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
6071 InstrumentationRuntimeCollection::iterator pos;
6072 pos = m_instrumentation_runtimes.find(type);
6073 if (pos == m_instrumentation_runtimes.end()) {
6074 return InstrumentationRuntimeSP();
6075 } else
6076 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00006077}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006078
Kate Stoneb9c1b512016-09-06 20:57:50 +00006079bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6080 const ArchSpec &arch, ModuleSpec &module_spec) {
6081 module_spec.Clear();
6082 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006083}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006084
Kate Stoneb9c1b512016-09-06 20:57:50 +00006085size_t Process::AddImageToken(lldb::addr_t image_ptr) {
6086 m_image_tokens.push_back(image_ptr);
6087 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006088}
6089
Kate Stoneb9c1b512016-09-06 20:57:50 +00006090lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
6091 if (token < m_image_tokens.size())
6092 return m_image_tokens[token];
6093 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006094}
6095
Kate Stoneb9c1b512016-09-06 20:57:50 +00006096void Process::ResetImageToken(size_t token) {
6097 if (token < m_image_tokens.size())
6098 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00006099}
Jason Molendafd4cea52016-01-08 21:40:11 +00006100
6101Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00006102Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
6103 AddressRange range_bounds) {
6104 Target &target = GetTarget();
6105 DisassemblerSP disassembler_sp;
6106 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006107
Kate Stoneb9c1b512016-09-06 20:57:50 +00006108 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006109
Kate Stoneb9c1b512016-09-06 20:57:50 +00006110 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00006111 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006112 if (!default_stop_addr.IsValid())
6113 return retval;
6114
6115 ExecutionContext exe_ctx(this);
6116 const char *plugin_name = nullptr;
6117 const char *flavor = nullptr;
6118 const bool prefer_file_cache = true;
6119 disassembler_sp = Disassembler::DisassembleRange(
6120 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6121 prefer_file_cache);
6122 if (disassembler_sp)
6123 insn_list = &disassembler_sp->GetInstructionList();
6124
6125 if (insn_list == nullptr) {
6126 return retval;
6127 }
6128
6129 size_t insn_offset =
6130 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6131 if (insn_offset == UINT32_MAX) {
6132 return retval;
6133 }
6134
6135 uint32_t branch_index =
6136 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6137 if (branch_index == UINT32_MAX) {
6138 return retval;
6139 }
6140
6141 if (branch_index > insn_offset) {
6142 Address next_branch_insn_address =
6143 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6144 if (next_branch_insn_address.IsValid() &&
6145 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6146 retval = next_branch_insn_address;
6147 }
6148 }
6149
6150 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00006151}
Howard Hellyerad007562016-07-07 08:21:28 +00006152
Kate Stoneb9c1b512016-09-06 20:57:50 +00006153Error Process::GetMemoryRegions(
6154 std::vector<lldb::MemoryRegionInfoSP> &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00006155
Kate Stoneb9c1b512016-09-06 20:57:50 +00006156 Error error;
Howard Hellyerad007562016-07-07 08:21:28 +00006157
Kate Stoneb9c1b512016-09-06 20:57:50 +00006158 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00006159
Kate Stoneb9c1b512016-09-06 20:57:50 +00006160 region_list.clear();
6161 do {
6162 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6163 error = GetMemoryRegionInfo(range_end, *region_info);
6164 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6165 if (error.Fail()) {
6166 region_list.clear();
6167 break;
Todd Fiala75930012016-08-19 04:21:48 +00006168 }
6169
Kate Stoneb9c1b512016-09-06 20:57:50 +00006170 range_end = region_info->GetRange().GetRangeEnd();
6171 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6172 region_list.push_back(region_info);
6173 }
6174 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00006175
Kate Stoneb9c1b512016-09-06 20:57:50 +00006176 return error;
6177}
6178
6179Error Process::ConfigureStructuredData(
6180 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
6181 // If you get this, the Process-derived class needs to implement a method
6182 // to enable an already-reported asynchronous structured data feature.
6183 // See ProcessGDBRemote for an example implementation over gdb-remote.
6184 return Error("unimplemented");
6185}
6186
6187void Process::MapSupportedStructuredDataPlugins(
6188 const StructuredData::Array &supported_type_names) {
6189 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6190
6191 // Bail out early if there are no type names to map.
6192 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00006193 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006194 log->Printf("Process::%s(): no structured data types supported",
6195 __FUNCTION__);
6196 return;
6197 }
Todd Fiala75930012016-08-19 04:21:48 +00006198
Kate Stoneb9c1b512016-09-06 20:57:50 +00006199 // Convert StructuredData type names to ConstString instances.
6200 std::set<ConstString> const_type_names;
6201
6202 if (log)
6203 log->Printf("Process::%s(): the process supports the following async "
6204 "structured data types:",
6205 __FUNCTION__);
6206
6207 supported_type_names.ForEach(
6208 [&const_type_names, &log](StructuredData::Object *object) {
6209 if (!object) {
6210 // Invalid - shouldn't be null objects in the array.
6211 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006212 }
6213
6214 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006215 if (!type_name) {
6216 // Invalid format - all type names should be strings.
6217 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006218 }
6219
6220 const_type_names.insert(ConstString(type_name->GetValue()));
6221 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006222 log->Printf("- %s", type_name->GetValue().c_str());
Todd Fiala75930012016-08-19 04:21:48 +00006223 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006224 });
Todd Fiala75930012016-08-19 04:21:48 +00006225
Kate Stoneb9c1b512016-09-06 20:57:50 +00006226 // For each StructuredDataPlugin, if the plugin handles any of the
6227 // types in the supported_type_names, map that type name to that plugin.
6228 uint32_t plugin_index = 0;
6229 for (auto create_instance =
6230 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6231 plugin_index);
6232 create_instance && !const_type_names.empty(); ++plugin_index) {
6233 // Create the plugin.
6234 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6235 if (!plugin_sp) {
6236 // This plugin doesn't think it can work with the process.
6237 // Move on to the next.
6238 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006239 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006240
6241 // For any of the remaining type names, map any that this plugin
6242 // supports.
6243 std::vector<ConstString> names_to_remove;
6244 for (auto &type_name : const_type_names) {
6245 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6246 m_structured_data_plugin_map.insert(
6247 std::make_pair(type_name, plugin_sp));
6248 names_to_remove.push_back(type_name);
6249 if (log)
6250 log->Printf("Process::%s(): using plugin %s for type name "
6251 "%s",
6252 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6253 type_name.GetCString());
6254 }
6255 }
6256
6257 // Remove the type names that were consumed by this plugin.
6258 for (auto &type_name : names_to_remove)
6259 const_type_names.erase(type_name);
6260 }
Todd Fiala75930012016-08-19 04:21:48 +00006261}
6262
Kate Stoneb9c1b512016-09-06 20:57:50 +00006263bool Process::RouteAsyncStructuredData(
6264 const StructuredData::ObjectSP object_sp) {
6265 // Nothing to do if there's no data.
6266 if (!object_sp)
6267 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006268
Kate Stoneb9c1b512016-09-06 20:57:50 +00006269 // The contract is this must be a dictionary, so we can look up the
6270 // routing key via the top-level 'type' string value within the dictionary.
6271 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6272 if (!dictionary)
6273 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006274
Kate Stoneb9c1b512016-09-06 20:57:50 +00006275 // Grab the async structured type name (i.e. the feature/plugin name).
6276 ConstString type_name;
6277 if (!dictionary->GetValueForKeyAsString("type", type_name))
6278 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006279
Kate Stoneb9c1b512016-09-06 20:57:50 +00006280 // Check if there's a plugin registered for this type name.
6281 auto find_it = m_structured_data_plugin_map.find(type_name);
6282 if (find_it == m_structured_data_plugin_map.end()) {
6283 // We don't have a mapping for this structured data type.
6284 return false;
6285 }
Todd Fiala75930012016-08-19 04:21:48 +00006286
Kate Stoneb9c1b512016-09-06 20:57:50 +00006287 // Route the structured data to the plugin.
6288 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6289 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006290}