blob: ad0c13437088d6b9659748b5c9d73c2471bad175 [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
Pavel Labathd35031e12016-11-30 10:41:42 +000071// A temporary function to convert between old representations of timeouts (0
72// means infinite wait) and new Timeout class (0 means "poll").
73// TODO(labath): Fix up all callers and remove this.
74static Timeout<std::micro> ConvertTimeout(std::chrono::microseconds t) {
75 if (t == std::chrono::microseconds(0))
76 return llvm::None;
77 return t;
78}
79
Kate Stoneb9c1b512016-09-06 20:57:50 +000080// Comment out line below to disable memory caching, overriding the process
81// setting
Greg Clayton67cc0632012-08-22 17:17:09 +000082// target.process.disable-memory-cache
83#define ENABLE_MEMORY_CACHING
84
85#ifdef ENABLE_MEMORY_CACHING
86#define DISABLE_MEM_CACHE_DEFAULT false
87#else
88#define DISABLE_MEM_CACHE_DEFAULT true
89#endif
90
Kate Stoneb9c1b512016-09-06 20:57:50 +000091class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000092public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000093 ProcessOptionValueProperties(const ConstString &name)
94 : OptionValueProperties(name) {}
95
96 // This constructor is used when creating ProcessOptionValueProperties when it
97 // is part of a new lldb_private::Process instance. It will copy all current
98 // global property values as needed
99 ProcessOptionValueProperties(ProcessProperties *global_properties)
100 : OptionValueProperties(*global_properties->GetValueProperties()) {}
101
102 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
103 bool will_modify,
104 uint32_t idx) const override {
105 // When getting the value for a key from the process options, we will always
106 // try and grab the setting from the current process if there is one. Else
107 // we just
108 // use the one from this instance.
109 if (exe_ctx) {
110 Process *process = exe_ctx->GetProcessPtr();
111 if (process) {
112 ProcessOptionValueProperties *instance_properties =
113 static_cast<ProcessOptionValueProperties *>(
114 process->GetValueProperties().get());
115 if (this != instance_properties)
116 return instance_properties->ProtectedGetPropertyAtIndex(idx);
117 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000118 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 return ProtectedGetPropertyAtIndex(idx);
120 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000121};
122
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123static PropertyDefinition g_properties[] = {
124 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
125 DISABLE_MEM_CACHE_DEFAULT, nullptr, nullptr,
126 "Disable reading and caching of memory in fixed-size units."},
127 {"extra-startup-command", OptionValue::eTypeArray, false,
128 OptionValue::eTypeString, nullptr, nullptr,
129 "A list containing extra commands understood by the particular process "
130 "plugin used. "
131 "For instance, to turn on debugserver logging set this to "
132 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
133 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
134 nullptr, nullptr,
135 "If true, breakpoints will be ignored during expression evaluation."},
136 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
137 nullptr, nullptr, "If true, errors in expression evaluation will unwind "
138 "the stack back to the state before the call."},
139 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
140 nullptr, "A path to a python OS plug-in module file that contains a "
141 "OperatingSystemPlugIn class."},
142 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
143 nullptr, nullptr,
144 "If true, stop when a shared library is loaded or unloaded."},
145 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
146 nullptr, "If true, detach will attempt to keep the process stopped."},
147 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
148 nullptr, "The memory cache line size"},
149 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
150 nullptr, "If true, warn when stopped in code that is optimized where "
151 "stepping and variable availability may not behave as expected."},
152 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000153
154enum {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 ePropertyDisableMemCache,
156 ePropertyExtraStartCommand,
157 ePropertyIgnoreBreakpointsInExpressions,
158 ePropertyUnwindOnErrorInExpressions,
159 ePropertyPythonOSPluginPath,
160 ePropertyStopOnSharedLibraryEvents,
161 ePropertyDetachKeepsStopped,
162 ePropertyMemCacheLineSize,
163 ePropertyWarningOptimization
Greg Clayton67cc0632012-08-22 17:17:09 +0000164};
165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166ProcessProperties::ProcessProperties(lldb_private::Process *process)
167 : Properties(),
168 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000169{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170 if (process == nullptr) {
171 // Global process properties, set them up one time
172 m_collection_sp.reset(
173 new ProcessOptionValueProperties(ConstString("process")));
174 m_collection_sp->Initialize(g_properties);
175 m_collection_sp->AppendProperty(
176 ConstString("thread"), ConstString("Settings specific to threads."),
177 true, Thread::GetGlobalProperties()->GetValueProperties());
178 } else {
179 m_collection_sp.reset(
180 new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
181 m_collection_sp->SetValueChangedCallback(
182 ePropertyPythonOSPluginPath,
183 ProcessProperties::OptionValueChangedCallback, this);
184 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000185}
186
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000187ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000188
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189void ProcessProperties::OptionValueChangedCallback(void *baton,
190 OptionValue *option_value) {
191 ProcessProperties *properties = (ProcessProperties *)baton;
192 if (properties->m_process)
193 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000194}
195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196bool ProcessProperties::GetDisableMemoryCache() const {
197 const uint32_t idx = ePropertyDisableMemCache;
198 return m_collection_sp->GetPropertyAtIndexAsBoolean(
199 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000200}
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
203 const uint32_t idx = ePropertyMemCacheLineSize;
204 return m_collection_sp->GetPropertyAtIndexAsUInt64(
205 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000206}
207
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208Args ProcessProperties::GetExtraStartupCommands() const {
209 Args args;
210 const uint32_t idx = ePropertyExtraStartCommand;
211 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
212 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000213}
214
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215void ProcessProperties::SetExtraStartupCommands(const Args &args) {
216 const uint32_t idx = ePropertyExtraStartCommand;
217 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000218}
219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220FileSpec ProcessProperties::GetPythonOSPluginPath() const {
221 const uint32_t idx = ePropertyPythonOSPluginPath;
222 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000223}
224
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
226 const uint32_t idx = ePropertyPythonOSPluginPath;
227 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000228}
229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
231 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
232 return m_collection_sp->GetPropertyAtIndexAsBoolean(
233 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000234}
235
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
237 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
238 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000239}
240
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
242 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
243 return m_collection_sp->GetPropertyAtIndexAsBoolean(
244 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000245}
246
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
248 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
249 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000250}
251
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
253 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
254 return m_collection_sp->GetPropertyAtIndexAsBoolean(
255 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000256}
257
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
259 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
260 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
261}
262
263bool ProcessProperties::GetDetachKeepsStopped() const {
264 const uint32_t idx = ePropertyDetachKeepsStopped;
265 return m_collection_sp->GetPropertyAtIndexAsBoolean(
266 nullptr, idx, g_properties[idx].default_uint_value != 0);
267}
268
269void ProcessProperties::SetDetachKeepsStopped(bool stop) {
270 const uint32_t idx = ePropertyDetachKeepsStopped;
271 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
272}
273
274bool ProcessProperties::GetWarningsOptimization() const {
275 const uint32_t idx = ePropertyWarningOptimization;
276 return m_collection_sp->GetPropertyAtIndexAsBoolean(
277 nullptr, idx, g_properties[idx].default_uint_value != 0);
278}
279
280void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const {
281 const char *cstr;
282 if (m_pid != LLDB_INVALID_PROCESS_ID)
283 s.Printf(" pid = %" PRIu64 "\n", m_pid);
284
285 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
286 s.Printf(" parent = %" PRIu64 "\n", m_parent_pid);
287
288 if (m_executable) {
289 s.Printf(" name = %s\n", m_executable.GetFilename().GetCString());
290 s.PutCString(" file = ");
291 m_executable.Dump(&s);
292 s.EOL();
293 }
294 const uint32_t argc = m_arguments.GetArgumentCount();
295 if (argc > 0) {
296 for (uint32_t i = 0; i < argc; i++) {
297 const char *arg = m_arguments.GetArgumentAtIndex(i);
298 if (i < 10)
299 s.Printf(" arg[%u] = %s\n", i, arg);
300 else
301 s.Printf("arg[%u] = %s\n", i, arg);
302 }
303 }
304
305 const uint32_t envc = m_environment.GetArgumentCount();
306 if (envc > 0) {
307 for (uint32_t i = 0; i < envc; i++) {
308 const char *env = m_environment.GetArgumentAtIndex(i);
309 if (i < 10)
310 s.Printf(" env[%u] = %s\n", i, env);
311 else
312 s.Printf("env[%u] = %s\n", i, env);
313 }
314 }
315
316 if (m_arch.IsValid()) {
317 s.Printf(" arch = ");
318 m_arch.DumpTriple(s);
319 s.EOL();
320 }
321
322 if (m_uid != UINT32_MAX) {
323 cstr = platform->GetUserName(m_uid);
324 s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
325 }
326 if (m_gid != UINT32_MAX) {
327 cstr = platform->GetGroupName(m_gid);
328 s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
329 }
330 if (m_euid != UINT32_MAX) {
331 cstr = platform->GetUserName(m_euid);
332 s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
333 }
334 if (m_egid != UINT32_MAX) {
335 cstr = platform->GetGroupName(m_egid);
336 s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
337 }
338}
339
340void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform,
341 bool show_args, bool verbose) {
342 const char *label;
343 if (show_args || verbose)
344 label = "ARGUMENTS";
345 else
346 label = "NAME";
347
348 if (verbose) {
349 s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE "
350 " %s\n",
351 label);
352 s.PutCString("====== ====== ========== ========== ========== ========== "
353 "======================== ============================\n");
354 } else {
355 s.Printf("PID PARENT USER TRIPLE %s\n", label);
356 s.PutCString("====== ====== ========== ======================== "
357 "============================\n");
358 }
359}
360
361void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform,
362 bool show_args, bool verbose) const {
363 if (m_pid != LLDB_INVALID_PROCESS_ID) {
Greg Clayton32e0a752011-03-30 18:16:51 +0000364 const char *cstr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000366
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 StreamString arch_strm;
Todd Fiala7df337f2015-10-13 23:41:19 +0000368 if (m_arch.IsValid())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 m_arch.DumpTriple(arch_strm);
370
371 if (verbose) {
372 cstr = platform->GetUserName(m_uid);
373 if (cstr &&
374 cstr[0]) // Watch for empty string that indicates lookup failed
375 s.Printf("%-10s ", cstr);
376 else
377 s.Printf("%-10u ", m_uid);
378
379 cstr = platform->GetGroupName(m_gid);
380 if (cstr &&
381 cstr[0]) // Watch for empty string that indicates lookup failed
382 s.Printf("%-10s ", cstr);
383 else
384 s.Printf("%-10u ", m_gid);
385
386 cstr = platform->GetUserName(m_euid);
387 if (cstr &&
388 cstr[0]) // Watch for empty string that indicates lookup failed
389 s.Printf("%-10s ", cstr);
390 else
391 s.Printf("%-10u ", m_euid);
392
393 cstr = platform->GetGroupName(m_egid);
394 if (cstr &&
395 cstr[0]) // Watch for empty string that indicates lookup failed
396 s.Printf("%-10s ", cstr);
397 else
398 s.Printf("%-10u ", m_egid);
399
Zachary Turnerc1564272016-11-16 21:15:24 +0000400 s.Printf("%-24s ", arch_strm.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 } else {
402 s.Printf("%-10s %-24s ", platform->GetUserName(m_euid),
Zachary Turnerc1564272016-11-16 21:15:24 +0000403 arch_strm.GetData());
Todd Fiala7df337f2015-10-13 23:41:19 +0000404 }
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000405
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 if (verbose || show_args) {
407 const uint32_t argc = m_arguments.GetArgumentCount();
408 if (argc > 0) {
409 for (uint32_t i = 0; i < argc; i++) {
410 if (i > 0)
411 s.PutChar(' ');
412 s.PutCString(m_arguments.GetArgumentAtIndex(i));
413 }
414 }
415 } else {
416 s.PutCString(GetName());
Greg Clayton32e0a752011-03-30 18:16:51 +0000417 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418
419 s.EOL();
420 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000421}
422
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423Error ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000424 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425 ExecutionContext *execution_context) {
426 Error error;
427 const int short_option = m_getopt_table[option_idx].val;
428
429 switch (short_option) {
430 case 's': // Stop at program entry point
431 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
432 break;
433
434 case 'i': // STDIN for read only
435 {
436 FileAction action;
437 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
438 launch_info.AppendFileAction(action);
439 break;
440 }
441
442 case 'o': // Open STDOUT for write only
443 {
444 FileAction action;
445 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
446 launch_info.AppendFileAction(action);
447 break;
448 }
449
450 case 'e': // STDERR for write only
451 {
452 FileAction action;
453 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
454 launch_info.AppendFileAction(action);
455 break;
456 }
457
458 case 'p': // Process plug-in name
459 launch_info.SetProcessPluginName(option_arg);
460 break;
461
462 case 'n': // Disable STDIO
463 {
464 FileAction action;
465 const FileSpec dev_null{FileSystem::DEV_NULL, false};
466 if (action.Open(STDIN_FILENO, dev_null, true, false))
467 launch_info.AppendFileAction(action);
468 if (action.Open(STDOUT_FILENO, dev_null, false, true))
469 launch_info.AppendFileAction(action);
470 if (action.Open(STDERR_FILENO, dev_null, false, true))
471 launch_info.AppendFileAction(action);
472 break;
473 }
474
475 case 'w':
476 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
477 break;
478
479 case 't': // Open process in new terminal window
480 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
481 break;
482
483 case 'a': {
484 TargetSP target_sp =
485 execution_context ? execution_context->GetTargetSP() : TargetSP();
486 PlatformSP platform_sp =
487 target_sp ? target_sp->GetPlatform() : PlatformSP();
488 if (!launch_info.GetArchitecture().SetTriple(option_arg, platform_sp.get()))
489 launch_info.GetArchitecture().SetTriple(option_arg);
490 } break;
491
492 case 'A': // Disable ASLR.
493 {
494 bool success;
495 const bool disable_aslr_arg =
Zachary Turnerfe114832016-11-12 16:56:47 +0000496 Args::StringToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 if (success)
498 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000499 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500 error.SetErrorStringWithFormat(
501 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000502 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 break;
504 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000505
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506 case 'X': // shell expand args.
507 {
508 bool success;
Zachary Turnerfe114832016-11-12 16:56:47 +0000509 const bool expand_args = Args::StringToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510 if (success)
511 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000512 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513 error.SetErrorStringWithFormat(
514 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000515 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 break;
517 }
518
519 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000520 if (!option_arg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 launch_info.SetShell(FileSpec(option_arg, false));
522 else
523 launch_info.SetShell(HostInfo::GetDefaultShell());
524 break;
525
526 case 'v':
Zachary Turnerfe114832016-11-12 16:56:47 +0000527 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 break;
529
530 default:
531 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
532 short_option);
533 break;
534 }
535 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000536}
537
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000538static OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
540 nullptr, nullptr, 0, eArgTypeNone,
541 "Stop at the entry point of the program when launching a process."},
542 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
543 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
544 "Set whether to disable address space layout randomization when launching "
545 "a process."},
546 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
547 nullptr, nullptr, 0, eArgTypePlugin,
548 "Name of the process plugin you want to use."},
549 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
550 OptionParser::eRequiredArgument, nullptr, nullptr, 0,
551 eArgTypeDirectoryName,
552 "Set the current working directory to <path> when running the inferior."},
553 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
554 nullptr, nullptr, 0, eArgTypeArchitecture,
555 "Set the architecture for the process to launch when ambiguous."},
556 {LLDB_OPT_SET_ALL, false, "environment", 'v',
557 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone,
558 "Specify an environment variable name/value string (--environment "
559 "NAME=VALUE). Can be specified multiple times for subsequent environment "
560 "entries."},
561 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
562 OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeFilename,
563 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000564
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
566 nullptr, nullptr, 0, eArgTypeFilename,
567 "Redirect stdin for the process to <filename>."},
568 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
569 nullptr, nullptr, 0, eArgTypeFilename,
570 "Redirect stdout for the process to <filename>."},
571 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
572 nullptr, nullptr, 0, eArgTypeFilename,
573 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000574
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
576 nullptr, 0, eArgTypeNone,
577 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000578
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
580 nullptr, 0, eArgTypeNone,
581 "Do not set up for terminal I/O to go to running process."},
582 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
583 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
584 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000585};
586
587llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000588 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000589}
Greg Clayton32e0a752011-03-30 18:16:51 +0000590
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
592 if (m_name_match_type == eNameMatchIgnore || process_name == nullptr)
Greg Clayton32e0a752011-03-30 18:16:51 +0000593 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594 const char *match_name = m_match_info.GetName();
595 if (!match_name)
Greg Clayton32e0a752011-03-30 18:16:51 +0000596 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597
598 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
Greg Clayton32e0a752011-03-30 18:16:51 +0000599}
600
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601bool ProcessInstanceInfoMatch::Matches(
602 const ProcessInstanceInfo &proc_info) const {
603 if (!NameMatches(proc_info.GetName()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000604 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605
606 if (m_match_info.ProcessIDIsValid() &&
607 m_match_info.GetProcessID() != proc_info.GetProcessID())
608 return false;
609
610 if (m_match_info.ParentProcessIDIsValid() &&
611 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
612 return false;
613
614 if (m_match_info.UserIDIsValid() &&
615 m_match_info.GetUserID() != proc_info.GetUserID())
616 return false;
617
618 if (m_match_info.GroupIDIsValid() &&
619 m_match_info.GetGroupID() != proc_info.GetGroupID())
620 return false;
621
622 if (m_match_info.EffectiveUserIDIsValid() &&
623 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
624 return false;
625
626 if (m_match_info.EffectiveGroupIDIsValid() &&
627 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
628 return false;
629
630 if (m_match_info.GetArchitecture().IsValid() &&
631 !m_match_info.GetArchitecture().IsCompatibleMatch(
632 proc_info.GetArchitecture()))
633 return false;
634 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000635}
636
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
638 if (m_name_match_type != eNameMatchIgnore)
639 return false;
640
641 if (m_match_info.ProcessIDIsValid())
642 return false;
643
644 if (m_match_info.ParentProcessIDIsValid())
645 return false;
646
647 if (m_match_info.UserIDIsValid())
648 return false;
649
650 if (m_match_info.GroupIDIsValid())
651 return false;
652
653 if (m_match_info.EffectiveUserIDIsValid())
654 return false;
655
656 if (m_match_info.EffectiveGroupIDIsValid())
657 return false;
658
659 if (m_match_info.GetArchitecture().IsValid())
660 return false;
661
662 if (m_match_all_users)
663 return false;
664
665 return true;
666}
667
668void ProcessInstanceInfoMatch::Clear() {
669 m_match_info.Clear();
670 m_name_match_type = eNameMatchIgnore;
671 m_match_all_users = false;
672}
673
Zachary Turner31659452016-11-17 21:15:14 +0000674ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
675 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000676 ListenerSP listener_sp,
677 const FileSpec *crash_file_path) {
678 static uint32_t g_process_unique_id = 0;
679
680 ProcessSP process_sp;
681 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000682 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000683 ConstString const_plugin_name(plugin_name);
684 create_callback =
685 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
686 if (create_callback) {
687 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
688 if (process_sp) {
689 if (process_sp->CanDebug(target_sp, true)) {
690 process_sp->m_process_unique_id = ++g_process_unique_id;
691 } else
692 process_sp.reset();
693 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000694 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 } else {
696 for (uint32_t idx = 0;
697 (create_callback =
698 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
699 ++idx) {
700 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
701 if (process_sp) {
702 if (process_sp->CanDebug(target_sp, false)) {
703 process_sp->m_process_unique_id = ++g_process_unique_id;
704 break;
705 } else
706 process_sp.reset();
707 }
708 }
709 }
710 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000711}
712
Kate Stoneb9c1b512016-09-06 20:57:50 +0000713ConstString &Process::GetStaticBroadcasterClass() {
714 static ConstString class_name("lldb.process");
715 return class_name;
716}
717
718Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
719 : Process(target_sp, listener_sp,
720 UnixSignals::Create(HostInfo::GetArchitecture())) {
721 // This constructor just delegates to the full Process constructor,
722 // defaulting to using the Host's UnixSignals.
723}
724
725Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
726 const UnixSignalsSP &unix_signals_sp)
727 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
728 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
729 Process::GetStaticBroadcasterClass().AsCString()),
730 m_target_sp(target_sp), m_public_state(eStateUnloaded),
731 m_private_state(eStateUnloaded),
732 m_private_state_broadcaster(nullptr,
733 "lldb.process.internal_state_broadcaster"),
734 m_private_state_control_broadcaster(
735 nullptr, "lldb.process.internal_state_control_broadcaster"),
736 m_private_state_listener_sp(
737 Listener::MakeListener("lldb.process.internal_state_listener")),
738 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
739 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
740 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
741 m_thread_list(this), m_extended_thread_list(this),
742 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
743 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
744 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
745 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
746 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
747 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
748 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
749 m_memory_cache(*this), m_allocated_memory_cache(*this),
750 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
751 m_private_run_lock(), m_stop_info_override_callback(nullptr),
752 m_finalizing(false), m_finalize_called(false),
753 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
754 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
755 m_can_interpret_function_calls(false), m_warnings_issued(),
756 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
757 CheckInWithManager();
758
759 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
760 if (log)
761 log->Printf("%p Process::Process()", static_cast<void *>(this));
762
763 if (!m_unix_signals_sp)
764 m_unix_signals_sp = std::make_shared<UnixSignals>();
765
766 SetEventName(eBroadcastBitStateChanged, "state-changed");
767 SetEventName(eBroadcastBitInterrupt, "interrupt");
768 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
769 SetEventName(eBroadcastBitSTDERR, "stderr-available");
770 SetEventName(eBroadcastBitProfileData, "profile-data-available");
771 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
772
773 m_private_state_control_broadcaster.SetEventName(
774 eBroadcastInternalStateControlStop, "control-stop");
775 m_private_state_control_broadcaster.SetEventName(
776 eBroadcastInternalStateControlPause, "control-pause");
777 m_private_state_control_broadcaster.SetEventName(
778 eBroadcastInternalStateControlResume, "control-resume");
779
780 m_listener_sp->StartListeningForEvents(
781 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
782 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
783 eBroadcastBitProfileData | eBroadcastBitStructuredData);
784
785 m_private_state_listener_sp->StartListeningForEvents(
786 &m_private_state_broadcaster,
787 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
788
789 m_private_state_listener_sp->StartListeningForEvents(
790 &m_private_state_control_broadcaster,
791 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
792 eBroadcastInternalStateControlResume);
793 // We need something valid here, even if just the default UnixSignalsSP.
794 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
795
796 // Allow the platform to override the default cache line size
797 OptionValueSP value_sp =
798 m_collection_sp
799 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
800 ->GetValue();
801 uint32_t platform_cache_line_size =
802 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
803 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
804 value_sp->SetUInt64Value(platform_cache_line_size);
805}
806
807Process::~Process() {
808 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
809 if (log)
810 log->Printf("%p Process::~Process()", static_cast<void *>(this));
811 StopPrivateStateThread();
812
813 // ThreadList::Clear() will try to acquire this process's mutex, so
814 // explicitly clear the thread list here to ensure that the mutex
815 // is not destroyed before the thread list.
816 m_thread_list.Clear();
817}
818
819const ProcessPropertiesSP &Process::GetGlobalProperties() {
820 // NOTE: intentional leak so we don't crash if global destructor chain gets
821 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000822 static ProcessPropertiesSP *g_settings_sp_ptr =
823 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824 return *g_settings_sp_ptr;
825}
826
827void Process::Finalize() {
828 m_finalizing = true;
829
830 // Destroy this process if needed
831 switch (GetPrivateState()) {
832 case eStateConnected:
833 case eStateAttaching:
834 case eStateLaunching:
835 case eStateStopped:
836 case eStateRunning:
837 case eStateStepping:
838 case eStateCrashed:
839 case eStateSuspended:
840 Destroy(false);
841 break;
842
843 case eStateInvalid:
844 case eStateUnloaded:
845 case eStateDetached:
846 case eStateExited:
847 break;
848 }
849
850 // Clear our broadcaster before we proceed with destroying
851 Broadcaster::Clear();
852
853 // Do any cleanup needed prior to being destructed... Subclasses
854 // that override this method should call this superclass method as well.
855
856 // We need to destroy the loader before the derived Process class gets
857 // destroyed
858 // since it is very likely that undoing the loader will require access to the
859 // real process.
860 m_dynamic_checkers_ap.reset();
861 m_abi_sp.reset();
862 m_os_ap.reset();
863 m_system_runtime_ap.reset();
864 m_dyld_ap.reset();
865 m_jit_loaders_ap.reset();
866 m_thread_list_real.Destroy();
867 m_thread_list.Destroy();
868 m_extended_thread_list.Destroy();
869 m_queue_list.Clear();
870 m_queue_list_stop_id = 0;
871 std::vector<Notifications> empty_notifications;
872 m_notifications.swap(empty_notifications);
873 m_image_tokens.clear();
874 m_memory_cache.Clear();
875 m_allocated_memory_cache.Clear();
876 m_language_runtimes.clear();
877 m_instrumentation_runtimes.clear();
878 m_next_event_action_ap.reset();
879 m_stop_info_override_callback = nullptr;
880 // Clear the last natural stop ID since it has a strong
881 // reference to this process
882 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
883 //#ifdef LLDB_CONFIGURATION_DEBUG
884 // StreamFile s(stdout, false);
885 // EventSP event_sp;
886 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
887 // {
888 // event_sp->Dump (&s);
889 // s.EOL();
890 // }
891 //#endif
892 // We have to be very careful here as the m_private_state_listener might
893 // contain events that have ProcessSP values in them which can keep this
894 // process around forever. These events need to be cleared out.
895 m_private_state_listener_sp->Clear();
896 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
897 m_public_run_lock.SetStopped();
898 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
899 m_private_run_lock.SetStopped();
900 m_finalize_called = true;
901}
902
903void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
904 m_notifications.push_back(callbacks);
905 if (callbacks.initialize != nullptr)
906 callbacks.initialize(callbacks.baton, this);
907}
908
909bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
910 std::vector<Notifications>::iterator pos, end = m_notifications.end();
911 for (pos = m_notifications.begin(); pos != end; ++pos) {
912 if (pos->baton == callbacks.baton &&
913 pos->initialize == callbacks.initialize &&
914 pos->process_state_changed == callbacks.process_state_changed) {
915 m_notifications.erase(pos);
916 return true;
917 }
918 }
919 return false;
920}
921
922void Process::SynchronouslyNotifyStateChanged(StateType state) {
923 std::vector<Notifications>::iterator notification_pos,
924 notification_end = m_notifications.end();
925 for (notification_pos = m_notifications.begin();
926 notification_pos != notification_end; ++notification_pos) {
927 if (notification_pos->process_state_changed)
928 notification_pos->process_state_changed(notification_pos->baton, this,
929 state);
930 }
931}
932
933// FIXME: We need to do some work on events before the general Listener sees
934// them.
935// For instance if we are continuing from a breakpoint, we need to ensure that
936// we do
937// the little "insert real insn, step & stop" trick. But we can't do that when
938// the
939// event is delivered by the broadcaster - since that is done on the thread that
940// is
941// waiting for new events, so if we needed more than one event for our handling,
942// we would
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000943// stall. So instead we do it when we fetch the event off of the queue.
944//
945
Kate Stoneb9c1b512016-09-06 20:57:50 +0000946StateType Process::GetNextEvent(EventSP &event_sp) {
947 StateType state = eStateInvalid;
948
Pavel Labathd35031e12016-11-30 10:41:42 +0000949 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
950 std::chrono::seconds(0)) &&
951 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
953
954 return state;
955}
956
957void Process::SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec) {
958 // don't sync (potentially context switch) in case where there is no process
959 // IO
960 if (!m_process_input_reader)
961 return;
962
963 uint32_t new_iohandler_id = 0;
964 m_iohandler_sync.WaitForValueNotEqualTo(
965 iohandler_id, new_iohandler_id, std::chrono::milliseconds(timeout_msec));
966
967 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
968 if (log)
969 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, "
970 "new value is %u",
971 __FUNCTION__, iohandler_id, new_iohandler_id);
972}
973
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000974StateType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975Process::WaitForProcessToStop(const std::chrono::microseconds &timeout,
976 EventSP *event_sp_ptr, bool wait_always,
977 ListenerSP hijack_listener_sp, Stream *stream,
978 bool use_run_lock) {
979 // We can't just wait for a "stopped" event, because the stopped event may
980 // have restarted the target.
981 // We have to actually check each event, and in the case of a stopped event
982 // check the restarted flag
983 // on the event.
984 if (event_sp_ptr)
985 event_sp_ptr->reset();
986 StateType state = GetState();
987 // If we are exited or detached, we won't ever get back to any
988 // other valid state...
989 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000990 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
993 if (log)
994 log->Printf("Process::%s (timeout = %llu)", __FUNCTION__,
995 static_cast<unsigned long long>(timeout.count()));
Todd Fialaa3b89e22014-08-12 14:33:19 +0000996
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997 if (!wait_always && StateIsStoppedState(state, true) &&
998 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000999 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 log->Printf("Process::%s returning without waiting for events; process "
1001 "private and public states are already 'stopped'.",
1002 __FUNCTION__);
1003 // We need to toggle the run lock as this won't get done in
1004 // SetPublicState() if the process is hijacked.
1005 if (hijack_listener_sp && use_run_lock)
1006 m_public_run_lock.SetStopped();
1007 return state;
1008 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001009
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 while (state != eStateInvalid) {
1011 EventSP event_sp;
1012 state = WaitForStateChangedEvents(timeout, event_sp, hijack_listener_sp);
1013 if (event_sp_ptr && event_sp)
1014 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001015
Kate Stoneb9c1b512016-09-06 20:57:50 +00001016 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1017 Process::HandleProcessStateChangedEvent(event_sp, stream,
1018 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +00001019
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 switch (state) {
1021 case eStateCrashed:
1022 case eStateDetached:
1023 case eStateExited:
1024 case eStateUnloaded:
1025 // We need to toggle the run lock as this won't get done in
1026 // SetPublicState() if the process is hijacked.
1027 if (hijack_listener_sp && use_run_lock)
1028 m_public_run_lock.SetStopped();
1029 return state;
1030 case eStateStopped:
1031 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1032 continue;
1033 else {
Pavel Labath78521ef2015-03-06 10:52:47 +00001034 // We need to toggle the run lock as this won't get done in
1035 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001036 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037 m_public_run_lock.SetStopped();
1038 return state;
1039 }
1040 default:
1041 continue;
1042 }
1043 }
1044 return state;
1045}
1046
1047bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1048 Stream *stream,
1049 bool &pop_process_io_handler) {
1050 const bool handle_pop = pop_process_io_handler;
1051
1052 pop_process_io_handler = false;
1053 ProcessSP process_sp =
1054 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1055
1056 if (!process_sp)
1057 return false;
1058
1059 StateType event_state =
1060 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1061 if (event_state == eStateInvalid)
1062 return false;
1063
1064 switch (event_state) {
1065 case eStateInvalid:
1066 case eStateUnloaded:
1067 case eStateAttaching:
1068 case eStateLaunching:
1069 case eStateStepping:
1070 case eStateDetached:
1071 if (stream)
1072 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1073 StateAsCString(event_state));
1074 if (event_state == eStateDetached)
1075 pop_process_io_handler = true;
1076 break;
1077
1078 case eStateConnected:
1079 case eStateRunning:
1080 // Don't be chatty when we run...
1081 break;
1082
1083 case eStateExited:
1084 if (stream)
1085 process_sp->GetStatus(*stream);
1086 pop_process_io_handler = true;
1087 break;
1088
1089 case eStateStopped:
1090 case eStateCrashed:
1091 case eStateSuspended:
1092 // Make sure the program hasn't been auto-restarted:
1093 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1094 if (stream) {
1095 size_t num_reasons =
1096 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1097 if (num_reasons > 0) {
1098 // FIXME: Do we want to report this, or would that just be annoyingly
1099 // chatty?
1100 if (num_reasons == 1) {
1101 const char *reason =
1102 Process::ProcessEventData::GetRestartedReasonAtIndex(
1103 event_sp.get(), 0);
1104 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1105 process_sp->GetID(),
1106 reason ? reason : "<UNKNOWN REASON>");
1107 } else {
1108 stream->Printf("Process %" PRIu64
1109 " stopped and restarted, reasons:\n",
1110 process_sp->GetID());
1111
1112 for (size_t i = 0; i < num_reasons; i++) {
1113 const char *reason =
1114 Process::ProcessEventData::GetRestartedReasonAtIndex(
1115 event_sp.get(), i);
1116 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1117 }
1118 }
1119 }
1120 }
1121 } else {
1122 StopInfoSP curr_thread_stop_info_sp;
1123 // Lock the thread list so it doesn't change on us, this is the scope for
1124 // the locker:
1125 {
1126 ThreadList &thread_list = process_sp->GetThreadList();
1127 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1128
1129 ThreadSP curr_thread(thread_list.GetSelectedThread());
1130 ThreadSP thread;
1131 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1132 if (curr_thread) {
1133 curr_thread_stop_reason = curr_thread->GetStopReason();
1134 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1135 }
1136 if (!curr_thread || !curr_thread->IsValid() ||
1137 curr_thread_stop_reason == eStopReasonInvalid ||
1138 curr_thread_stop_reason == eStopReasonNone) {
1139 // Prefer a thread that has just completed its plan over another
1140 // thread as current thread.
1141 ThreadSP plan_thread;
1142 ThreadSP other_thread;
1143
1144 const size_t num_threads = thread_list.GetSize();
1145 size_t i;
1146 for (i = 0; i < num_threads; ++i) {
1147 thread = thread_list.GetThreadAtIndex(i);
1148 StopReason thread_stop_reason = thread->GetStopReason();
1149 switch (thread_stop_reason) {
1150 case eStopReasonInvalid:
1151 case eStopReasonNone:
1152 break;
1153
1154 case eStopReasonSignal: {
1155 // Don't select a signal thread if we weren't going to stop at
1156 // that
1157 // signal. We have to have had another reason for stopping here,
1158 // and
1159 // the user doesn't want to see this thread.
1160 uint64_t signo = thread->GetStopInfo()->GetValue();
1161 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1162 if (!other_thread)
1163 other_thread = thread;
1164 }
1165 break;
1166 }
1167 case eStopReasonTrace:
1168 case eStopReasonBreakpoint:
1169 case eStopReasonWatchpoint:
1170 case eStopReasonException:
1171 case eStopReasonExec:
1172 case eStopReasonThreadExiting:
1173 case eStopReasonInstrumentation:
1174 if (!other_thread)
1175 other_thread = thread;
1176 break;
1177 case eStopReasonPlanComplete:
1178 if (!plan_thread)
1179 plan_thread = thread;
1180 break;
1181 }
1182 }
1183 if (plan_thread)
1184 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1185 else if (other_thread)
1186 thread_list.SetSelectedThreadByID(other_thread->GetID());
1187 else {
1188 if (curr_thread && curr_thread->IsValid())
1189 thread = curr_thread;
1190 else
1191 thread = thread_list.GetThreadAtIndex(0);
1192
1193 if (thread)
1194 thread_list.SetSelectedThreadByID(thread->GetID());
1195 }
1196 }
1197 }
1198 // Drop the ThreadList mutex by here, since GetThreadStatus below might
1199 // have to run code,
1200 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the
1201 // process is going to
1202 // have a hard time restarting the process.
1203 if (stream) {
1204 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1205 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1206 &process_sp->GetTarget()) {
1207 const bool only_threads_with_stop_reason = true;
1208 const uint32_t start_frame = 0;
1209 const uint32_t num_frames = 1;
1210 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001211 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001212 process_sp->GetStatus(*stream);
1213 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1214 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001215 num_frames_with_source,
1216 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 if (curr_thread_stop_info_sp) {
1218 lldb::addr_t crashing_address;
1219 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1220 curr_thread_stop_info_sp, &crashing_address);
1221 if (valobj_sp) {
1222 const bool qualify_cxx_base_classes = false;
1223
1224 const ValueObject::GetExpressionPathFormat format =
1225 ValueObject::GetExpressionPathFormat::
1226 eGetExpressionPathFormatHonorPointers;
1227 stream->PutCString("Likely cause: ");
1228 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1229 format);
1230 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1231 }
1232 }
1233 } else {
1234 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1235 process_sp->GetTarget().shared_from_this());
1236 if (target_idx != UINT32_MAX)
1237 stream->Printf("Target %d: (", target_idx);
1238 else
1239 stream->Printf("Target <unknown index>: (");
1240 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1241 stream->Printf(") stopped.\n");
1242 }
1243 }
1244
1245 // Pop the process IO handler
1246 pop_process_io_handler = true;
1247 }
1248 break;
1249 }
1250
1251 if (handle_pop && pop_process_io_handler)
1252 process_sp->PopProcessIOHandler();
1253
1254 return true;
1255}
1256
1257StateType Process::WaitForState(const std::chrono::microseconds &timeout,
1258 const StateType *match_states,
1259 const uint32_t num_match_states) {
1260 EventSP event_sp;
1261 StateType state = GetState();
1262 while (state != eStateInvalid) {
1263 // If we are exited or detached, we won't ever get back to any
1264 // other valid state...
1265 if (state == eStateDetached || state == eStateExited)
1266 return state;
1267
1268 state = WaitForStateChangedEvents(timeout, event_sp, nullptr);
1269
1270 for (uint32_t i = 0; i < num_match_states; ++i) {
1271 if (match_states[i] == state)
Daniel Malea9e9919f2013-10-09 16:56:28 +00001272 return state;
1273 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 }
1275 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001276}
1277
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1279 if (listener_sp) {
1280 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1281 eBroadcastBitInterrupt);
1282 } else
1283 return false;
1284}
Greg Claytondc6224e2014-10-21 01:00:42 +00001285
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001287
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288StateType
1289Process::WaitForStateChangedEvents(const std::chrono::microseconds &timeout,
1290 EventSP &event_sp,
1291 ListenerSP hijack_listener_sp) {
1292 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001293
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294 if (log)
1295 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1296 static_cast<unsigned long long>(timeout.count()));
Greg Claytondc6224e2014-10-21 01:00:42 +00001297
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298 ListenerSP listener_sp = hijack_listener_sp;
1299 if (!listener_sp)
1300 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001301
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001303 if (listener_sp->GetEventForBroadcasterWithType(
1304 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1305 ConvertTimeout(timeout))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001306 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1307 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1308 else if (log)
1309 log->Printf("Process::%s got no event or was interrupted.", __FUNCTION__);
1310 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001311
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312 if (log)
1313 log->Printf("Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1314 static_cast<unsigned long long>(timeout.count()),
1315 StateAsCString(state));
1316 return state;
1317}
Greg Claytondc6224e2014-10-21 01:00:42 +00001318
Kate Stoneb9c1b512016-09-06 20:57:50 +00001319Event *Process::PeekAtStateChangedEvents() {
1320 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001321
Kate Stoneb9c1b512016-09-06 20:57:50 +00001322 if (log)
1323 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001324
Kate Stoneb9c1b512016-09-06 20:57:50 +00001325 Event *event_ptr;
1326 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1327 this, eBroadcastBitStateChanged);
1328 if (log) {
1329 if (event_ptr) {
1330 log->Printf(
1331 "Process::%s (event_ptr) => %s", __FUNCTION__,
1332 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1333 } else {
1334 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001335 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001336 }
1337 return event_ptr;
1338}
Greg Claytondc6224e2014-10-21 01:00:42 +00001339
Kate Stoneb9c1b512016-09-06 20:57:50 +00001340StateType Process::WaitForStateChangedEventsPrivate(
1341 const std::chrono::microseconds &timeout, EventSP &event_sp) {
1342 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001343
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 if (log)
1345 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1346 static_cast<unsigned long long>(timeout.count()));
1347
1348 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001349 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1350 &m_private_state_broadcaster,
1351 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1352 ConvertTimeout(timeout)))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001353 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1354 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1355
1356 // This is a bit of a hack, but when we wait here we could very well return
1357 // to the command-line, and that could disable the log, which would render the
1358 // log we got above invalid.
1359 if (log)
1360 log->Printf("Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1361 static_cast<unsigned long long>(timeout.count()),
1362 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1363 return state;
1364}
1365
1366bool Process::WaitForEventsPrivate(const std::chrono::microseconds &timeout,
1367 EventSP &event_sp, bool control_only) {
1368 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1369
1370 if (log)
1371 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1372 static_cast<unsigned long long>(timeout.count()));
1373
1374 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001375 return m_private_state_listener_sp->GetEventForBroadcaster(
1376 &m_private_state_control_broadcaster, event_sp,
1377 ConvertTimeout(timeout));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001378 else
Pavel Labathd35031e12016-11-30 10:41:42 +00001379 return m_private_state_listener_sp->GetEvent(event_sp,
1380 ConvertTimeout(timeout));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001381}
1382
1383bool Process::IsRunning() const {
1384 return StateIsRunningState(m_public_state.GetValue());
1385}
1386
1387int Process::GetExitStatus() {
1388 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1389
1390 if (m_public_state.GetValue() == eStateExited)
1391 return m_exit_status;
1392 return -1;
1393}
1394
1395const char *Process::GetExitDescription() {
1396 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1397
1398 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1399 return m_exit_string.c_str();
1400 return nullptr;
1401}
1402
1403bool Process::SetExitStatus(int status, const char *cstr) {
1404 // Use a mutex to protect setting the exit status.
1405 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1406
1407 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1408 LIBLLDB_LOG_PROCESS));
1409 if (log)
1410 log->Printf(
1411 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1412 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1413 cstr ? "\"" : "");
1414
1415 // We were already in the exited state
1416 if (m_private_state.GetValue() == eStateExited) {
1417 if (log)
1418 log->Printf("Process::SetExitStatus () ignoring exit status because "
1419 "state was already set to eStateExited");
1420 return false;
1421 }
1422
1423 m_exit_status = status;
1424 if (cstr)
1425 m_exit_string = cstr;
1426 else
1427 m_exit_string.clear();
1428
1429 // Clear the last natural stop ID since it has a strong
1430 // reference to this process
1431 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1432
1433 SetPrivateState(eStateExited);
1434
1435 // Allow subclasses to do some cleanup
1436 DidExit();
1437
1438 return true;
1439}
1440
1441bool Process::IsAlive() {
1442 switch (m_private_state.GetValue()) {
1443 case eStateConnected:
1444 case eStateAttaching:
1445 case eStateLaunching:
1446 case eStateStopped:
1447 case eStateRunning:
1448 case eStateStepping:
1449 case eStateCrashed:
1450 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001451 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452 default:
1453 return false;
1454 }
Jason Molendaa814f702015-11-05 23:03:44 +00001455}
1456
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001457// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001458// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001459// found in the global target list (we want to be completely sure that the
1460// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461bool Process::SetProcessExitStatus(
1462 lldb::pid_t pid, bool exited,
1463 int signo, // Zero for no signal
1464 int exit_status // Exit value of process if signal is zero
1465 ) {
1466 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1467 if (log)
1468 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1469 ", exited=%i, signal=%i, exit_status=%i)\n",
1470 pid, exited, signo, exit_status);
1471
1472 if (exited) {
1473 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1474 if (target_sp) {
1475 ProcessSP process_sp(target_sp->GetProcessSP());
1476 if (process_sp) {
1477 const char *signal_cstr = nullptr;
1478 if (signo)
1479 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1480
1481 process_sp->SetExitStatus(exit_status, signal_cstr);
1482 }
1483 }
1484 return true;
1485 }
1486 return false;
1487}
1488
1489void Process::UpdateThreadListIfNeeded() {
1490 const uint32_t stop_id = GetStopID();
1491 if (m_thread_list.GetSize(false) == 0 ||
1492 stop_id != m_thread_list.GetStopID()) {
1493 const StateType state = GetPrivateState();
1494 if (StateIsStoppedState(state, true)) {
1495 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1496 // m_thread_list does have its own mutex, but we need to
1497 // hold onto the mutex between the call to UpdateThreadList(...)
1498 // and the os->UpdateThreadList(...) so it doesn't change on us
1499 ThreadList &old_thread_list = m_thread_list;
1500 ThreadList real_thread_list(this);
1501 ThreadList new_thread_list(this);
1502 // Always update the thread list with the protocol specific
1503 // thread list, but only update if "true" is returned
1504 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1505 // Don't call into the OperatingSystem to update the thread list if we
1506 // are shutting down, since
1507 // that may call back into the SBAPI's, requiring the API lock which is
1508 // already held by whoever is
1509 // shutting us down, causing a deadlock.
1510 OperatingSystem *os = GetOperatingSystem();
1511 if (os && !m_destroy_in_process) {
1512 // Clear any old backing threads where memory threads might have been
1513 // backed by actual threads from the lldb_private::Process subclass
1514 size_t num_old_threads = old_thread_list.GetSize(false);
1515 for (size_t i = 0; i < num_old_threads; ++i)
1516 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1517
1518 // Turn off dynamic types to ensure we don't run any expressions.
1519 // Objective C
1520 // can run an expression to determine if a SBValue is a dynamic type
1521 // or not
1522 // and we need to avoid this. OperatingSystem plug-ins can't run
1523 // expressions
1524 // that require running code...
1525
1526 Target &target = GetTarget();
1527 const lldb::DynamicValueType saved_prefer_dynamic =
1528 target.GetPreferDynamicValue();
1529 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1530 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1531
1532 // Now let the OperatingSystem plug-in update the thread list
1533
1534 os->UpdateThreadList(
1535 old_thread_list, // Old list full of threads created by OS plug-in
1536 real_thread_list, // The actual thread list full of threads
1537 // created by each lldb_private::Process
1538 // subclass
1539 new_thread_list); // The new thread list that we will show to the
1540 // user that gets filled in
1541
1542 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1543 target.SetPreferDynamicValue(saved_prefer_dynamic);
1544 } else {
1545 // No OS plug-in, the new thread list is the same as the real thread
1546 // list
1547 new_thread_list = real_thread_list;
1548 }
1549
1550 m_thread_list_real.Update(real_thread_list);
1551 m_thread_list.Update(new_thread_list);
1552 m_thread_list.SetStopID(stop_id);
1553
1554 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1555 // Clear any extended threads that we may have accumulated previously
1556 m_extended_thread_list.Clear();
1557 m_extended_thread_stop_id = GetLastNaturalStopID();
1558
1559 m_queue_list.Clear();
1560 m_queue_list_stop_id = GetLastNaturalStopID();
1561 }
1562 }
1563 }
1564 }
1565}
1566
1567void Process::UpdateQueueListIfNeeded() {
1568 if (m_system_runtime_ap) {
1569 if (m_queue_list.GetSize() == 0 ||
1570 m_queue_list_stop_id != GetLastNaturalStopID()) {
1571 const StateType state = GetPrivateState();
1572 if (StateIsStoppedState(state, true)) {
1573 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1574 m_queue_list_stop_id = GetLastNaturalStopID();
1575 }
1576 }
1577 }
1578}
1579
1580ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1581 OperatingSystem *os = GetOperatingSystem();
1582 if (os)
1583 return os->CreateThread(tid, context);
1584 return ThreadSP();
1585}
1586
1587uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1588 return AssignIndexIDToThread(thread_id);
1589}
1590
1591bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1592 return (m_thread_id_to_index_id_map.find(thread_id) !=
1593 m_thread_id_to_index_id_map.end());
1594}
1595
1596uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1597 uint32_t result = 0;
1598 std::map<uint64_t, uint32_t>::iterator iterator =
1599 m_thread_id_to_index_id_map.find(thread_id);
1600 if (iterator == m_thread_id_to_index_id_map.end()) {
1601 result = ++m_thread_index_id;
1602 m_thread_id_to_index_id_map[thread_id] = result;
1603 } else {
1604 result = iterator->second;
1605 }
1606
1607 return result;
1608}
1609
1610StateType Process::GetState() {
1611 // If any other threads access this we will need a mutex for it
1612 return m_public_state.GetValue();
1613}
1614
1615bool Process::StateChangedIsExternallyHijacked() {
1616 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1617 const char *hijacking_name = GetHijackingListenerName();
1618 if (hijacking_name &&
1619 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1620 return true;
1621 }
1622 return false;
1623}
1624
1625void Process::SetPublicState(StateType new_state, bool restarted) {
1626 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1627 LIBLLDB_LOG_PROCESS));
1628 if (log)
1629 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1630 StateAsCString(new_state), restarted);
1631 const StateType old_state = m_public_state.GetValue();
1632 m_public_state.SetValue(new_state);
1633
1634 // On the transition from Run to Stopped, we unlock the writer end of the
1635 // run lock. The lock gets locked in Resume, which is the public API
1636 // to tell the program to run.
1637 if (!StateChangedIsExternallyHijacked()) {
1638 if (new_state == eStateDetached) {
1639 if (log)
1640 log->Printf(
1641 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1642 StateAsCString(new_state));
1643 m_public_run_lock.SetStopped();
1644 } else {
1645 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1646 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1647 if ((old_state_is_stopped != new_state_is_stopped)) {
1648 if (new_state_is_stopped && !restarted) {
1649 if (log)
1650 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1651 StateAsCString(new_state));
1652 m_public_run_lock.SetStopped();
1653 }
1654 }
1655 }
1656 }
1657}
1658
1659Error Process::Resume() {
1660 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1661 LIBLLDB_LOG_PROCESS));
1662 if (log)
1663 log->Printf("Process::Resume -- locking run lock");
1664 if (!m_public_run_lock.TrySetRunning()) {
1665 Error error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001666 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001667 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001668 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001669 }
1670 return PrivateResume();
Greg Claytondc6224e2014-10-21 01:00:42 +00001671}
1672
Kate Stoneb9c1b512016-09-06 20:57:50 +00001673Error Process::ResumeSynchronous(Stream *stream) {
1674 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1675 LIBLLDB_LOG_PROCESS));
1676 if (log)
1677 log->Printf("Process::ResumeSynchronous -- locking run lock");
1678 if (!m_public_run_lock.TrySetRunning()) {
1679 Error error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001680 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001681 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1682 return error;
1683 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001684
Kate Stoneb9c1b512016-09-06 20:57:50 +00001685 ListenerSP listener_sp(
1686 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1687 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001688
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 Error error = PrivateResume();
1690 if (error.Success()) {
1691 StateType state = WaitForProcessToStop(std::chrono::microseconds(0), NULL,
1692 true, listener_sp, stream);
1693 const bool must_be_alive =
1694 false; // eStateExited is ok, so this must be false
1695 if (!StateIsStoppedState(state, must_be_alive))
1696 error.SetErrorStringWithFormat(
1697 "process not in stopped state after synchronous resume: %s",
1698 StateAsCString(state));
1699 }
Ed Mastec29693f2013-07-02 16:35:47 +00001700
Kate Stoneb9c1b512016-09-06 20:57:50 +00001701 // Undo the hijacking of process events...
1702 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001703
Kate Stoneb9c1b512016-09-06 20:57:50 +00001704 return error;
1705}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001706
Kate Stoneb9c1b512016-09-06 20:57:50 +00001707StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001708
Kate Stoneb9c1b512016-09-06 20:57:50 +00001709void Process::SetPrivateState(StateType new_state) {
1710 if (m_finalize_called)
1711 return;
1712
1713 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1714 LIBLLDB_LOG_PROCESS));
1715 bool state_changed = false;
1716
1717 if (log)
1718 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1719
1720 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1721 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1722
1723 const StateType old_state = m_private_state.GetValueNoLock();
1724 state_changed = old_state != new_state;
1725
1726 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1727 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1728 if (old_state_is_stopped != new_state_is_stopped) {
1729 if (new_state_is_stopped)
1730 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001731 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732 m_private_run_lock.SetRunning();
1733 }
1734
1735 if (state_changed) {
1736 m_private_state.SetValueNoLock(new_state);
1737 EventSP event_sp(
1738 new Event(eBroadcastBitStateChanged,
1739 new ProcessEventData(shared_from_this(), new_state)));
1740 if (StateIsStoppedState(new_state, false)) {
1741 // Note, this currently assumes that all threads in the list
1742 // stop when the process stops. In the future we will want to
1743 // support a debugging model where some threads continue to run
1744 // while others are stopped. When that happens we will either need
1745 // a way for the thread list to identify which threads are stopping
1746 // or create a special thread list containing only threads which
1747 // actually stopped.
1748 //
1749 // The process plugin is responsible for managing the actual
1750 // behavior of the threads and should have stopped any threads
1751 // that are going to stop before we get here.
1752 m_thread_list.DidStop();
1753
1754 m_mod_id.BumpStopID();
1755 if (!m_mod_id.IsLastResumeForUserExpression())
1756 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1757 m_memory_cache.Clear();
1758 if (log)
1759 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1760 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001761 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001762
Kate Stoneb9c1b512016-09-06 20:57:50 +00001763 // Use our target to get a shared pointer to ourselves...
1764 if (m_finalize_called && !PrivateStateThreadIsValid())
1765 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001766 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001767 m_private_state_broadcaster.BroadcastEvent(event_sp);
1768 } else {
1769 if (log)
1770 log->Printf(
1771 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1772 StateAsCString(new_state));
1773 }
Jim Ingham22777012010-09-23 02:01:19 +00001774}
1775
Kate Stoneb9c1b512016-09-06 20:57:50 +00001776void Process::SetRunningUserExpression(bool on) {
1777 m_mod_id.SetRunningUserExpression(on);
1778}
1779
1780addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1781
1782const lldb::ABISP &Process::GetABI() {
1783 if (!m_abi_sp)
1784 m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture());
1785 return m_abi_sp;
1786}
1787
1788LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1789 bool retry_if_null) {
1790 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001791 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001792
1793 LanguageRuntimeCollection::iterator pos;
1794 pos = m_language_runtimes.find(language);
1795 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1796 lldb::LanguageRuntimeSP runtime_sp(
1797 LanguageRuntime::FindPlugin(this, language));
1798
1799 m_language_runtimes[language] = runtime_sp;
1800 return runtime_sp.get();
1801 } else
1802 return (*pos).second.get();
Jim Ingham22777012010-09-23 02:01:19 +00001803}
1804
Kate Stoneb9c1b512016-09-06 20:57:50 +00001805CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1806 LanguageRuntime *runtime =
1807 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1808 if (runtime != nullptr &&
1809 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1810 return static_cast<CPPLanguageRuntime *>(runtime);
1811 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001812}
1813
Kate Stoneb9c1b512016-09-06 20:57:50 +00001814ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1815 LanguageRuntime *runtime =
1816 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1817 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1818 return static_cast<ObjCLanguageRuntime *>(runtime);
1819 return nullptr;
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001820}
1821
Kate Stoneb9c1b512016-09-06 20:57:50 +00001822bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1823 if (m_finalizing)
1824 return false;
1825
1826 if (in_value.IsDynamic())
1827 return false;
1828 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1829
1830 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1831 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1832 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1833 }
1834
1835 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1836 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1837 return true;
1838
1839 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1840 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001841}
1842
Kate Stoneb9c1b512016-09-06 20:57:50 +00001843void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1844 m_dynamic_checkers_ap.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001845}
1846
Kate Stoneb9c1b512016-09-06 20:57:50 +00001847BreakpointSiteList &Process::GetBreakpointSiteList() {
1848 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001849}
1850
Kate Stoneb9c1b512016-09-06 20:57:50 +00001851const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1852 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001853}
1854
Kate Stoneb9c1b512016-09-06 20:57:50 +00001855void Process::DisableAllBreakpointSites() {
1856 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1857 // bp_site->SetEnabled(true);
1858 DisableBreakpointSite(bp_site);
1859 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001860}
1861
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862Error Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1863 Error error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864
Kate Stoneb9c1b512016-09-06 20:57:50 +00001865 if (error.Success())
1866 m_breakpoint_site_list.Remove(break_id);
1867
1868 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001869}
1870
Kate Stoneb9c1b512016-09-06 20:57:50 +00001871Error Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1872 Error error;
1873 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1874 if (bp_site_sp) {
1875 if (bp_site_sp->IsEnabled())
1876 error = DisableBreakpointSite(bp_site_sp.get());
1877 } else {
1878 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1879 break_id);
1880 }
1881
1882 return error;
1883}
1884
1885Error Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1886 Error error;
1887 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1888 if (bp_site_sp) {
1889 if (!bp_site_sp->IsEnabled())
1890 error = EnableBreakpointSite(bp_site_sp.get());
1891 } else {
1892 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1893 break_id);
1894 }
1895 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001896}
1897
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001898lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001899Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1900 bool use_hardware) {
1901 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001902
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903 bool show_error = true;
1904 switch (GetState()) {
1905 case eStateInvalid:
1906 case eStateUnloaded:
1907 case eStateConnected:
1908 case eStateAttaching:
1909 case eStateLaunching:
1910 case eStateDetached:
1911 case eStateExited:
1912 show_error = false;
1913 break;
1914
1915 case eStateStopped:
1916 case eStateRunning:
1917 case eStateStepping:
1918 case eStateCrashed:
1919 case eStateSuspended:
1920 show_error = IsAlive();
1921 break;
1922 }
1923
1924 // Reset the IsIndirect flag here, in case the location changes from
1925 // pointing to a indirect symbol to a regular symbol.
1926 owner->SetIsIndirect(false);
1927
1928 if (owner->ShouldResolveIndirectFunctions()) {
1929 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1930 if (symbol && symbol->IsIndirect()) {
1931 Error error;
1932 Address symbol_address = symbol->GetAddress();
1933 load_addr = ResolveIndirectFunction(&symbol_address, error);
1934 if (!error.Success() && show_error) {
1935 GetTarget().GetDebugger().GetErrorFile()->Printf(
1936 "warning: failed to resolve indirect function at 0x%" PRIx64
1937 " for breakpoint %i.%i: %s\n",
1938 symbol->GetLoadAddress(&GetTarget()),
1939 owner->GetBreakpoint().GetID(), owner->GetID(),
1940 error.AsCString() ? error.AsCString() : "unknown error");
1941 return LLDB_INVALID_BREAK_ID;
1942 }
1943 Address resolved_address(load_addr);
1944 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1945 owner->SetIsIndirect(true);
1946 } else
1947 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1948 } else
1949 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1950
1951 if (load_addr != LLDB_INVALID_ADDRESS) {
1952 BreakpointSiteSP bp_site_sp;
1953
1954 // Look up this breakpoint site. If it exists, then add this new owner,
1955 // otherwise
1956 // create a new breakpoint site and add it.
1957
1958 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1959
1960 if (bp_site_sp) {
1961 bp_site_sp->AddOwner(owner);
1962 owner->SetBreakpointSite(bp_site_sp);
1963 return bp_site_sp->GetID();
1964 } else {
1965 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1966 load_addr, use_hardware));
1967 if (bp_site_sp) {
1968 Error error = EnableBreakpointSite(bp_site_sp.get());
1969 if (error.Success()) {
1970 owner->SetBreakpointSite(bp_site_sp);
1971 return m_breakpoint_site_list.Add(bp_site_sp);
1972 } else {
1973 if (show_error) {
1974 // Report error for setting breakpoint...
1975 GetTarget().GetDebugger().GetErrorFile()->Printf(
1976 "warning: failed to set breakpoint site at 0x%" PRIx64
1977 " for breakpoint %i.%i: %s\n",
1978 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1979 error.AsCString() ? error.AsCString() : "unknown error");
1980 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001981 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001982 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001983 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984 }
1985 // We failed to enable the breakpoint
1986 return LLDB_INVALID_BREAK_ID;
1987}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001988
Kate Stoneb9c1b512016-09-06 20:57:50 +00001989void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1990 lldb::user_id_t owner_loc_id,
1991 BreakpointSiteSP &bp_site_sp) {
1992 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1993 if (num_owners == 0) {
1994 // Don't try to disable the site if we don't have a live process anymore.
1995 if (IsAlive())
1996 DisableBreakpointSite(bp_site_sp.get());
1997 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1998 }
1999}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002000
Kate Stoneb9c1b512016-09-06 20:57:50 +00002001size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
2002 uint8_t *buf) const {
2003 size_t bytes_removed = 0;
2004 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002005
Kate Stoneb9c1b512016-09-06 20:57:50 +00002006 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
2007 bp_sites_in_range)) {
2008 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](
2009 BreakpointSite *bp_site) -> void {
2010 if (bp_site->GetType() == BreakpointSite::eSoftware) {
2011 addr_t intersect_addr;
2012 size_t intersect_size;
2013 size_t opcode_offset;
2014 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
2015 &intersect_size, &opcode_offset)) {
2016 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2017 assert(bp_addr < intersect_addr + intersect_size &&
2018 intersect_addr + intersect_size <= bp_addr + size);
2019 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
2020 size_t buf_offset = intersect_addr - bp_addr;
2021 ::memcpy(buf + buf_offset,
2022 bp_site->GetSavedOpcodeBytes() + opcode_offset,
2023 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002024 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002025 }
2026 });
2027 }
2028 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002029}
2030
Kate Stoneb9c1b512016-09-06 20:57:50 +00002031size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
2032 PlatformSP platform_sp(GetTarget().GetPlatform());
2033 if (platform_sp)
2034 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
2035 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002036}
2037
Kate Stoneb9c1b512016-09-06 20:57:50 +00002038Error Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
2039 Error error;
2040 assert(bp_site != nullptr);
2041 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2042 const addr_t bp_addr = bp_site->GetLoadAddress();
2043 if (log)
2044 log->Printf(
2045 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
2046 bp_site->GetID(), (uint64_t)bp_addr);
2047 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002048 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002049 log->Printf(
2050 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2051 " -- already enabled",
2052 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002053 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002054 }
2055
2056 if (bp_addr == LLDB_INVALID_ADDRESS) {
2057 error.SetErrorString("BreakpointSite contains an invalid load address.");
2058 return error;
2059 }
2060 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2061 // trap for the breakpoint site
2062 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2063
2064 if (bp_opcode_size == 0) {
2065 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2066 "returned zero, unable to get breakpoint "
2067 "trap for address 0x%" PRIx64,
2068 bp_addr);
2069 } else {
2070 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2071
2072 if (bp_opcode_bytes == nullptr) {
2073 error.SetErrorString(
2074 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2075 return error;
2076 }
2077
2078 // Save the original opcode by reading it
2079 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2080 error) == bp_opcode_size) {
2081 // Write a software breakpoint in place of the original opcode
2082 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2083 bp_opcode_size) {
2084 uint8_t verify_bp_opcode_bytes[64];
2085 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2086 error) == bp_opcode_size) {
2087 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2088 bp_opcode_size) == 0) {
2089 bp_site->SetEnabled(true);
2090 bp_site->SetType(BreakpointSite::eSoftware);
2091 if (log)
2092 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2093 "addr = 0x%" PRIx64 " -- SUCCESS",
2094 bp_site->GetID(), (uint64_t)bp_addr);
2095 } else
2096 error.SetErrorString(
2097 "failed to verify the breakpoint trap in memory.");
2098 } else
2099 error.SetErrorString(
2100 "Unable to read memory to verify breakpoint trap.");
2101 } else
2102 error.SetErrorString("Unable to write breakpoint trap to memory.");
2103 } else
2104 error.SetErrorString("Unable to read memory at breakpoint address.");
2105 }
2106 if (log && error.Fail())
2107 log->Printf(
2108 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2109 " -- FAILED: %s",
2110 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2111 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002112}
2113
Kate Stoneb9c1b512016-09-06 20:57:50 +00002114Error Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2115 Error error;
2116 assert(bp_site != nullptr);
2117 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2118 addr_t bp_addr = bp_site->GetLoadAddress();
2119 lldb::user_id_t breakID = bp_site->GetID();
2120 if (log)
2121 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2122 ") addr = 0x%" PRIx64,
2123 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002124
Kate Stoneb9c1b512016-09-06 20:57:50 +00002125 if (bp_site->IsHardware()) {
2126 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2127 } else if (bp_site->IsEnabled()) {
2128 const size_t break_op_size = bp_site->GetByteSize();
2129 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2130 if (break_op_size > 0) {
2131 // Clear a software breakpoint instruction
2132 uint8_t curr_break_op[8];
2133 assert(break_op_size <= sizeof(curr_break_op));
2134 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002135
Kate Stoneb9c1b512016-09-06 20:57:50 +00002136 // Read the breakpoint opcode
2137 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2138 break_op_size) {
2139 bool verify = false;
2140 // Make sure the breakpoint opcode exists at this address
2141 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2142 break_op_found = true;
2143 // We found a valid breakpoint opcode at this address, now restore
2144 // the saved opcode.
2145 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2146 break_op_size, error) == break_op_size) {
2147 verify = true;
2148 } else
2149 error.SetErrorString(
2150 "Memory write failed when restoring original opcode.");
2151 } else {
2152 error.SetErrorString(
2153 "Original breakpoint trap is no longer in memory.");
2154 // Set verify to true and so we can check if the original opcode has
2155 // already been restored
2156 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002157 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002158
Kate Stoneb9c1b512016-09-06 20:57:50 +00002159 if (verify) {
2160 uint8_t verify_opcode[8];
2161 assert(break_op_size < sizeof(verify_opcode));
2162 // Verify that our original opcode made it back to the inferior
2163 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2164 break_op_size) {
2165 // compare the memory we just read with the original opcode
2166 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2167 break_op_size) == 0) {
2168 // SUCCESS
2169 bp_site->SetEnabled(false);
2170 if (log)
2171 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2172 "addr = 0x%" PRIx64 " -- SUCCESS",
2173 bp_site->GetID(), (uint64_t)bp_addr);
2174 return error;
2175 } else {
2176 if (break_op_found)
2177 error.SetErrorString("Failed to restore original opcode.");
2178 }
2179 } else
2180 error.SetErrorString("Failed to read memory to verify that "
2181 "breakpoint trap was restored.");
2182 }
2183 } else
2184 error.SetErrorString(
2185 "Unable to read memory that should contain the breakpoint trap.");
2186 }
2187 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002188 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189 log->Printf(
2190 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2191 " -- already disabled",
2192 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002193 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002194 }
2195
2196 if (log)
2197 log->Printf(
2198 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2199 " -- FAILED: %s",
2200 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2201 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002202}
2203
Greg Clayton58be07b2011-01-07 06:08:19 +00002204// Uncomment to verify memory caching works after making changes to caching code
2205//#define VERIFY_MEMORY_READS
2206
Kate Stoneb9c1b512016-09-06 20:57:50 +00002207size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Error &error) {
2208 error.Clear();
2209 if (!GetDisableMemoryCache()) {
2210#if defined(VERIFY_MEMORY_READS)
2211 // Memory caching is enabled, with debug verification
2212
2213 if (buf && size) {
2214 // Uncomment the line below to make sure memory caching is working.
2215 // I ran this through the test suite and got no assertions, so I am
2216 // pretty confident this is working well. If any changes are made to
2217 // memory caching, uncomment the line below and test your changes!
2218
2219 // Verify all memory reads by using the cache first, then redundantly
2220 // reading the same memory from the inferior and comparing to make sure
2221 // everything is exactly the same.
2222 std::string verify_buf(size, '\0');
2223 assert(verify_buf.size() == size);
2224 const size_t cache_bytes_read =
2225 m_memory_cache.Read(this, addr, buf, size, error);
2226 Error verify_error;
2227 const size_t verify_bytes_read =
2228 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2229 verify_buf.size(), verify_error);
2230 assert(cache_bytes_read == verify_bytes_read);
2231 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2232 assert(verify_error.Success() == error.Success());
2233 return cache_bytes_read;
2234 }
2235 return 0;
2236#else // !defined(VERIFY_MEMORY_READS)
2237 // Memory caching is enabled, without debug verification
2238
2239 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002240#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002241 } else {
2242 // Memory caching is disabled
2243
2244 return ReadMemoryFromInferior(addr, buf, size, error);
2245 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002246}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002247
2248size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2249 Error &error) {
2250 char buf[256];
2251 out_str.clear();
2252 addr_t curr_addr = addr;
2253 while (true) {
2254 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2255 if (length == 0)
2256 break;
2257 out_str.append(buf, length);
2258 // If we got "length - 1" bytes, we didn't get the whole C string, we
2259 // need to read some more characters
2260 if (length == sizeof(buf) - 1)
2261 curr_addr += length;
2262 else
2263 break;
2264 }
2265 return out_str.size();
2266}
2267
2268size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
2269 Error &error, size_t type_width) {
2270 size_t total_bytes_read = 0;
2271 if (dst && max_bytes && type_width && max_bytes >= type_width) {
2272 // Ensure a null terminator independent of the number of bytes that is read.
2273 memset(dst, 0, max_bytes);
2274 size_t bytes_left = max_bytes - type_width;
2275
2276 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2277 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2278 "string with more than 4 bytes "
2279 "per character!");
2280
Greg Clayton4c82d422012-05-18 23:20:01 +00002281 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002282 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2283 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002284
Kate Stoneb9c1b512016-09-06 20:57:50 +00002285 error.Clear();
2286 while (bytes_left > 0 && error.Success()) {
2287 addr_t cache_line_bytes_left =
2288 cache_line_size - (curr_addr % cache_line_size);
2289 addr_t bytes_to_read =
2290 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2291 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002292
Kate Stoneb9c1b512016-09-06 20:57:50 +00002293 if (bytes_read == 0)
2294 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002295
Kate Stoneb9c1b512016-09-06 20:57:50 +00002296 // Search for a null terminator of correct size and alignment in
2297 // bytes_read
2298 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2299 for (size_t i = aligned_start;
2300 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2301 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2302 error.Clear();
2303 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002304 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002305
2306 total_bytes_read += bytes_read;
2307 curr_dst += bytes_read;
2308 curr_addr += bytes_read;
2309 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002310 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002311 } else {
2312 if (max_bytes)
2313 error.SetErrorString("invalid arguments");
2314 }
2315 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002316}
2317
Kate Stoneb9c1b512016-09-06 20:57:50 +00002318// Deprecated in favor of ReadStringFromMemory which has wchar support and
2319// correct code to find
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002320// null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002321size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
2322 size_t dst_max_len, Error &result_error) {
2323 size_t total_cstr_len = 0;
2324 if (dst && dst_max_len) {
2325 result_error.Clear();
2326 // NULL out everything just to be safe
2327 memset(dst, 0, dst_max_len);
2328 Error error;
2329 addr_t curr_addr = addr;
2330 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2331 size_t bytes_left = dst_max_len - 1;
2332 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002333
Kate Stoneb9c1b512016-09-06 20:57:50 +00002334 while (bytes_left > 0) {
2335 addr_t cache_line_bytes_left =
2336 cache_line_size - (curr_addr % cache_line_size);
2337 addr_t bytes_to_read =
2338 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2339 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002340
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341 if (bytes_read == 0) {
2342 result_error = error;
2343 dst[total_cstr_len] = '\0';
2344 break;
2345 }
2346 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002347
Kate Stoneb9c1b512016-09-06 20:57:50 +00002348 total_cstr_len += len;
2349
2350 if (len < bytes_to_read)
2351 break;
2352
2353 curr_dst += bytes_read;
2354 curr_addr += bytes_read;
2355 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002356 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357 } else {
2358 if (dst == nullptr)
2359 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002360 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002361 result_error.Clear();
2362 }
2363 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002364}
2365
Kate Stoneb9c1b512016-09-06 20:57:50 +00002366size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2367 Error &error) {
2368 if (buf == nullptr || size == 0)
2369 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002370
Kate Stoneb9c1b512016-09-06 20:57:50 +00002371 size_t bytes_read = 0;
2372 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002373
Kate Stoneb9c1b512016-09-06 20:57:50 +00002374 while (bytes_read < size) {
2375 const size_t curr_size = size - bytes_read;
2376 const size_t curr_bytes_read =
2377 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2378 bytes_read += curr_bytes_read;
2379 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2380 break;
2381 }
2382
2383 // Replace any software breakpoint opcodes that fall into this range back
2384 // into "buf" before we return
2385 if (bytes_read > 0)
2386 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2387 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002388}
2389
Kate Stoneb9c1b512016-09-06 20:57:50 +00002390uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2391 size_t integer_byte_size,
2392 uint64_t fail_value,
2393 Error &error) {
2394 Scalar scalar;
2395 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2396 error))
2397 return scalar.ULongLong(fail_value);
2398 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002399}
2400
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2402 size_t integer_byte_size,
2403 int64_t fail_value, Error &error) {
2404 Scalar scalar;
2405 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2406 error))
2407 return scalar.SLongLong(fail_value);
2408 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002409}
2410
Kate Stoneb9c1b512016-09-06 20:57:50 +00002411addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error) {
2412 Scalar scalar;
2413 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2414 error))
2415 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2416 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002417}
2418
Kate Stoneb9c1b512016-09-06 20:57:50 +00002419bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
2420 Error &error) {
2421 Scalar scalar;
2422 const uint32_t addr_byte_size = GetAddressByteSize();
2423 if (addr_byte_size <= 4)
2424 scalar = (uint32_t)ptr_value;
2425 else
2426 scalar = ptr_value;
2427 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2428 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002429}
2430
Kate Stoneb9c1b512016-09-06 20:57:50 +00002431size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2432 Error &error) {
2433 size_t bytes_written = 0;
2434 const uint8_t *bytes = (const uint8_t *)buf;
2435
2436 while (bytes_written < size) {
2437 const size_t curr_size = size - bytes_written;
2438 const size_t curr_bytes_written = DoWriteMemory(
2439 addr + bytes_written, bytes + bytes_written, curr_size, error);
2440 bytes_written += curr_bytes_written;
2441 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2442 break;
2443 }
2444 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002445}
2446
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2448 Error &error) {
2449#if defined(ENABLE_MEMORY_CACHING)
2450 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002451#endif
2452
Kate Stoneb9c1b512016-09-06 20:57:50 +00002453 if (buf == nullptr || size == 0)
2454 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002455
Kate Stoneb9c1b512016-09-06 20:57:50 +00002456 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002457
Kate Stoneb9c1b512016-09-06 20:57:50 +00002458 // We need to write any data that would go where any current software traps
2459 // (enabled software breakpoints) any software traps (breakpoints) that we
2460 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002461
Kate Stoneb9c1b512016-09-06 20:57:50 +00002462 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002463
Kate Stoneb9c1b512016-09-06 20:57:50 +00002464 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2465 bp_sites_in_range)) {
2466 // No breakpoint sites overlap
2467 if (bp_sites_in_range.IsEmpty())
2468 return WriteMemoryPrivate(addr, buf, size, error);
2469 else {
2470 const uint8_t *ubuf = (const uint8_t *)buf;
2471 uint64_t bytes_written = 0;
2472
2473 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2474 &error](BreakpointSite *bp) -> void {
2475
2476 if (error.Success()) {
2477 addr_t intersect_addr;
2478 size_t intersect_size;
2479 size_t opcode_offset;
2480 const bool intersects = bp->IntersectsRange(
2481 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2482 UNUSED_IF_ASSERT_DISABLED(intersects);
2483 assert(intersects);
2484 assert(addr <= intersect_addr && intersect_addr < addr + size);
2485 assert(addr < intersect_addr + intersect_size &&
2486 intersect_addr + intersect_size <= addr + size);
2487 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2488
2489 // Check for bytes before this breakpoint
2490 const addr_t curr_addr = addr + bytes_written;
2491 if (intersect_addr > curr_addr) {
2492 // There are some bytes before this breakpoint that we need to
2493 // just write to memory
2494 size_t curr_size = intersect_addr - curr_addr;
2495 size_t curr_bytes_written = WriteMemoryPrivate(
2496 curr_addr, ubuf + bytes_written, curr_size, error);
2497 bytes_written += curr_bytes_written;
2498 if (curr_bytes_written != curr_size) {
2499 // We weren't able to write all of the requested bytes, we
2500 // are done looping and will return the number of bytes that
2501 // we have written so far.
2502 if (error.Success())
2503 error.SetErrorToGenericError();
2504 }
2505 }
2506 // Now write any bytes that would cover up any software breakpoints
2507 // directly into the breakpoint opcode buffer
2508 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2509 ubuf + bytes_written, intersect_size);
2510 bytes_written += intersect_size;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002511 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002512 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002513
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514 if (bytes_written < size)
2515 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2516 size - bytes_written, error);
2517 }
2518 } else {
2519 return WriteMemoryPrivate(addr, buf, size, error);
2520 }
2521
2522 // Write any remaining bytes after the last breakpoint if we have any left
2523 return 0; // bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002524}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002525
Kate Stoneb9c1b512016-09-06 20:57:50 +00002526size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2527 size_t byte_size, Error &error) {
2528 if (byte_size == UINT32_MAX)
2529 byte_size = scalar.GetByteSize();
2530 if (byte_size > 0) {
2531 uint8_t buf[32];
2532 const size_t mem_size =
2533 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2534 if (mem_size > 0)
2535 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002536 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002537 error.SetErrorString("failed to get scalar as memory data");
2538 } else {
2539 error.SetErrorString("invalid scalar value");
2540 }
2541 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002542}
2543
Kate Stoneb9c1b512016-09-06 20:57:50 +00002544size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2545 bool is_signed, Scalar &scalar,
2546 Error &error) {
2547 uint64_t uval = 0;
2548 if (byte_size == 0) {
2549 error.SetErrorString("byte size is zero");
2550 } else if (byte_size & (byte_size - 1)) {
2551 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2552 byte_size);
2553 } else if (byte_size <= sizeof(uval)) {
2554 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2555 if (bytes_read == byte_size) {
2556 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2557 GetAddressByteSize());
2558 lldb::offset_t offset = 0;
2559 if (byte_size <= 4)
2560 scalar = data.GetMaxU32(&offset, byte_size);
2561 else
2562 scalar = data.GetMaxU64(&offset, byte_size);
2563 if (is_signed)
2564 scalar.SignExtend(byte_size * 8);
2565 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002566 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002567 } else {
2568 error.SetErrorStringWithFormat(
2569 "byte size of %u is too large for integer scalar type", byte_size);
2570 }
2571 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002572}
2573
Greg Claytond495c532011-05-17 03:37:42 +00002574#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002575addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2576 Error &error) {
2577 if (GetPrivateState() != eStateStopped)
2578 return LLDB_INVALID_ADDRESS;
2579
2580#if defined(USE_ALLOCATE_MEMORY_CACHE)
2581 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002582#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002583 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2584 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2585 if (log)
2586 log->Printf("Process::AllocateMemory(size=%" PRIu64
2587 ", permissions=%s) => 0x%16.16" PRIx64
2588 " (m_stop_id = %u m_memory_id = %u)",
2589 (uint64_t)size, GetPermissionsAsCString(permissions),
2590 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2591 m_mod_id.GetMemoryID());
2592 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002593#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002594}
2595
Kate Stoneb9c1b512016-09-06 20:57:50 +00002596addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2597 Error &error) {
2598 addr_t return_addr = AllocateMemory(size, permissions, error);
2599 if (error.Success()) {
2600 std::string buffer(size, 0);
2601 WriteMemory(return_addr, buffer.c_str(), size, error);
2602 }
2603 return return_addr;
2604}
2605
2606bool Process::CanJIT() {
2607 if (m_can_jit == eCanJITDontKnow) {
2608 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2609 Error err;
2610
2611 uint64_t allocated_memory = AllocateMemory(
2612 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2613 err);
2614
2615 if (err.Success()) {
2616 m_can_jit = eCanJITYes;
2617 if (log)
2618 log->Printf("Process::%s pid %" PRIu64
2619 " allocation test passed, CanJIT () is true",
2620 __FUNCTION__, GetID());
2621 } else {
2622 m_can_jit = eCanJITNo;
2623 if (log)
2624 log->Printf("Process::%s pid %" PRIu64
2625 " allocation test failed, CanJIT () is false: %s",
2626 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002627 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002628
2629 DeallocateMemory(allocated_memory);
2630 }
2631
2632 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002633}
2634
Kate Stoneb9c1b512016-09-06 20:57:50 +00002635void Process::SetCanJIT(bool can_jit) {
2636 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002637}
2638
Kate Stoneb9c1b512016-09-06 20:57:50 +00002639void Process::SetCanRunCode(bool can_run_code) {
2640 SetCanJIT(can_run_code);
2641 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002642}
2643
Kate Stoneb9c1b512016-09-06 20:57:50 +00002644Error Process::DeallocateMemory(addr_t ptr) {
2645 Error error;
2646#if defined(USE_ALLOCATE_MEMORY_CACHE)
2647 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2648 error.SetErrorStringWithFormat(
2649 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2650 }
Greg Claytond495c532011-05-17 03:37:42 +00002651#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002652 error = DoDeallocateMemory(ptr);
2653
2654 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2655 if (log)
2656 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2657 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2658 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2659 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002660#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002661 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002662}
2663
Kate Stoneb9c1b512016-09-06 20:57:50 +00002664ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2665 lldb::addr_t header_addr,
2666 size_t size_to_read) {
2667 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2668 if (log) {
2669 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2670 file_spec.GetPath().c_str());
2671 }
2672 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2673 if (module_sp) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002674 Error error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002675 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2676 shared_from_this(), header_addr, error, size_to_read);
2677 if (objfile)
2678 return module_sp;
2679 }
2680 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002681}
2682
Kate Stoneb9c1b512016-09-06 20:57:50 +00002683bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2684 uint32_t &permissions) {
2685 MemoryRegionInfo range_info;
2686 permissions = 0;
2687 Error error(GetMemoryRegionInfo(load_addr, range_info));
2688 if (!error.Success())
2689 return false;
2690 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2691 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2692 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2693 return false;
2694 }
2695
2696 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2697 permissions |= lldb::ePermissionsReadable;
2698
2699 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2700 permissions |= lldb::ePermissionsWritable;
2701
2702 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2703 permissions |= lldb::ePermissionsExecutable;
2704
2705 return true;
2706}
2707
2708Error Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2709 Error error;
2710 error.SetErrorString("watchpoints are not supported");
2711 return error;
2712}
2713
2714Error Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2715 Error error;
2716 error.SetErrorString("watchpoints are not supported");
2717 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002718}
2719
2720StateType
Kate Stoneb9c1b512016-09-06 20:57:50 +00002721Process::WaitForProcessStopPrivate(const std::chrono::microseconds &timeout,
2722 EventSP &event_sp) {
2723 StateType state;
2724 // Now wait for the process to launch and return control to us, and then
2725 // call DidLaunch:
2726 while (true) {
2727 event_sp.reset();
2728 state = WaitForStateChangedEventsPrivate(timeout, event_sp);
Greg Clayton6779606a2011-01-22 23:43:18 +00002729
Kate Stoneb9c1b512016-09-06 20:57:50 +00002730 if (StateIsStoppedState(state, false))
2731 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002732
Kate Stoneb9c1b512016-09-06 20:57:50 +00002733 // If state is invalid, then we timed out
2734 if (state == eStateInvalid)
2735 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002736
Kate Stoneb9c1b512016-09-06 20:57:50 +00002737 if (event_sp)
2738 HandlePrivateEvent(event_sp);
2739 }
2740 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002741}
2742
Kate Stoneb9c1b512016-09-06 20:57:50 +00002743void Process::LoadOperatingSystemPlugin(bool flush) {
2744 if (flush)
2745 m_thread_list.Clear();
2746 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2747 if (flush)
2748 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002749}
2750
Kate Stoneb9c1b512016-09-06 20:57:50 +00002751Error Process::Launch(ProcessLaunchInfo &launch_info) {
2752 Error error;
2753 m_abi_sp.reset();
2754 m_dyld_ap.reset();
2755 m_jit_loaders_ap.reset();
2756 m_system_runtime_ap.reset();
2757 m_os_ap.reset();
2758 m_process_input_reader.reset();
2759 m_stop_info_override_callback = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002760
Kate Stoneb9c1b512016-09-06 20:57:50 +00002761 Module *exe_module = GetTarget().GetExecutableModulePointer();
2762 if (exe_module) {
2763 char local_exec_file_path[PATH_MAX];
2764 char platform_exec_file_path[PATH_MAX];
2765 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2766 sizeof(local_exec_file_path));
2767 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2768 sizeof(platform_exec_file_path));
2769 if (exe_module->GetFileSpec().Exists()) {
2770 // Install anything that might need to be installed prior to launching.
2771 // For host systems, this will do nothing, but if we are connected to a
2772 // remote platform it will install any needed binaries
2773 error = GetTarget().Install(&launch_info);
2774 if (error.Fail())
2775 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002776
Kate Stoneb9c1b512016-09-06 20:57:50 +00002777 if (PrivateStateThreadIsValid())
2778 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002779
Kate Stoneb9c1b512016-09-06 20:57:50 +00002780 error = WillLaunch(exe_module);
2781 if (error.Success()) {
2782 const bool restarted = false;
2783 SetPublicState(eStateLaunching, restarted);
2784 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002785
Kate Stoneb9c1b512016-09-06 20:57:50 +00002786 if (m_public_run_lock.TrySetRunning()) {
2787 // Now launch using these arguments.
2788 error = DoLaunch(exe_module, launch_info);
2789 } else {
2790 // This shouldn't happen
2791 error.SetErrorString("failed to acquire process run lock");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002792 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002793
Kate Stoneb9c1b512016-09-06 20:57:50 +00002794 if (error.Fail()) {
2795 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2796 SetID(LLDB_INVALID_PROCESS_ID);
2797 const char *error_string = error.AsCString();
2798 if (error_string == nullptr)
2799 error_string = "launch failed";
2800 SetExitStatus(-1, error_string);
2801 }
2802 } else {
2803 EventSP event_sp;
2804 StateType state =
2805 WaitForProcessStopPrivate(std::chrono::seconds(10), event_sp);
Greg Clayton35824e32015-02-20 20:59:47 +00002806
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807 if (state == eStateInvalid || !event_sp) {
2808 // We were able to launch the process, but we failed to
2809 // catch the initial stop.
2810 error.SetErrorString("failed to catch stop after launch");
2811 SetExitStatus(0, "failed to catch stop after launch");
2812 Destroy(false);
2813 } else if (state == eStateStopped || state == eStateCrashed) {
2814 DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002815
Kate Stoneb9c1b512016-09-06 20:57:50 +00002816 DynamicLoader *dyld = GetDynamicLoader();
2817 if (dyld)
2818 dyld->DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002819
Kate Stoneb9c1b512016-09-06 20:57:50 +00002820 GetJITLoaders().DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002821
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 SystemRuntime *system_runtime = GetSystemRuntime();
2823 if (system_runtime)
2824 system_runtime->DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002825
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002827
Kate Stoneb9c1b512016-09-06 20:57:50 +00002828 // Note, the stop event was consumed above, but not handled. This
2829 // was done
2830 // to give DidLaunch a chance to run. The target is either stopped
2831 // or crashed.
2832 // Directly set the state. This is done to prevent a stop message
2833 // with a bunch
2834 // of spurious output on thread status, as well as not pop a
2835 // ProcessIOHandler.
2836 SetPublicState(state, false);
Greg Claytonc3776bf2012-02-09 06:16:32 +00002837
Kate Stoneb9c1b512016-09-06 20:57:50 +00002838 if (PrivateStateThreadIsValid())
2839 ResumePrivateStateThread();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002840 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 StartPrivateStateThread();
Todd Fiala76e0fc92014-08-27 22:58:26 +00002842
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843 m_stop_info_override_callback =
2844 GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002845
Kate Stoneb9c1b512016-09-06 20:57:50 +00002846 // Target was stopped at entry as was intended. Need to notify the
2847 // listeners
2848 // about it.
2849 if (state == eStateStopped &&
2850 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2851 HandlePrivateEvent(event_sp);
2852 } else if (state == eStateExited) {
2853 // We exited while trying to launch somehow. Don't call DidLaunch
2854 // as that's
2855 // not likely to work, and return an invalid pid.
2856 HandlePrivateEvent(event_sp);
2857 }
2858 }
2859 }
2860 } else {
2861 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2862 local_exec_file_path);
Jim Inghambb3a2832011-01-29 01:49:25 +00002863 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002864 }
2865 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002866}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002867
Kate Stoneb9c1b512016-09-06 20:57:50 +00002868Error Process::LoadCore() {
2869 Error error = DoLoadCore();
2870 if (error.Success()) {
2871 ListenerSP listener_sp(
2872 Listener::MakeListener("lldb.process.load_core_listener"));
2873 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002874
Kate Stoneb9c1b512016-09-06 20:57:50 +00002875 if (PrivateStateThreadIsValid())
2876 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002877 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002879
Kate Stoneb9c1b512016-09-06 20:57:50 +00002880 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002881 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002882 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002883
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002884 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002885
Kate Stoneb9c1b512016-09-06 20:57:50 +00002886 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002887 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002888 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002889
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002890 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002891 // We successfully loaded a core file, now pretend we stopped so we can
2892 // show all of the threads in the core file and explore the crashed
2893 // state.
2894 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002895
Kate Stoneb9c1b512016-09-06 20:57:50 +00002896 // Wait indefinitely for a stopped event since we just posted one above...
2897 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00002898 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002899 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2900
2901 if (!StateIsStoppedState(state, false)) {
2902 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2903 if (log)
2904 log->Printf("Process::Halt() failed to stop, state is: %s",
2905 StateAsCString(state));
2906 error.SetErrorString(
2907 "Did not get stopped event after loading the core file.");
2908 }
2909 RestoreProcessEvents();
2910 }
2911 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002912}
2913
Kate Stoneb9c1b512016-09-06 20:57:50 +00002914DynamicLoader *Process::GetDynamicLoader() {
2915 if (!m_dyld_ap)
2916 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2917 return m_dyld_ap.get();
2918}
2919
2920const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2921
2922JITLoaderList &Process::GetJITLoaders() {
2923 if (!m_jit_loaders_ap) {
2924 m_jit_loaders_ap.reset(new JITLoaderList());
2925 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2926 }
2927 return *m_jit_loaders_ap;
2928}
2929
2930SystemRuntime *Process::GetSystemRuntime() {
2931 if (!m_system_runtime_ap)
2932 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2933 return m_system_runtime_ap.get();
2934}
2935
2936Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2937 uint32_t exec_count)
2938 : NextEventAction(process), m_exec_count(exec_count) {
2939 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2940 if (log)
2941 log->Printf(
2942 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2943 __FUNCTION__, static_cast<void *>(process), exec_count);
2944}
2945
2946Process::NextEventAction::EventActionResult
2947Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2948 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2949
2950 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2951 if (log)
2952 log->Printf(
2953 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2954 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2955
2956 switch (state) {
2957 case eStateAttaching:
2958 return eEventActionSuccess;
2959
2960 case eStateRunning:
2961 case eStateConnected:
2962 return eEventActionRetry;
2963
2964 case eStateStopped:
2965 case eStateCrashed:
2966 // During attach, prior to sending the eStateStopped event,
2967 // lldb_private::Process subclasses must set the new process ID.
2968 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2969 // We don't want these events to be reported, so go set the ShouldReportStop
2970 // here:
2971 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2972
2973 if (m_exec_count > 0) {
2974 --m_exec_count;
2975
2976 if (log)
2977 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2978 "remaining exec count to %" PRIu32 ", requesting resume",
2979 __FUNCTION__, StateAsCString(state), m_exec_count);
2980
2981 RequestResume();
2982 return eEventActionRetry;
2983 } else {
2984 if (log)
2985 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2986 "execs expected to start, continuing with attach",
2987 __FUNCTION__, StateAsCString(state));
2988
2989 m_process->CompleteAttach();
2990 return eEventActionSuccess;
2991 }
2992 break;
2993
2994 default:
2995 case eStateExited:
2996 case eStateInvalid:
2997 break;
2998 }
2999
3000 m_exit_string.assign("No valid Process");
3001 return eEventActionExit;
3002}
3003
3004Process::NextEventAction::EventActionResult
3005Process::AttachCompletionHandler::HandleBeingInterrupted() {
3006 return eEventActionSuccess;
3007}
3008
3009const char *Process::AttachCompletionHandler::GetExitString() {
3010 return m_exit_string.c_str();
3011}
3012
3013ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
3014 if (m_listener_sp)
3015 return m_listener_sp;
3016 else
3017 return debugger.GetListener();
3018}
3019
3020Error Process::Attach(ProcessAttachInfo &attach_info) {
3021 m_abi_sp.reset();
3022 m_process_input_reader.reset();
3023 m_dyld_ap.reset();
3024 m_jit_loaders_ap.reset();
3025 m_system_runtime_ap.reset();
3026 m_os_ap.reset();
3027 m_stop_info_override_callback = nullptr;
3028
3029 lldb::pid_t attach_pid = attach_info.GetProcessID();
3030 Error error;
3031 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
3032 char process_name[PATH_MAX];
3033
3034 if (attach_info.GetExecutableFile().GetPath(process_name,
3035 sizeof(process_name))) {
3036 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3037
3038 if (wait_for_launch) {
3039 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3040 if (error.Success()) {
3041 if (m_public_run_lock.TrySetRunning()) {
3042 m_should_detach = true;
3043 const bool restarted = false;
3044 SetPublicState(eStateAttaching, restarted);
3045 // Now attach using these arguments.
3046 error = DoAttachToProcessWithName(process_name, attach_info);
3047 } else {
3048 // This shouldn't happen
3049 error.SetErrorString("failed to acquire process run lock");
3050 }
3051
3052 if (error.Fail()) {
3053 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3054 SetID(LLDB_INVALID_PROCESS_ID);
3055 if (error.AsCString() == nullptr)
3056 error.SetErrorString("attach failed");
3057
3058 SetExitStatus(-1, error.AsCString());
3059 }
3060 } else {
3061 SetNextEventAction(new Process::AttachCompletionHandler(
3062 this, attach_info.GetResumeCount()));
3063 StartPrivateStateThread();
3064 }
3065 return error;
3066 }
3067 } else {
3068 ProcessInstanceInfoList process_infos;
3069 PlatformSP platform_sp(GetTarget().GetPlatform());
3070
3071 if (platform_sp) {
3072 ProcessInstanceInfoMatch match_info;
3073 match_info.GetProcessInfo() = attach_info;
3074 match_info.SetNameMatchType(eNameMatchEquals);
3075 platform_sp->FindProcesses(match_info, process_infos);
3076 const uint32_t num_matches = process_infos.GetSize();
3077 if (num_matches == 1) {
3078 attach_pid = process_infos.GetProcessIDAtIndex(0);
3079 // Fall through and attach using the above process ID
3080 } else {
3081 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3082 process_name, sizeof(process_name));
3083 if (num_matches > 1) {
3084 StreamString s;
3085 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3086 false);
3087 for (size_t i = 0; i < num_matches; i++) {
3088 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3089 s, platform_sp.get(), true, false);
3090 }
3091 error.SetErrorStringWithFormat(
3092 "more than one process named %s:\n%s", process_name,
3093 s.GetData());
3094 } else
3095 error.SetErrorStringWithFormat(
3096 "could not find a process named %s", process_name);
3097 }
3098 } else {
3099 error.SetErrorString(
3100 "invalid platform, can't find processes by name");
3101 return error;
3102 }
3103 }
3104 } else {
3105 error.SetErrorString("invalid process name");
3106 }
3107 }
3108
3109 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3110 error = WillAttachToProcessWithID(attach_pid);
3111 if (error.Success()) {
3112
3113 if (m_public_run_lock.TrySetRunning()) {
3114 // Now attach using these arguments.
3115 m_should_detach = true;
3116 const bool restarted = false;
3117 SetPublicState(eStateAttaching, restarted);
3118 error = DoAttachToProcessWithID(attach_pid, attach_info);
3119 } else {
3120 // This shouldn't happen
3121 error.SetErrorString("failed to acquire process run lock");
3122 }
3123
3124 if (error.Success()) {
3125 SetNextEventAction(new Process::AttachCompletionHandler(
3126 this, attach_info.GetResumeCount()));
3127 StartPrivateStateThread();
3128 } else {
Greg Clayton71337622011-02-24 22:24:29 +00003129 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003130 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003131
Kate Stoneb9c1b512016-09-06 20:57:50 +00003132 const char *error_string = error.AsCString();
3133 if (error_string == nullptr)
3134 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00003135
Kate Stoneb9c1b512016-09-06 20:57:50 +00003136 SetExitStatus(-1, error_string);
3137 }
Greg Claytonb766a732011-02-04 01:58:07 +00003138 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 }
3140 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00003141}
3142
Kate Stoneb9c1b512016-09-06 20:57:50 +00003143void Process::CompleteAttach() {
3144 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3145 LIBLLDB_LOG_TARGET));
3146 if (log)
3147 log->Printf("Process::%s()", __FUNCTION__);
3148
3149 // Let the process subclass figure out at much as it can about the process
3150 // before we go looking for a dynamic loader plug-in.
3151 ArchSpec process_arch;
3152 DidAttach(process_arch);
3153
3154 if (process_arch.IsValid()) {
3155 GetTarget().SetArchitecture(process_arch);
3156 if (log) {
3157 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3158 log->Printf("Process::%s replacing process architecture with DidAttach() "
3159 "architecture: %s",
3160 __FUNCTION__, triple_str ? triple_str : "<null>");
3161 }
3162 }
3163
3164 // We just attached. If we have a platform, ask it for the process
3165 // architecture, and if it isn't
3166 // the same as the one we've already set, switch architectures.
3167 PlatformSP platform_sp(GetTarget().GetPlatform());
3168 assert(platform_sp);
3169 if (platform_sp) {
3170 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3171 if (target_arch.IsValid() &&
3172 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3173 ArchSpec platform_arch;
3174 platform_sp =
3175 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3176 if (platform_sp) {
3177 GetTarget().SetPlatform(platform_sp);
3178 GetTarget().SetArchitecture(platform_arch);
3179 if (log)
3180 log->Printf("Process::%s switching platform to %s and architecture "
3181 "to %s based on info from attach",
3182 __FUNCTION__, platform_sp->GetName().AsCString(""),
3183 platform_arch.GetTriple().getTriple().c_str());
3184 }
3185 } else if (!process_arch.IsValid()) {
3186 ProcessInstanceInfo process_info;
3187 GetProcessInfo(process_info);
3188 const ArchSpec &process_arch = process_info.GetArchitecture();
3189 if (process_arch.IsValid() &&
3190 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3191 GetTarget().SetArchitecture(process_arch);
3192 if (log)
3193 log->Printf("Process::%s switching architecture to %s based on info "
3194 "the platform retrieved for pid %" PRIu64,
3195 __FUNCTION__,
3196 process_arch.GetTriple().getTriple().c_str(), GetID());
3197 }
3198 }
3199 }
3200
3201 // We have completed the attach, now it is time to find the dynamic loader
3202 // plug-in
3203 DynamicLoader *dyld = GetDynamicLoader();
3204 if (dyld) {
3205 dyld->DidAttach();
3206 if (log) {
3207 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3208 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3209 "executable is %s (using %s plugin)",
3210 __FUNCTION__,
3211 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3212 : "<none>",
3213 dyld->GetPluginName().AsCString("<unnamed>"));
3214 }
3215 }
3216
3217 GetJITLoaders().DidAttach();
3218
3219 SystemRuntime *system_runtime = GetSystemRuntime();
3220 if (system_runtime) {
3221 system_runtime->DidAttach();
3222 if (log) {
3223 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3224 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3225 "executable is %s (using %s plugin)",
3226 __FUNCTION__,
3227 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3228 : "<none>",
3229 system_runtime->GetPluginName().AsCString("<unnamed>"));
3230 }
3231 }
3232
3233 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
3234 // Figure out which one is the executable, and set that in our target:
3235 const ModuleList &target_modules = GetTarget().GetImages();
3236 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3237 size_t num_modules = target_modules.GetSize();
3238 ModuleSP new_executable_module_sp;
3239
3240 for (size_t i = 0; i < num_modules; i++) {
3241 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3242 if (module_sp && module_sp->IsExecutable()) {
3243 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3244 new_executable_module_sp = module_sp;
3245 break;
3246 }
3247 }
3248 if (new_executable_module_sp) {
3249 GetTarget().SetExecutableModule(new_executable_module_sp, false);
3250 if (log) {
3251 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3252 log->Printf(
3253 "Process::%s after looping through modules, target executable is %s",
3254 __FUNCTION__,
3255 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3256 : "<none>");
3257 }
3258 }
3259
3260 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
3261}
3262
Zachary Turner31659452016-11-17 21:15:14 +00003263Error Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003264 m_abi_sp.reset();
3265 m_process_input_reader.reset();
3266
3267 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003268 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003269
3270 Error error(DoConnectRemote(strm, remote_url));
3271 if (error.Success()) {
3272 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3273 EventSP event_sp;
3274 StateType state =
3275 WaitForProcessStopPrivate(std::chrono::microseconds(0), event_sp);
3276
3277 if (state == eStateStopped || state == eStateCrashed) {
3278 // If we attached and actually have a process on the other end, then
3279 // this ended up being the equivalent of an attach.
3280 CompleteAttach();
3281
3282 // This delays passing the stopped event to listeners till
3283 // CompleteAttach gets a chance to complete...
3284 HandlePrivateEvent(event_sp);
3285 }
3286 }
3287
3288 if (PrivateStateThreadIsValid())
3289 ResumePrivateStateThread();
3290 else
3291 StartPrivateStateThread();
3292 }
3293 return error;
3294}
3295
3296Error Process::PrivateResume() {
3297 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3298 LIBLLDB_LOG_STEP));
3299 if (log)
3300 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3301 "private state: %s",
3302 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3303 StateAsCString(m_private_state.GetValue()));
3304
3305 Error error(WillResume());
3306 // Tell the process it is about to resume before the thread list
3307 if (error.Success()) {
3308 // Now let the thread list know we are about to resume so it
3309 // can let all of our threads know that they are about to be
3310 // resumed. Threads will each be called with
3311 // Thread::WillResume(StateType) where StateType contains the state
3312 // that they are supposed to have when the process is resumed
3313 // (suspended/running/stepping). Threads should also check
3314 // their resume signal in lldb::Thread::GetResumeSignal()
3315 // to see if they are supposed to start back up with a signal.
3316 if (m_thread_list.WillResume()) {
3317 // Last thing, do the PreResumeActions.
3318 if (!RunPreResumeActions()) {
3319 error.SetErrorStringWithFormat(
3320 "Process::PrivateResume PreResumeActions failed, not resuming.");
3321 } else {
3322 m_mod_id.BumpResumeID();
3323 error = DoResume();
3324 if (error.Success()) {
3325 DidResume();
3326 m_thread_list.DidResume();
3327 if (log)
3328 log->Printf("Process thinks the process has resumed.");
3329 }
3330 }
3331 } else {
3332 // Somebody wanted to run without running (e.g. we were faking a step from
3333 // one frame of a set of inlined
3334 // frames that share the same PC to another.) So generate a continue & a
3335 // stopped event,
3336 // and let the world handle them.
3337 if (log)
3338 log->Printf(
3339 "Process::PrivateResume() asked to simulate a start & stop.");
3340
3341 SetPrivateState(eStateRunning);
3342 SetPrivateState(eStateStopped);
3343 }
3344 } else if (log)
3345 log->Printf("Process::PrivateResume() got an error \"%s\".",
3346 error.AsCString("<unknown error>"));
3347 return error;
3348}
3349
3350Error Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3351 if (!StateIsRunningState(m_public_state.GetValue()))
3352 return Error("Process is not running.");
3353
3354 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3355 // in case it was already set and some thread plan logic calls halt on its
3356 // own.
3357 m_clear_thread_plans_on_stop |= clear_thread_plans;
3358
3359 ListenerSP halt_listener_sp(
3360 Listener::MakeListener("lldb.process.halt_listener"));
3361 HijackProcessEvents(halt_listener_sp);
3362
3363 EventSP event_sp;
3364
3365 SendAsyncInterrupt();
3366
3367 if (m_public_state.GetValue() == eStateAttaching) {
3368 // Don't hijack and eat the eStateExited as the code that was doing
3369 // the attach will be waiting for this event...
3370 RestoreProcessEvents();
3371 SetExitStatus(SIGKILL, "Cancelled async attach.");
3372 Destroy(false);
Mehdi Aminic1edf562016-11-11 04:29:25 +00003373 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003374 }
3375
3376 // Wait for 10 second for the process to stop.
3377 StateType state =
3378 WaitForProcessToStop(std::chrono::seconds(10), &event_sp, true,
3379 halt_listener_sp, nullptr, use_run_lock);
3380 RestoreProcessEvents();
3381
3382 if (state == eStateInvalid || !event_sp) {
3383 // We timed out and didn't get a stop event...
3384 return Error("Halt timed out. State = %s", StateAsCString(GetState()));
3385 }
3386
3387 BroadcastEvent(event_sp);
3388
Mehdi Aminic1edf562016-11-11 04:29:25 +00003389 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003390}
3391
3392Error Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3393 Error error;
3394
3395 // Check both the public & private states here. If we're hung evaluating an
3396 // expression, for instance, then
3397 // the public state will be stopped, but we still need to interrupt.
3398 if (m_public_state.GetValue() == eStateRunning ||
3399 m_private_state.GetValue() == eStateRunning) {
3400 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003401 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003402 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003403
Kate Stoneb9c1b512016-09-06 20:57:50 +00003404 ListenerSP listener_sp(
3405 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3406 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003407
Pavel Labath19da1f12015-12-07 12:36:52 +00003408 SendAsyncInterrupt();
3409
Kate Stoneb9c1b512016-09-06 20:57:50 +00003410 // Consume the interrupt event.
3411 StateType state = WaitForProcessToStop(std::chrono::seconds(10),
3412 &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003413
Pavel Labath19da1f12015-12-07 12:36:52 +00003414 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003415
Kate Stoneb9c1b512016-09-06 20:57:50 +00003416 // If the process exited while we were waiting for it to stop, put the
3417 // exited event into
3418 // the shared pointer passed in and return. Our caller doesn't need to do
3419 // anything else, since
3420 // they don't have a process anymore...
3421
3422 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3423 if (log)
3424 log->Printf("Process::%s() Process exited while waiting to stop.",
3425 __FUNCTION__);
3426 return error;
3427 } else
3428 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3429
3430 if (state != eStateStopped) {
3431 if (log)
3432 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3433 StateAsCString(state));
3434 // If we really couldn't stop the process then we should just error out
3435 // here, but if the
3436 // lower levels just bobbled sending the event and we really are stopped,
3437 // then continue on.
3438 StateType private_state = m_private_state.GetValue();
3439 if (private_state != eStateStopped) {
3440 return Error("Attempt to stop the target in order to detach timed out. "
3441 "State = %s",
3442 StateAsCString(GetState()));
3443 }
3444 }
3445 }
3446 return error;
3447}
3448
3449Error Process::Detach(bool keep_stopped) {
3450 EventSP exit_event_sp;
3451 Error error;
3452 m_destroy_in_process = true;
3453
3454 error = WillDetach();
3455
3456 if (error.Success()) {
3457 if (DetachRequiresHalt()) {
3458 error = StopForDestroyOrDetach(exit_event_sp);
3459 if (!error.Success()) {
3460 m_destroy_in_process = false;
3461 return error;
3462 } else if (exit_event_sp) {
3463 // We shouldn't need to do anything else here. There's no process left
3464 // to detach from...
3465 StopPrivateStateThread();
3466 m_destroy_in_process = false;
3467 return error;
3468 }
3469 }
3470
3471 m_thread_list.DiscardThreadPlans();
3472 DisableAllBreakpointSites();
3473
3474 error = DoDetach(keep_stopped);
3475 if (error.Success()) {
3476 DidDetach();
3477 StopPrivateStateThread();
3478 } else {
3479 return error;
3480 }
3481 }
3482 m_destroy_in_process = false;
3483
3484 // If we exited when we were waiting for a process to stop, then
3485 // forward the event here so we don't lose the event
3486 if (exit_event_sp) {
3487 // Directly broadcast our exited event because we shut down our
3488 // private state thread above
3489 BroadcastEvent(exit_event_sp);
3490 }
3491
3492 // If we have been interrupted (to kill us) in the middle of running, we may
3493 // not end up propagating
3494 // the last events through the event system, in which case we might strand the
3495 // write lock. Unlock
3496 // it here so when we do to tear down the process we don't get an error
3497 // destroying the lock.
3498
3499 m_public_run_lock.SetStopped();
3500 return error;
3501}
3502
3503Error Process::Destroy(bool force_kill) {
3504
3505 // Tell ourselves we are in the process of destroying the process, so that we
3506 // don't do any unnecessary work
3507 // that might hinder the destruction. Remember to set this back to false when
3508 // we are done. That way if the attempt
3509 // failed and the process stays around for some reason it won't be in a
3510 // confused state.
3511
3512 if (force_kill)
3513 m_should_detach = false;
3514
3515 if (GetShouldDetach()) {
3516 // FIXME: This will have to be a process setting:
3517 bool keep_stopped = false;
3518 Detach(keep_stopped);
3519 }
3520
3521 m_destroy_in_process = true;
3522
3523 Error error(WillDestroy());
3524 if (error.Success()) {
3525 EventSP exit_event_sp;
3526 if (DestroyRequiresHalt()) {
3527 error = StopForDestroyOrDetach(exit_event_sp);
3528 }
3529
3530 if (m_public_state.GetValue() != eStateRunning) {
3531 // Ditch all thread plans, and remove all our breakpoints: in case we have
3532 // to restart the target to
3533 // kill it, we don't want it hitting a breakpoint...
3534 // Only do this if we've stopped, however, since if we didn't manage to
3535 // halt it above, then
3536 // we're not going to have much luck doing this now.
3537 m_thread_list.DiscardThreadPlans();
3538 DisableAllBreakpointSites();
3539 }
3540
3541 error = DoDestroy();
3542 if (error.Success()) {
3543 DidDestroy();
3544 StopPrivateStateThread();
3545 }
3546 m_stdio_communication.Disconnect();
3547 m_stdio_communication.StopReadThread();
3548 m_stdin_forward = false;
3549
3550 if (m_process_input_reader) {
3551 m_process_input_reader->SetIsDone(true);
3552 m_process_input_reader->Cancel();
3553 m_process_input_reader.reset();
3554 }
3555
3556 // If we exited when we were waiting for a process to stop, then
3557 // forward the event here so we don't lose the event
3558 if (exit_event_sp) {
3559 // Directly broadcast our exited event because we shut down our
3560 // private state thread above
3561 BroadcastEvent(exit_event_sp);
3562 }
3563
3564 // If we have been interrupted (to kill us) in the middle of running, we may
3565 // not end up propagating
3566 // the last events through the event system, in which case we might strand
3567 // the write lock. Unlock
3568 // it here so when we do to tear down the process we don't get an error
3569 // destroying the lock.
3570 m_public_run_lock.SetStopped();
3571 }
3572
3573 m_destroy_in_process = false;
3574
3575 return error;
3576}
3577
3578Error Process::Signal(int signal) {
3579 Error error(WillSignal());
3580 if (error.Success()) {
3581 error = DoSignal(signal);
3582 if (error.Success())
3583 DidSignal();
3584 }
3585 return error;
3586}
3587
3588void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3589 assert(signals_sp && "null signals_sp");
3590 m_unix_signals_sp = signals_sp;
3591}
3592
3593const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3594 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3595 return m_unix_signals_sp;
3596}
3597
3598lldb::ByteOrder Process::GetByteOrder() const {
3599 return GetTarget().GetArchitecture().GetByteOrder();
3600}
3601
3602uint32_t Process::GetAddressByteSize() const {
3603 return GetTarget().GetArchitecture().GetAddressByteSize();
3604}
3605
3606bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3607 const StateType state =
3608 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3609 bool return_value = true;
3610 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3611 LIBLLDB_LOG_PROCESS));
3612
3613 switch (state) {
3614 case eStateDetached:
3615 case eStateExited:
3616 case eStateUnloaded:
3617 m_stdio_communication.SynchronizeWithReadThread();
3618 m_stdio_communication.Disconnect();
3619 m_stdio_communication.StopReadThread();
3620 m_stdin_forward = false;
3621
3622 LLVM_FALLTHROUGH;
3623 case eStateConnected:
3624 case eStateAttaching:
3625 case eStateLaunching:
3626 // These events indicate changes in the state of the debugging session,
3627 // always report them.
3628 return_value = true;
3629 break;
3630 case eStateInvalid:
3631 // We stopped for no apparent reason, don't report it.
3632 return_value = false;
3633 break;
3634 case eStateRunning:
3635 case eStateStepping:
3636 // If we've started the target running, we handle the cases where we
3637 // are already running and where there is a transition from stopped to
3638 // running differently.
3639 // running -> running: Automatically suppress extra running events
3640 // stopped -> running: Report except when there is one or more no votes
3641 // and no yes votes.
3642 SynchronouslyNotifyStateChanged(state);
3643 if (m_force_next_event_delivery)
3644 return_value = true;
3645 else {
3646 switch (m_last_broadcast_state) {
3647 case eStateRunning:
3648 case eStateStepping:
3649 // We always suppress multiple runnings with no PUBLIC stop in between.
3650 return_value = false;
3651 break;
3652 default:
3653 // TODO: make this work correctly. For now always report
3654 // run if we aren't running so we don't miss any running
3655 // events. If I run the lldb/test/thread/a.out file and
3656 // break at main.cpp:58, run and hit the breakpoints on
3657 // multiple threads, then somehow during the stepping over
3658 // of all breakpoints no run gets reported.
3659
3660 // This is a transition from stop to run.
3661 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3662 case eVoteYes:
3663 case eVoteNoOpinion:
3664 return_value = true;
3665 break;
3666 case eVoteNo:
3667 return_value = false;
3668 break;
3669 }
3670 break;
3671 }
3672 }
3673 break;
3674 case eStateStopped:
3675 case eStateCrashed:
3676 case eStateSuspended:
3677 // We've stopped. First see if we're going to restart the target.
3678 // If we are going to stop, then we always broadcast the event.
3679 // If we aren't going to stop, let the thread plans decide if we're going to
3680 // report this event.
3681 // If no thread has an opinion, we don't report it.
3682
3683 m_stdio_communication.SynchronizeWithReadThread();
3684 RefreshStateAfterStop();
3685 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3686 if (log)
3687 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3688 "interrupt, state: %s",
3689 static_cast<void *>(event_ptr), StateAsCString(state));
3690 // Even though we know we are going to stop, we should let the threads
3691 // have a look at the stop,
3692 // so they can properly set their state.
3693 m_thread_list.ShouldStop(event_ptr);
3694 return_value = true;
3695 } else {
3696 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3697 bool should_resume = false;
3698
3699 // It makes no sense to ask "ShouldStop" if we've already been
3700 // restarted...
3701 // Asking the thread list is also not likely to go well, since we are
3702 // running again.
3703 // So in that case just report the event.
3704
3705 if (!was_restarted)
3706 should_resume = !m_thread_list.ShouldStop(event_ptr);
3707
3708 if (was_restarted || should_resume || m_resume_requested) {
3709 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3710 if (log)
3711 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3712 "%s was_restarted: %i stop_vote: %d.",
3713 should_resume, StateAsCString(state), was_restarted,
3714 stop_vote);
3715
3716 switch (stop_vote) {
3717 case eVoteYes:
3718 return_value = true;
3719 break;
3720 case eVoteNoOpinion:
3721 case eVoteNo:
3722 return_value = false;
3723 break;
3724 }
3725
3726 if (!was_restarted) {
3727 if (log)
3728 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3729 "from state: %s",
3730 static_cast<void *>(event_ptr), StateAsCString(state));
3731 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3732 PrivateResume();
3733 }
3734 } else {
3735 return_value = true;
3736 SynchronouslyNotifyStateChanged(state);
3737 }
3738 }
3739 break;
3740 }
3741
3742 // Forcing the next event delivery is a one shot deal. So reset it here.
3743 m_force_next_event_delivery = false;
3744
3745 // We do some coalescing of events (for instance two consecutive running
3746 // events get coalesced.)
3747 // But we only coalesce against events we actually broadcast. So we use
3748 // m_last_broadcast_state
3749 // to track that. NB - you can't use "m_public_state.GetValue()" for that
3750 // purpose, as was originally done,
3751 // because the PublicState reflects the last event pulled off the queue, and
3752 // there may be several
3753 // events stacked up on the queue unserviced. So the PublicState may not
3754 // reflect the last broadcasted event
3755 // yet. m_last_broadcast_state gets updated here.
3756
3757 if (return_value)
3758 m_last_broadcast_state = state;
3759
3760 if (log)
3761 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3762 "broadcast state: %s - %s",
3763 static_cast<void *>(event_ptr), StateAsCString(state),
3764 StateAsCString(m_last_broadcast_state),
3765 return_value ? "YES" : "NO");
3766 return return_value;
3767}
3768
3769bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3770 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3771
3772 bool already_running = PrivateStateThreadIsValid();
3773 if (log)
3774 log->Printf("Process::%s()%s ", __FUNCTION__,
3775 already_running ? " already running"
3776 : " starting private state thread");
3777
3778 if (!is_secondary_thread && already_running)
3779 return true;
3780
3781 // Create a thread that watches our internal state and controls which
3782 // events make it to clients (into the DCProcess event queue).
3783 char thread_name[1024];
3784
3785 if (HostInfo::GetMaxThreadNameLength() <= 30) {
3786 // On platforms with abbreviated thread name lengths, choose thread names
3787 // that fit within the limit.
3788 if (already_running)
3789 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3790 else
3791 snprintf(thread_name, sizeof(thread_name), "intern-state");
3792 } else {
3793 if (already_running)
3794 snprintf(thread_name, sizeof(thread_name),
3795 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3796 GetID());
3797 else
3798 snprintf(thread_name, sizeof(thread_name),
3799 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3800 }
3801
3802 // Create the private state thread, and start it running.
3803 PrivateStateThreadArgs *args_ptr =
3804 new PrivateStateThreadArgs(this, is_secondary_thread);
3805 m_private_state_thread =
3806 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3807 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3808 if (m_private_state_thread.IsJoinable()) {
3809 ResumePrivateStateThread();
3810 return true;
3811 } else
3812 return false;
3813}
3814
3815void Process::PausePrivateStateThread() {
3816 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3817}
3818
3819void Process::ResumePrivateStateThread() {
3820 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3821}
3822
3823void Process::StopPrivateStateThread() {
3824 if (m_private_state_thread.IsJoinable())
3825 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3826 else {
3827 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3828 if (log)
3829 log->Printf(
3830 "Went to stop the private state thread, but it was already invalid.");
3831 }
3832}
3833
3834void Process::ControlPrivateStateThread(uint32_t signal) {
3835 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3836
3837 assert(signal == eBroadcastInternalStateControlStop ||
3838 signal == eBroadcastInternalStateControlPause ||
3839 signal == eBroadcastInternalStateControlResume);
3840
3841 if (log)
3842 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3843
3844 // Signal the private state thread
3845 if (m_private_state_thread.IsJoinable()) {
3846 // Broadcast the event.
3847 // It is important to do this outside of the if below, because
3848 // it's possible that the thread state is invalid but that the
3849 // thread is waiting on a control event instead of simply being
3850 // on its way out (this should not happen, but it apparently can).
3851 if (log)
3852 log->Printf("Sending control event of type: %d.", signal);
3853 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3854 m_private_state_control_broadcaster.BroadcastEvent(signal,
3855 event_receipt_sp);
3856
3857 // Wait for the event receipt or for the private state thread to exit
3858 bool receipt_received = false;
3859 if (PrivateStateThreadIsValid()) {
3860 while (!receipt_received) {
3861 bool timed_out = false;
3862 // Check for a receipt for 2 seconds and then check if the private state
3863 // thread is still around.
3864 receipt_received = event_receipt_sp->WaitForEventReceived(
3865 std::chrono::seconds(2), &timed_out);
3866 if (!receipt_received) {
3867 // Check if the private state thread is still around. If it isn't then
3868 // we are done waiting
3869 if (!PrivateStateThreadIsValid())
3870 break; // Private state thread exited or is exiting, we are done
3871 }
3872 }
3873 }
3874
3875 if (signal == eBroadcastInternalStateControlStop) {
3876 thread_result_t result = NULL;
3877 m_private_state_thread.Join(&result);
3878 m_private_state_thread.Reset();
3879 }
3880 } else {
3881 if (log)
3882 log->Printf(
3883 "Private state thread already dead, no need to signal it to stop.");
3884 }
3885}
3886
3887void Process::SendAsyncInterrupt() {
3888 if (PrivateStateThreadIsValid())
3889 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3890 nullptr);
3891 else
3892 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3893}
3894
3895void Process::HandlePrivateEvent(EventSP &event_sp) {
3896 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3897 m_resume_requested = false;
3898
3899 const StateType new_state =
3900 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3901
3902 // First check to see if anybody wants a shot at this event:
3903 if (m_next_event_action_ap) {
3904 NextEventAction::EventActionResult action_result =
3905 m_next_event_action_ap->PerformAction(event_sp);
3906 if (log)
3907 log->Printf("Ran next event action, result was %d.", action_result);
3908
3909 switch (action_result) {
3910 case NextEventAction::eEventActionSuccess:
3911 SetNextEventAction(nullptr);
3912 break;
3913
3914 case NextEventAction::eEventActionRetry:
3915 break;
3916
3917 case NextEventAction::eEventActionExit:
3918 // Handle Exiting Here. If we already got an exited event,
3919 // we should just propagate it. Otherwise, swallow this event,
3920 // and set our state to exit so the next event will kill us.
3921 if (new_state != eStateExited) {
3922 // FIXME: should cons up an exited event, and discard this one.
3923 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3924 SetNextEventAction(nullptr);
3925 return;
3926 }
3927 SetNextEventAction(nullptr);
3928 break;
3929 }
3930 }
3931
3932 // See if we should broadcast this state to external clients?
3933 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3934
3935 if (should_broadcast) {
3936 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3937 if (log) {
3938 log->Printf("Process::%s (pid = %" PRIu64
3939 ") broadcasting new state %s (old state %s) to %s",
3940 __FUNCTION__, GetID(), StateAsCString(new_state),
3941 StateAsCString(GetState()),
3942 is_hijacked ? "hijacked" : "public");
3943 }
3944 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3945 if (StateIsRunningState(new_state)) {
3946 // Only push the input handler if we aren't fowarding events,
3947 // as this means the curses GUI is in use...
3948 // Or don't push it if we are launching since it will come up stopped.
3949 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3950 new_state != eStateLaunching && new_state != eStateAttaching) {
3951 PushProcessIOHandler();
3952 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3953 eBroadcastAlways);
3954 if (log)
3955 log->Printf("Process::%s updated m_iohandler_sync to %d",
3956 __FUNCTION__, m_iohandler_sync.GetValue());
3957 }
3958 } else if (StateIsStoppedState(new_state, false)) {
3959 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3960 // If the lldb_private::Debugger is handling the events, we don't
3961 // want to pop the process IOHandler here, we want to do it when
3962 // we receive the stopped event so we can carefully control when
3963 // the process IOHandler is popped because when we stop we want to
3964 // display some text stating how and why we stopped, then maybe some
3965 // process/thread/frame info, and then we want the "(lldb) " prompt
3966 // to show up. If we pop the process IOHandler here, then we will
3967 // cause the command interpreter to become the top IOHandler after
3968 // the process pops off and it will update its prompt right away...
3969 // See the Debugger.cpp file where it calls the function as
3970 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3971 // Otherwise we end up getting overlapping "(lldb) " prompts and
3972 // garbled output.
3973 //
3974 // If we aren't handling the events in the debugger (which is indicated
3975 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3976 // are hijacked, then we always pop the process IO handler manually.
3977 // Hijacking happens when the internal process state thread is running
3978 // thread plans, or when commands want to run in synchronous mode
3979 // and they call "process->WaitForProcessToStop()". An example of
3980 // something
3981 // that will hijack the events is a simple expression:
3982 //
3983 // (lldb) expr (int)puts("hello")
3984 //
3985 // This will cause the internal process state thread to resume and halt
3986 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3987 // events) and we do need the IO handler to be pushed and popped
3988 // correctly.
3989
3990 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3991 PopProcessIOHandler();
3992 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003993 }
3994
3995 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003996 } else {
3997 if (log) {
3998 log->Printf(
3999 "Process::%s (pid = %" PRIu64
4000 ") suppressing state %s (old state %s): should_broadcast == false",
4001 __FUNCTION__, GetID(), StateAsCString(new_state),
4002 StateAsCString(GetState()));
4003 }
4004 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004005}
4006
Kate Stoneb9c1b512016-09-06 20:57:50 +00004007Error Process::HaltPrivate() {
4008 EventSP event_sp;
4009 Error error(WillHalt());
4010 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004011 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004012
4013 // Ask the process subclass to actually halt our process
4014 bool caused_stop;
4015 error = DoHalt(caused_stop);
4016
4017 DidHalt();
4018 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004019}
4020
Kate Stoneb9c1b512016-09-06 20:57:50 +00004021thread_result_t Process::PrivateStateThread(void *arg) {
4022 std::unique_ptr<PrivateStateThreadArgs> args_up(
4023 static_cast<PrivateStateThreadArgs *>(arg));
4024 thread_result_t result =
4025 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
4026 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004027}
4028
Kate Stoneb9c1b512016-09-06 20:57:50 +00004029thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
4030 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00004031
Kate Stoneb9c1b512016-09-06 20:57:50 +00004032 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4033 if (log)
4034 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4035 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00004036
Kate Stoneb9c1b512016-09-06 20:57:50 +00004037 bool exit_now = false;
4038 bool interrupt_requested = false;
4039 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00004040 EventSP event_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004041 WaitForEventsPrivate(std::chrono::microseconds(0), event_sp, control_only);
4042 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4043 if (log)
4044 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4045 ") got a control event: %d",
4046 __FUNCTION__, static_cast<void *>(this), GetID(),
4047 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00004048
Kate Stoneb9c1b512016-09-06 20:57:50 +00004049 switch (event_sp->GetType()) {
4050 case eBroadcastInternalStateControlStop:
4051 exit_now = true;
4052 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00004053
Kate Stoneb9c1b512016-09-06 20:57:50 +00004054 case eBroadcastInternalStateControlPause:
4055 control_only = true;
4056 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004057
Kate Stoneb9c1b512016-09-06 20:57:50 +00004058 case eBroadcastInternalStateControlResume:
4059 control_only = false;
4060 break;
4061 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004062
Kate Stoneb9c1b512016-09-06 20:57:50 +00004063 continue;
4064 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4065 if (m_public_state.GetValue() == eStateAttaching) {
4066 if (log)
4067 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4068 ") woke up with an interrupt while attaching - "
4069 "forwarding interrupt.",
4070 __FUNCTION__, static_cast<void *>(this), GetID());
4071 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4072 } else if (StateIsRunningState(m_last_broadcast_state)) {
4073 if (log)
4074 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4075 ") woke up with an interrupt - Halting.",
4076 __FUNCTION__, static_cast<void *>(this), GetID());
4077 Error error = HaltPrivate();
4078 if (error.Fail() && log)
4079 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4080 ") failed to halt the process: %s",
4081 __FUNCTION__, static_cast<void *>(this), GetID(),
4082 error.AsCString());
4083 // Halt should generate a stopped event. Make a note of the fact that we
4084 // were
4085 // doing the interrupt, so we can set the interrupted flag after we
4086 // receive the
4087 // event. We deliberately set this to true even if HaltPrivate failed,
4088 // so that we
4089 // can interrupt on the next natural stop.
4090 interrupt_requested = true;
4091 } else {
4092 // This can happen when someone (e.g. Process::Halt) sees that we are
4093 // running and
4094 // sends an interrupt request, but the process actually stops before we
4095 // receive
4096 // it. In that case, we can just ignore the request. We use
4097 // m_last_broadcast_state, because the Stopped event may not have been
4098 // popped of
4099 // the event queue yet, which is when the public state gets updated.
4100 if (log)
4101 log->Printf(
4102 "Process::%s ignoring interrupt as we have already stopped.",
4103 __FUNCTION__);
4104 }
4105 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004106 }
4107
Kate Stoneb9c1b512016-09-06 20:57:50 +00004108 const StateType internal_state =
4109 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004110
Kate Stoneb9c1b512016-09-06 20:57:50 +00004111 if (internal_state != eStateInvalid) {
4112 if (m_clear_thread_plans_on_stop &&
4113 StateIsStoppedState(internal_state, true)) {
4114 m_clear_thread_plans_on_stop = false;
4115 m_thread_list.DiscardThreadPlans();
4116 }
4117
4118 if (interrupt_requested) {
4119 if (StateIsStoppedState(internal_state, true)) {
4120 // We requested the interrupt, so mark this as such in the stop event
4121 // so
4122 // clients can tell an interrupted process from a natural stop
4123 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4124 interrupt_requested = false;
4125 } else if (log) {
4126 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4127 "state '%s' received.",
4128 __FUNCTION__, StateAsCString(internal_state));
4129 }
4130 }
4131
4132 HandlePrivateEvent(event_sp);
4133 }
4134
4135 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4136 internal_state == eStateDetached) {
4137 if (log)
4138 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4139 ") about to exit with internal state %s...",
4140 __FUNCTION__, static_cast<void *>(this), GetID(),
4141 StateAsCString(internal_state));
4142
4143 break;
4144 }
4145 }
4146
4147 // Verify log is still enabled before attempting to write to it...
4148 if (log)
4149 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4150 __FUNCTION__, static_cast<void *>(this), GetID());
4151
4152 // If we are a secondary thread, then the primary thread we are working for
4153 // will have already
4154 // acquired the public_run_lock, and isn't done with what it was doing yet, so
4155 // don't
4156 // try to change it on the way out.
4157 if (!is_secondary_thread)
4158 m_public_run_lock.SetStopped();
4159 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004160}
4161
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004162//------------------------------------------------------------------
4163// Process Event Data
4164//------------------------------------------------------------------
4165
Kate Stoneb9c1b512016-09-06 20:57:50 +00004166Process::ProcessEventData::ProcessEventData()
4167 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4168 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004169
Kate Stoneb9c1b512016-09-06 20:57:50 +00004170Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4171 StateType state)
4172 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4173 m_update_state(0), m_interrupted(false) {
4174 if (process_sp)
4175 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004176}
4177
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004178Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004179
Kate Stoneb9c1b512016-09-06 20:57:50 +00004180const ConstString &Process::ProcessEventData::GetFlavorString() {
4181 static ConstString g_flavor("Process::ProcessEventData");
4182 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004183}
4184
Kate Stoneb9c1b512016-09-06 20:57:50 +00004185const ConstString &Process::ProcessEventData::GetFlavor() const {
4186 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004187}
4188
Kate Stoneb9c1b512016-09-06 20:57:50 +00004189void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4190 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004191
Kate Stoneb9c1b512016-09-06 20:57:50 +00004192 if (!process_sp)
4193 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004194
Kate Stoneb9c1b512016-09-06 20:57:50 +00004195 // This function gets called twice for each event, once when the event gets
4196 // pulled
4197 // off of the private process event queue, and then any number of times, first
4198 // when it gets pulled off of
4199 // the public event queue, then other times when we're pretending that this is
4200 // where we stopped at the
4201 // end of expression evaluation. m_update_state is used to distinguish these
4202 // three cases; it is 0 when we're just pulling it off for private handling,
4203 // and > 1 for expression evaluation, and we don't want to do the breakpoint
4204 // command handling then.
4205 if (m_update_state != 1)
4206 return;
4207
4208 process_sp->SetPublicState(
4209 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4210
4211 // If this is a halt event, even if the halt stopped with some reason other
4212 // than a plain interrupt (e.g. we had
4213 // already stopped for a breakpoint when the halt request came through) don't
4214 // do the StopInfo actions, as they may
4215 // end up restarting the process.
4216 if (m_interrupted)
4217 return;
4218
4219 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4220 if (m_state == eStateStopped && !m_restarted) {
4221 // Let process subclasses know we are about to do a public stop and
4222 // do anything they might need to in order to speed up register and
4223 // memory accesses.
4224 process_sp->WillPublicStop();
4225
4226 ThreadList &curr_thread_list = process_sp->GetThreadList();
4227 uint32_t num_threads = curr_thread_list.GetSize();
4228 uint32_t idx;
4229
4230 // The actions might change one of the thread's stop_info's opinions about
4231 // whether we should
4232 // stop the process, so we need to query that as we go.
4233
4234 // One other complication here, is that we try to catch any case where the
4235 // target has run (except for expressions)
4236 // and immediately exit, but if we get that wrong (which is possible) then
4237 // the thread list might have changed, and
4238 // that would cause our iteration here to crash. We could make a copy of
4239 // the thread list, but we'd really like
4240 // to also know if it has changed at all, so we make up a vector of the
4241 // thread ID's and check what we get back
4242 // against this list & bag out if anything differs.
4243 std::vector<uint32_t> thread_index_array(num_threads);
4244 for (idx = 0; idx < num_threads; ++idx)
4245 thread_index_array[idx] =
4246 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4247
4248 // Use this to track whether we should continue from here. We will only
4249 // continue the target running if
4250 // no thread says we should stop. Of course if some thread's PerformAction
4251 // actually sets the target running,
4252 // then it doesn't matter what the other threads say...
4253
4254 bool still_should_stop = false;
4255
4256 // Sometimes - for instance if we have a bug in the stub we are talking to,
4257 // we stop but no thread has a
4258 // valid stop reason. In that case we should just stop, because we have no
4259 // way of telling what the right
4260 // thing to do is, and it's better to let the user decide than continue
4261 // behind their backs.
4262
4263 bool does_anybody_have_an_opinion = false;
4264
4265 for (idx = 0; idx < num_threads; ++idx) {
4266 curr_thread_list = process_sp->GetThreadList();
4267 if (curr_thread_list.GetSize() != num_threads) {
4268 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4269 LIBLLDB_LOG_PROCESS));
4270 if (log)
4271 log->Printf(
4272 "Number of threads changed from %u to %u while processing event.",
4273 num_threads, curr_thread_list.GetSize());
4274 break;
4275 }
4276
4277 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4278
4279 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4280 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4281 LIBLLDB_LOG_PROCESS));
4282 if (log)
4283 log->Printf("The thread at position %u changed from %u to %u while "
4284 "processing event.",
4285 idx, thread_index_array[idx], thread_sp->GetIndexID());
4286 break;
4287 }
4288
4289 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4290 if (stop_info_sp && stop_info_sp->IsValid()) {
4291 does_anybody_have_an_opinion = true;
4292 bool this_thread_wants_to_stop;
4293 if (stop_info_sp->GetOverrideShouldStop()) {
4294 this_thread_wants_to_stop =
4295 stop_info_sp->GetOverriddenShouldStopValue();
4296 } else {
4297 stop_info_sp->PerformAction(event_ptr);
4298 // The stop action might restart the target. If it does, then we want
4299 // to mark that in the
4300 // event so that whoever is receiving it will know to wait for the
4301 // running event and reflect
4302 // that state appropriately.
4303 // We also need to stop processing actions, since they aren't
4304 // expecting the target to be running.
4305
4306 // FIXME: we might have run.
4307 if (stop_info_sp->HasTargetRunSinceMe()) {
4308 SetRestarted(true);
4309 break;
4310 }
4311
4312 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004313 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004314
4315 if (!still_should_stop)
4316 still_should_stop = this_thread_wants_to_stop;
4317 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004318 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004319
4320 if (!GetRestarted()) {
4321 if (!still_should_stop && does_anybody_have_an_opinion) {
4322 // We've been asked to continue, so do that here.
4323 SetRestarted(true);
4324 // Use the public resume method here, since this is just
4325 // extending a public resume.
4326 process_sp->PrivateResume();
4327 } else {
4328 // If we didn't restart, run the Stop Hooks here:
4329 // They might also restart the target, so watch for that.
4330 process_sp->GetTarget().RunStopHooks();
4331 if (process_sp->GetPrivateState() == eStateRunning)
4332 SetRestarted(true);
4333 }
4334 }
4335 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004336}
4337
Kate Stoneb9c1b512016-09-06 20:57:50 +00004338void Process::ProcessEventData::Dump(Stream *s) const {
4339 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004340
Kate Stoneb9c1b512016-09-06 20:57:50 +00004341 if (process_sp)
4342 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4343 static_cast<void *>(process_sp.get()), process_sp->GetID());
4344 else
4345 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004346
Kate Stoneb9c1b512016-09-06 20:57:50 +00004347 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004348}
4349
4350const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004351Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4352 if (event_ptr) {
4353 const EventData *event_data = event_ptr->GetData();
4354 if (event_data &&
4355 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4356 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4357 }
4358 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004359}
4360
4361ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004362Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4363 ProcessSP process_sp;
4364 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4365 if (data)
4366 process_sp = data->GetProcessSP();
4367 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004368}
4369
Kate Stoneb9c1b512016-09-06 20:57:50 +00004370StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4371 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4372 if (data == nullptr)
4373 return eStateInvalid;
4374 else
4375 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004376}
4377
Kate Stoneb9c1b512016-09-06 20:57:50 +00004378bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4379 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4380 if (data == nullptr)
4381 return false;
4382 else
4383 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004384}
4385
Kate Stoneb9c1b512016-09-06 20:57:50 +00004386void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4387 bool new_value) {
4388 ProcessEventData *data =
4389 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4390 if (data != nullptr)
4391 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004392}
4393
Jim Ingham0161b492013-02-09 01:29:05 +00004394size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004395Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4396 ProcessEventData *data =
4397 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4398 if (data != nullptr)
4399 return data->GetNumRestartedReasons();
4400 else
4401 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004402}
4403
4404const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004405Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4406 size_t idx) {
4407 ProcessEventData *data =
4408 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4409 if (data != nullptr)
4410 return data->GetRestartedReasonAtIndex(idx);
4411 else
4412 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004413}
4414
Kate Stoneb9c1b512016-09-06 20:57:50 +00004415void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4416 const char *reason) {
4417 ProcessEventData *data =
4418 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4419 if (data != nullptr)
4420 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004421}
4422
Kate Stoneb9c1b512016-09-06 20:57:50 +00004423bool Process::ProcessEventData::GetInterruptedFromEvent(
4424 const Event *event_ptr) {
4425 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4426 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004427 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004428 else
4429 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004430}
4431
Kate Stoneb9c1b512016-09-06 20:57:50 +00004432void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4433 bool new_value) {
4434 ProcessEventData *data =
4435 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4436 if (data != nullptr)
4437 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004438}
4439
Kate Stoneb9c1b512016-09-06 20:57:50 +00004440bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4441 ProcessEventData *data =
4442 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4443 if (data) {
4444 data->SetUpdateStateOnRemoval();
4445 return true;
4446 }
4447 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004448}
4449
Kate Stoneb9c1b512016-09-06 20:57:50 +00004450lldb::TargetSP Process::CalculateTarget() { return m_target_sp.lock(); }
4451
4452void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4453 exe_ctx.SetTargetPtr(&GetTarget());
4454 exe_ctx.SetProcessPtr(this);
4455 exe_ctx.SetThreadPtr(nullptr);
4456 exe_ctx.SetFramePtr(nullptr);
4457}
4458
4459// uint32_t
4460// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4461// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004462//{
4463// return 0;
4464//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004465//
4466// ArchSpec
4467// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004468//{
4469// return Host::GetArchSpecForExistingProcess (pid);
4470//}
4471//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004472// ArchSpec
4473// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004474//{
4475// return Host::GetArchSpecForExistingProcess (process_name);
4476//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004477
Kate Stoneb9c1b512016-09-06 20:57:50 +00004478void Process::AppendSTDOUT(const char *s, size_t len) {
4479 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4480 m_stdout_data.append(s, len);
4481 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4482 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004483}
4484
Kate Stoneb9c1b512016-09-06 20:57:50 +00004485void Process::AppendSTDERR(const char *s, size_t len) {
4486 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4487 m_stderr_data.append(s, len);
4488 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4489 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004490}
4491
Kate Stoneb9c1b512016-09-06 20:57:50 +00004492void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4493 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4494 m_profile_data.push_back(one_profile_data);
4495 BroadcastEventIfUnique(eBroadcastBitProfileData,
4496 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004497}
4498
Kate Stoneb9c1b512016-09-06 20:57:50 +00004499void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4500 const StructuredDataPluginSP &plugin_sp) {
4501 BroadcastEvent(
4502 eBroadcastBitStructuredData,
4503 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004504}
4505
4506StructuredDataPluginSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004507Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4508 auto find_it = m_structured_data_plugin_map.find(type_name);
4509 if (find_it != m_structured_data_plugin_map.end())
4510 return find_it->second;
4511 else
4512 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004513}
4514
Kate Stoneb9c1b512016-09-06 20:57:50 +00004515size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Error &error) {
4516 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4517 if (m_profile_data.empty())
4518 return 0;
4519
4520 std::string &one_profile_data = m_profile_data.front();
4521 size_t bytes_available = one_profile_data.size();
4522 if (bytes_available > 0) {
4523 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4524 if (log)
4525 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4526 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4527 if (bytes_available > buf_size) {
4528 memcpy(buf, one_profile_data.c_str(), buf_size);
4529 one_profile_data.erase(0, buf_size);
4530 bytes_available = buf_size;
4531 } else {
4532 memcpy(buf, one_profile_data.c_str(), bytes_available);
4533 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004534 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004535 }
4536 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004537}
4538
Greg Clayton93e86192011-11-13 04:45:22 +00004539//------------------------------------------------------------------
4540// Process STDIO
4541//------------------------------------------------------------------
4542
Kate Stoneb9c1b512016-09-06 20:57:50 +00004543size_t Process::GetSTDOUT(char *buf, size_t buf_size, Error &error) {
4544 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4545 size_t bytes_available = m_stdout_data.size();
4546 if (bytes_available > 0) {
4547 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4548 if (log)
4549 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4550 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4551 if (bytes_available > buf_size) {
4552 memcpy(buf, m_stdout_data.c_str(), buf_size);
4553 m_stdout_data.erase(0, buf_size);
4554 bytes_available = buf_size;
4555 } else {
4556 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4557 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004558 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004559 }
4560 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004561}
4562
Kate Stoneb9c1b512016-09-06 20:57:50 +00004563size_t Process::GetSTDERR(char *buf, size_t buf_size, Error &error) {
4564 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4565 size_t bytes_available = m_stderr_data.size();
4566 if (bytes_available > 0) {
4567 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4568 if (log)
4569 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4570 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4571 if (bytes_available > buf_size) {
4572 memcpy(buf, m_stderr_data.c_str(), buf_size);
4573 m_stderr_data.erase(0, buf_size);
4574 bytes_available = buf_size;
4575 } else {
4576 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4577 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004578 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004579 }
4580 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004581}
4582
Kate Stoneb9c1b512016-09-06 20:57:50 +00004583void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4584 size_t src_len) {
4585 Process *process = (Process *)baton;
4586 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004587}
4588
Kate Stoneb9c1b512016-09-06 20:57:50 +00004589class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004590public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004591 IOHandlerProcessSTDIO(Process *process, int write_fd)
4592 : IOHandler(process->GetTarget().GetDebugger(),
4593 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004594 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004595 m_pipe.CreateNew(false);
4596 m_read_file.SetDescriptor(GetInputFD(), false);
4597 }
4598
4599 ~IOHandlerProcessSTDIO() override = default;
4600
4601 // Each IOHandler gets to run until it is done. It should read data
4602 // from the "in" and place output into "out" and "err and return
4603 // when done.
4604 void Run() override {
4605 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4606 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4607 SetIsDone(true);
4608 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004609 }
4610
Kate Stoneb9c1b512016-09-06 20:57:50 +00004611 SetIsDone(false);
4612 const int read_fd = m_read_file.GetDescriptor();
4613 TerminalState terminal_state;
4614 terminal_state.Save(read_fd, false);
4615 Terminal terminal(read_fd);
4616 terminal.SetCanonical(false);
4617 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004618// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004619#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004620 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4621 m_is_running = true;
4622 while (!GetIsDone()) {
4623 SelectHelper select_helper;
4624 select_helper.FDSetRead(read_fd);
4625 select_helper.FDSetRead(pipe_read_fd);
4626 Error error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004627
Kate Stoneb9c1b512016-09-06 20:57:50 +00004628 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004629 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004630 } else {
4631 char ch = 0;
4632 size_t n;
4633 if (select_helper.FDIsSetRead(read_fd)) {
4634 n = 1;
4635 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4636 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4637 SetIsDone(true);
4638 } else
4639 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004640 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004641 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4642 size_t bytes_read;
4643 // Consume the interrupt byte
4644 Error error = m_pipe.Read(&ch, 1, bytes_read);
4645 if (error.Success()) {
4646 switch (ch) {
4647 case 'q':
4648 SetIsDone(true);
4649 break;
4650 case 'i':
4651 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004652 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004653 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004654 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004655 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004656 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004657 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004658 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004659 m_is_running = false;
4660#endif
4661 terminal_state.Restore();
4662 }
4663
4664 void Cancel() override {
4665 SetIsDone(true);
4666 // Only write to our pipe to cancel if we are in
4667 // IOHandlerProcessSTDIO::Run().
4668 // We can end up with a python command that is being run from the command
4669 // interpreter:
4670 //
4671 // (lldb) step_process_thousands_of_times
4672 //
4673 // In this case the command interpreter will be in the middle of handling
4674 // the command and if the process pushes and pops the IOHandler thousands
4675 // of times, we can end up writing to m_pipe without ever consuming the
4676 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4677 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4678 if (m_is_running) {
4679 char ch = 'q'; // Send 'q' for quit
4680 size_t bytes_written = 0;
4681 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004682 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004683 }
4684
4685 bool Interrupt() override {
4686 // Do only things that are safe to do in an interrupt context (like in
4687 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4688 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4689 // that was written to the pipe and then call
4690 // m_process->SendAsyncInterrupt()
4691 // from a much safer location in code.
4692 if (m_active) {
4693 char ch = 'i'; // Send 'i' for interrupt
4694 size_t bytes_written = 0;
4695 Error result = m_pipe.Write(&ch, 1, bytes_written);
4696 return result.Success();
4697 } else {
4698 // This IOHandler might be pushed on the stack, but not being run
4699 // currently
4700 // so do the right thing if we aren't actively watching for STDIN by
4701 // sending
4702 // the interrupt to the process. Otherwise the write to the pipe above
4703 // would
4704 // do nothing. This can happen when the command interpreter is running and
4705 // gets a "expression ...". It will be on the IOHandler thread and sending
4706 // the input is complete to the delegate which will cause the expression
4707 // to
4708 // run, which will push the process IO handler, but not run it.
4709
4710 if (StateIsRunningState(m_process->GetState())) {
4711 m_process->SendAsyncInterrupt();
4712 return true;
4713 }
4714 }
4715 return false;
4716 }
4717
4718 void GotEOF() override {}
4719
Greg Clayton44d93782014-01-27 23:43:24 +00004720protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004721 Process *m_process;
4722 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4723 File m_write_file; // Write to this file (usually the master pty for getting
4724 // io to debuggee)
4725 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004726 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004727};
4728
Kate Stoneb9c1b512016-09-06 20:57:50 +00004729void Process::SetSTDIOFileDescriptor(int fd) {
4730 // First set up the Read Thread for reading/handling process I/O
4731
4732 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4733 new ConnectionFileDescriptor(fd, true));
4734
4735 if (conn_ap) {
4736 m_stdio_communication.SetConnection(conn_ap.release());
4737 if (m_stdio_communication.IsConnected()) {
4738 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4739 STDIOReadThreadBytesReceived, this);
4740 m_stdio_communication.StartReadThread();
4741
4742 // Now read thread is set up, set up input reader.
4743
4744 if (!m_process_input_reader)
4745 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004746 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004747 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004748}
4749
Kate Stoneb9c1b512016-09-06 20:57:50 +00004750bool Process::ProcessIOHandlerIsActive() {
4751 IOHandlerSP io_handler_sp(m_process_input_reader);
4752 if (io_handler_sp)
4753 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4754 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004755}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004756bool Process::PushProcessIOHandler() {
4757 IOHandlerSP io_handler_sp(m_process_input_reader);
4758 if (io_handler_sp) {
4759 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4760 if (log)
4761 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004762
Kate Stoneb9c1b512016-09-06 20:57:50 +00004763 io_handler_sp->SetIsDone(false);
4764 GetTarget().GetDebugger().PushIOHandler(io_handler_sp);
4765 return true;
4766 }
4767 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004768}
4769
Kate Stoneb9c1b512016-09-06 20:57:50 +00004770bool Process::PopProcessIOHandler() {
4771 IOHandlerSP io_handler_sp(m_process_input_reader);
4772 if (io_handler_sp)
4773 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4774 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004775}
4776
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004777// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004778void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004779
Kate Stoneb9c1b512016-09-06 20:57:50 +00004780void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004781
Kate Stoneb9c1b512016-09-06 20:57:50 +00004782namespace {
4783// RestorePlanState is used to record the "is private", "is master" and "okay to
4784// discard" fields of
4785// the plan we are running, and reset it on Clean or on destruction.
4786// It will only reset the state once, so you can call Clean and then monkey with
4787// the state and it
4788// won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004789
Kate Stoneb9c1b512016-09-06 20:57:50 +00004790class RestorePlanState {
4791public:
4792 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4793 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4794 if (m_thread_plan_sp) {
4795 m_private = m_thread_plan_sp->GetPrivate();
4796 m_is_master = m_thread_plan_sp->IsMasterPlan();
4797 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4798 }
4799 }
4800
4801 ~RestorePlanState() { Clean(); }
4802
4803 void Clean() {
4804 if (!m_already_reset && m_thread_plan_sp) {
4805 m_already_reset = true;
4806 m_thread_plan_sp->SetPrivate(m_private);
4807 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4808 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4809 }
4810 }
4811
4812private:
4813 lldb::ThreadPlanSP m_thread_plan_sp;
4814 bool m_already_reset;
4815 bool m_private;
4816 bool m_is_master;
4817 bool m_okay_to_discard;
4818};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004819} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004820
Jim Ingham1624a2d2014-05-05 02:26:40 +00004821ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004822Process::RunThreadPlan(ExecutionContext &exe_ctx,
4823 lldb::ThreadPlanSP &thread_plan_sp,
4824 const EvaluateExpressionOptions &options,
4825 DiagnosticManager &diagnostic_manager) {
4826 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004827
Kate Stoneb9c1b512016-09-06 20:57:50 +00004828 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4829
4830 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004831 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004832 eDiagnosticSeverityError,
4833 "RunThreadPlan called with empty thread plan.");
4834 return eExpressionSetupError;
4835 }
4836
4837 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004838 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004839 eDiagnosticSeverityError,
4840 "RunThreadPlan called with an invalid thread plan.");
4841 return eExpressionSetupError;
4842 }
4843
4844 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004845 diagnostic_manager.PutString(eDiagnosticSeverityError,
4846 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004847 return eExpressionSetupError;
4848 }
4849
4850 Thread *thread = exe_ctx.GetThreadPtr();
4851 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004852 diagnostic_manager.PutString(eDiagnosticSeverityError,
4853 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004854 return eExpressionSetupError;
4855 }
4856
4857 // We need to change some of the thread plan attributes for the thread plan
4858 // runner. This will restore them
4859 // when we are done:
4860
4861 RestorePlanState thread_plan_restorer(thread_plan_sp);
4862
4863 // We rely on the thread plan we are running returning "PlanCompleted" if when
4864 // it successfully completes.
4865 // For that to be true the plan can't be private - since private plans
4866 // suppress themselves in the
4867 // GetCompletedPlan call.
4868
4869 thread_plan_sp->SetPrivate(false);
4870
4871 // The plans run with RunThreadPlan also need to be terminal master plans or
4872 // when they are done we will end
4873 // up asking the plan above us whether we should stop, which may give the
4874 // wrong answer.
4875
4876 thread_plan_sp->SetIsMasterPlan(true);
4877 thread_plan_sp->SetOkayToDiscard(false);
4878
4879 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004880 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004881 eDiagnosticSeverityError,
4882 "RunThreadPlan called while the private state was not stopped.");
4883 return eExpressionSetupError;
4884 }
4885
4886 // Save the thread & frame from the exe_ctx for restoration after we run
4887 const uint32_t thread_idx_id = thread->GetIndexID();
4888 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4889 if (!selected_frame_sp) {
4890 thread->SetSelectedFrame(nullptr);
4891 selected_frame_sp = thread->GetSelectedFrame();
4892 if (!selected_frame_sp) {
4893 diagnostic_manager.Printf(
4894 eDiagnosticSeverityError,
4895 "RunThreadPlan called without a selected frame on thread %d",
4896 thread_idx_id);
4897 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004898 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004899 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004900
Kate Stoneb9c1b512016-09-06 20:57:50 +00004901 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004902
Kate Stoneb9c1b512016-09-06 20:57:50 +00004903 // N.B. Running the target may unset the currently selected thread and frame.
4904 // We don't want to do that either,
4905 // so we should arrange to reset them as well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004906
Kate Stoneb9c1b512016-09-06 20:57:50 +00004907 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004908
Kate Stoneb9c1b512016-09-06 20:57:50 +00004909 uint32_t selected_tid;
4910 StackID selected_stack_id;
4911 if (selected_thread_sp) {
4912 selected_tid = selected_thread_sp->GetIndexID();
4913 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4914 } else {
4915 selected_tid = LLDB_INVALID_THREAD_ID;
4916 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004917
Kate Stoneb9c1b512016-09-06 20:57:50 +00004918 HostThread backup_private_state_thread;
4919 lldb::StateType old_state = eStateInvalid;
4920 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004921
Kate Stoneb9c1b512016-09-06 20:57:50 +00004922 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4923 LIBLLDB_LOG_PROCESS));
4924 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4925 // Yikes, we are running on the private state thread! So we can't wait for
4926 // public events on this thread, since
4927 // we are the thread that is generating public events.
4928 // The simplest thing to do is to spin up a temporary thread to handle
4929 // private state thread events while
4930 // we are fielding public events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004931 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004932 log->Printf("Running thread plan on private state thread, spinning up "
4933 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004934
Kate Stoneb9c1b512016-09-06 20:57:50 +00004935 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004936
Kate Stoneb9c1b512016-09-06 20:57:50 +00004937 // One other bit of business: we want to run just this thread plan and
4938 // anything it pushes, and then stop,
4939 // returning control here.
4940 // But in the normal course of things, the plan above us on the stack would
4941 // be given a shot at the stop
4942 // event before deciding to stop, and we don't want that. So we insert a
4943 // "stopper" base plan on the stack
4944 // before the plan we want to run. Since base plans always stop and return
4945 // control to the user, that will
4946 // do just what we want.
4947 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4948 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4949 // Have to make sure our public state is stopped, since otherwise the
4950 // reporting logic below doesn't work correctly.
4951 old_state = m_public_state.GetValue();
4952 m_public_state.SetValueNoLock(eStateStopped);
4953
4954 // Now spin up the private state thread:
4955 StartPrivateStateThread(true);
4956 }
4957
4958 thread->QueueThreadPlan(
4959 thread_plan_sp, false); // This used to pass "true" does that make sense?
4960
4961 if (options.GetDebug()) {
4962 // In this case, we aren't actually going to run, we just want to stop right
4963 // away.
4964 // Flush this thread so we will refetch the stacks and show the correct
4965 // backtrace.
4966 // FIXME: To make this prettier we should invent some stop reason for this,
4967 // but that
4968 // is only cosmetic, and this functionality is only of use to lldb
4969 // developers who can
4970 // live with not pretty...
4971 thread->Flush();
4972 return eExpressionStoppedForDebug;
4973 }
4974
4975 ListenerSP listener_sp(
4976 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4977
4978 lldb::EventSP event_to_broadcast_sp;
4979
4980 {
4981 // This process event hijacker Hijacks the Public events and its destructor
4982 // makes sure that the process events get
4983 // restored on exit to the function.
4984 //
4985 // If the event needs to propagate beyond the hijacker (e.g., the process
4986 // exits during execution), then the event
4987 // is put into event_to_broadcast_sp for rebroadcasting.
4988
4989 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4990
4991 if (log) {
4992 StreamString s;
4993 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4994 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4995 " to run thread plan \"%s\".",
4996 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004997 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004998
4999 bool got_event;
5000 lldb::EventSP event_sp;
5001 lldb::StateType stop_state = lldb::eStateInvalid;
5002
5003 bool before_first_timeout = true; // This is set to false the first time
5004 // that we have to halt the target.
5005 bool do_resume = true;
5006 bool handle_running_event = true;
5007 const uint64_t default_one_thread_timeout_usec = 250000;
5008
5009 // This is just for accounting:
5010 uint32_t num_resumes = 0;
5011
5012 uint32_t timeout_usec = options.GetTimeoutUsec();
5013 uint32_t one_thread_timeout_usec;
5014 uint32_t all_threads_timeout_usec = 0;
5015
5016 // If we are going to run all threads the whole time, or if we are only
5017 // going to run one thread,
5018 // then we don't need the first timeout. So we set the final timeout, and
5019 // pretend we are after the
5020 // first timeout already.
5021
5022 if (!options.GetStopOthers() || !options.GetTryAllThreads()) {
5023 before_first_timeout = false;
5024 one_thread_timeout_usec = 0;
5025 all_threads_timeout_usec = timeout_usec;
5026 } else {
5027 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
5028
5029 // If the overall wait is forever, then we only need to set the one thread
5030 // timeout:
5031 if (timeout_usec == 0) {
5032 if (option_one_thread_timeout != 0)
5033 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005034 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005035 one_thread_timeout_usec = default_one_thread_timeout_usec;
5036 } else {
5037 // Otherwise, if the one thread timeout is set, make sure it isn't
5038 // longer than the overall timeout,
5039 // and use it, otherwise use half the total timeout, bounded by the
5040 // default_one_thread_timeout_usec.
5041 uint64_t computed_one_thread_timeout;
5042 if (option_one_thread_timeout != 0) {
5043 if (timeout_usec < option_one_thread_timeout) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00005044 diagnostic_manager.PutString(eDiagnosticSeverityError,
5045 "RunThreadPlan called without one "
5046 "thread timeout greater than total "
5047 "timeout");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005048 return eExpressionSetupError;
5049 }
5050 computed_one_thread_timeout = option_one_thread_timeout;
5051 } else {
5052 computed_one_thread_timeout = timeout_usec / 2;
5053 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5054 computed_one_thread_timeout = default_one_thread_timeout_usec;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005055 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005056 one_thread_timeout_usec = computed_one_thread_timeout;
5057 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5058 }
Kuba Breckaafdf8422014-10-10 23:43:03 +00005059 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005060
Kate Stoneb9c1b512016-09-06 20:57:50 +00005061 if (log)
5062 log->Printf(
5063 "Stop others: %u, try all: %u, before_first: %u, one thread: %" PRIu32
5064 " - all threads: %" PRIu32 ".\n",
5065 options.GetStopOthers(), options.GetTryAllThreads(),
5066 before_first_timeout, one_thread_timeout_usec,
5067 all_threads_timeout_usec);
5068
5069 // This isn't going to work if there are unfetched events on the queue.
5070 // Are there cases where we might want to run the remaining events here, and
5071 // then try to
5072 // call the function? That's probably being too tricky for our own good.
5073
5074 Event *other_events = listener_sp->PeekAtNextEvent();
5075 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00005076 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005077 eDiagnosticSeverityError,
5078 "RunThreadPlan called with pending events on the queue.");
5079 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00005080 }
5081
Kate Stoneb9c1b512016-09-06 20:57:50 +00005082 // We also need to make sure that the next event is delivered. We might be
5083 // calling a function as part of
5084 // a thread plan, in which case the last delivered event could be the
5085 // running event, and we don't want
5086 // event coalescing to cause us to lose OUR running event...
5087 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00005088
Kate Stoneb9c1b512016-09-06 20:57:50 +00005089// This while loop must exit out the bottom, there's cleanup that we need to do
5090// when we are done.
5091// So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00005092
Kate Stoneb9c1b512016-09-06 20:57:50 +00005093#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5094 // It's pretty much impossible to write test cases for things like:
5095 // One thread timeout expires, I go to halt, but the process already stopped
5096 // on the function call stop breakpoint. Turning on this define will make
5097 // us not
5098 // fetch the first event till after the halt. So if you run a quick
5099 // function, it will have
5100 // completed, and the completion event will be waiting, when you interrupt
5101 // for halt.
5102 // The expression evaluation should still succeed.
5103 bool miss_first_event = true;
5104#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00005105 std::chrono::microseconds timeout = std::chrono::microseconds(0);
Kuba Breckaa51ea382014-09-06 01:33:13 +00005106
Kate Stoneb9c1b512016-09-06 20:57:50 +00005107 while (true) {
5108 // We usually want to resume the process if we get to the top of the loop.
5109 // The only exception is if we get two running events with no intervening
5110 // stop, which can happen, we will just wait for then next stop event.
5111 if (log)
5112 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5113 "before_first_timeout: %i.",
5114 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00005115
Kate Stoneb9c1b512016-09-06 20:57:50 +00005116 if (do_resume || handle_running_event) {
5117 // Do the initial resume and wait for the running event before going
5118 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00005119
Kate Stoneb9c1b512016-09-06 20:57:50 +00005120 if (do_resume) {
5121 num_resumes++;
5122 Error resume_error = PrivateResume();
5123 if (!resume_error.Success()) {
5124 diagnostic_manager.Printf(
5125 eDiagnosticSeverityError,
5126 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5127 resume_error.AsCString());
5128 return_value = eExpressionSetupError;
5129 break;
5130 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005131 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005132
Pavel Labathd35031e12016-11-30 10:41:42 +00005133 got_event =
5134 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005135 if (!got_event) {
5136 if (log)
5137 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5138 "resume %" PRIu32 ", exiting.",
5139 num_resumes);
5140
5141 diagnostic_manager.Printf(eDiagnosticSeverityError,
5142 "didn't get any event after resume %" PRIu32
5143 ", exiting.",
5144 num_resumes);
5145 return_value = eExpressionSetupError;
5146 break;
5147 }
5148
5149 stop_state =
5150 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5151
5152 if (stop_state != eStateRunning) {
5153 bool restarted = false;
5154
5155 if (stop_state == eStateStopped) {
5156 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5157 event_sp.get());
5158 if (log)
5159 log->Printf(
5160 "Process::RunThreadPlan(): didn't get running event after "
5161 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5162 "handle_running_event: %i).",
5163 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5164 handle_running_event);
5165 }
5166
5167 if (restarted) {
5168 // This is probably an overabundance of caution, I don't think I
5169 // should ever get a stopped & restarted
5170 // event here. But if I do, the best thing is to Halt and then get
5171 // out of here.
5172 const bool clear_thread_plans = false;
5173 const bool use_run_lock = false;
5174 Halt(clear_thread_plans, use_run_lock);
5175 }
5176
5177 diagnostic_manager.Printf(
5178 eDiagnosticSeverityError,
5179 "didn't get running event after initial resume, got %s instead.",
5180 StateAsCString(stop_state));
5181 return_value = eExpressionSetupError;
5182 break;
5183 }
5184
5185 if (log)
5186 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5187 // We need to call the function synchronously, so spin waiting for it to
5188 // return.
5189 // If we get interrupted while executing, we're going to lose our
5190 // context, and
5191 // won't be able to gather the result at this point.
5192 // We set the timeout AFTER the resume, since the resume takes some time
5193 // and we
5194 // don't want to charge that to the timeout.
5195 } else {
5196 if (log)
5197 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5198 }
5199
5200 if (before_first_timeout) {
5201 if (options.GetTryAllThreads())
5202 timeout = std::chrono::microseconds(one_thread_timeout_usec);
Jason Molendaef7d6412015-08-06 03:27:10 +00005203 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005204 timeout = std::chrono::microseconds(timeout_usec);
5205 } else {
5206 if (timeout_usec == 0)
5207 timeout = std::chrono::microseconds(0);
5208 else
5209 timeout = std::chrono::microseconds(all_threads_timeout_usec);
5210 }
5211
5212 do_resume = true;
5213 handle_running_event = true;
5214
5215 // Now wait for the process to stop again:
5216 event_sp.reset();
5217
5218 if (log) {
5219 if (timeout.count()) {
5220 log->Printf(
5221 "Process::RunThreadPlan(): about to wait - now is %llu - "
5222 "endpoint is %llu",
5223 static_cast<unsigned long long>(
5224 std::chrono::system_clock::now().time_since_epoch().count()),
5225 static_cast<unsigned long long>(
5226 std::chrono::time_point<std::chrono::system_clock,
5227 std::chrono::microseconds>(timeout)
5228 .time_since_epoch()
5229 .count()));
5230 } else {
5231 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005232 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005233 }
5234
5235#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5236 // See comment above...
5237 if (miss_first_event) {
5238 usleep(1000);
5239 miss_first_event = false;
5240 got_event = false;
5241 } else
5242#endif
Pavel Labathd35031e12016-11-30 10:41:42 +00005243 got_event = listener_sp->GetEvent(event_sp, ConvertTimeout(timeout));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005244
5245 if (got_event) {
5246 if (event_sp) {
5247 bool keep_going = false;
5248 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5249 const bool clear_thread_plans = false;
5250 const bool use_run_lock = false;
5251 Halt(clear_thread_plans, use_run_lock);
5252 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005253 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5254 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005255 if (log)
5256 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5257 "eBroadcastBitInterrupted, exiting.");
5258 break;
5259 } else {
5260 stop_state =
5261 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5262 if (log)
5263 log->Printf(
5264 "Process::RunThreadPlan(): in while loop, got event: %s.",
5265 StateAsCString(stop_state));
5266
5267 switch (stop_state) {
5268 case lldb::eStateStopped: {
5269 // We stopped, figure out what we are going to do now.
5270 ThreadSP thread_sp =
5271 GetThreadList().FindThreadByIndexID(thread_idx_id);
5272 if (!thread_sp) {
5273 // Ooh, our thread has vanished. Unlikely that this was
5274 // successful execution...
5275 if (log)
5276 log->Printf("Process::RunThreadPlan(): execution completed "
5277 "but our thread (index-id=%u) has vanished.",
5278 thread_idx_id);
5279 return_value = eExpressionInterrupted;
5280 } else {
5281 // If we were restarted, we just need to go back up to fetch
5282 // another event.
5283 if (Process::ProcessEventData::GetRestartedFromEvent(
5284 event_sp.get())) {
5285 if (log) {
5286 log->Printf("Process::RunThreadPlan(): Got a stop and "
5287 "restart, so we'll continue waiting.");
5288 }
5289 keep_going = true;
5290 do_resume = false;
5291 handle_running_event = true;
5292 } else {
5293 StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
5294 StopReason stop_reason = eStopReasonInvalid;
5295 if (stop_info_sp)
5296 stop_reason = stop_info_sp->GetStopReason();
5297
5298 // FIXME: We only check if the stop reason is plan complete,
5299 // should we make sure that
5300 // it is OUR plan that is complete?
5301 if (stop_reason == eStopReasonPlanComplete) {
5302 if (log)
5303 log->PutCString("Process::RunThreadPlan(): execution "
5304 "completed successfully.");
5305
5306 // Restore the plan state so it will get reported as
5307 // intended when we are done.
5308 thread_plan_restorer.Clean();
5309
5310 return_value = eExpressionCompleted;
5311 } else {
5312 // Something restarted the target, so just wait for it to
5313 // stop for real.
5314 if (stop_reason == eStopReasonBreakpoint) {
5315 if (log)
5316 log->Printf("Process::RunThreadPlan() stopped for "
5317 "breakpoint: %s.",
5318 stop_info_sp->GetDescription());
5319 return_value = eExpressionHitBreakpoint;
5320 if (!options.DoesIgnoreBreakpoints()) {
5321 // Restore the plan state and then force Private to
5322 // false. We are
5323 // going to stop because of this plan so we need it to
5324 // become a public
5325 // plan or it won't report correctly when we continue to
5326 // its termination
5327 // later on.
5328 thread_plan_restorer.Clean();
5329 if (thread_plan_sp)
5330 thread_plan_sp->SetPrivate(false);
5331 event_to_broadcast_sp = event_sp;
5332 }
5333 } else {
5334 if (log)
5335 log->PutCString("Process::RunThreadPlan(): thread plan "
5336 "didn't successfully complete.");
5337 if (!options.DoesUnwindOnError())
5338 event_to_broadcast_sp = event_sp;
5339 return_value = eExpressionInterrupted;
5340 }
5341 }
5342 }
5343 }
5344 } break;
5345
5346 case lldb::eStateRunning:
5347 // This shouldn't really happen, but sometimes we do get two
5348 // running events without an
5349 // intervening stop, and in that case we should just go back to
5350 // waiting for the stop.
5351 do_resume = false;
5352 keep_going = true;
5353 handle_running_event = false;
5354 break;
5355
5356 default:
5357 if (log)
5358 log->Printf("Process::RunThreadPlan(): execution stopped with "
5359 "unexpected state: %s.",
5360 StateAsCString(stop_state));
5361
5362 if (stop_state == eStateExited)
5363 event_to_broadcast_sp = event_sp;
5364
Zachary Turnere2411fa2016-11-12 19:12:56 +00005365 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005366 eDiagnosticSeverityError,
5367 "execution stopped with unexpected state.");
5368 return_value = eExpressionInterrupted;
5369 break;
5370 }
5371 }
5372
5373 if (keep_going)
5374 continue;
5375 else
5376 break;
5377 } else {
5378 if (log)
5379 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5380 "the event pointer was null. How odd...");
5381 return_value = eExpressionInterrupted;
5382 break;
5383 }
5384 } else {
5385 // If we didn't get an event that means we've timed out...
5386 // We will interrupt the process here. Depending on what we were asked
5387 // to do we will
5388 // either exit, or try with all threads running for the same timeout.
5389
5390 if (log) {
5391 if (options.GetTryAllThreads()) {
5392 if (before_first_timeout) {
5393 if (timeout_usec != 0) {
5394 log->Printf("Process::RunThreadPlan(): Running function with "
5395 "one thread timeout timed out, "
5396 "running for %" PRIu32
5397 " usec with all threads enabled.",
5398 all_threads_timeout_usec);
5399 } else {
5400 log->Printf("Process::RunThreadPlan(): Running function with "
5401 "one thread timeout timed out, "
5402 "running forever with all threads enabled.");
5403 }
5404 } else
5405 log->Printf("Process::RunThreadPlan(): Restarting function with "
5406 "all threads enabled "
5407 "and timeout: %u timed out, abandoning execution.",
5408 timeout_usec);
5409 } else
5410 log->Printf("Process::RunThreadPlan(): Running function with "
5411 "timeout: %u timed out, "
5412 "abandoning execution.",
5413 timeout_usec);
5414 }
5415
5416 // It is possible that between the time we issued the Halt, and we get
5417 // around to calling Halt the target
5418 // could have stopped. That's fine, Halt will figure that out and send
5419 // the appropriate Stopped event.
5420 // BUT it is also possible that we stopped & restarted (e.g. hit a
5421 // signal with "stop" set to false.) In
5422 // that case, we'll get the stopped & restarted event, and we should go
5423 // back to waiting for the Halt's
5424 // stopped event. That's what this while loop does.
5425
5426 bool back_to_top = true;
5427 uint32_t try_halt_again = 0;
5428 bool do_halt = true;
5429 const uint32_t num_retries = 5;
5430 while (try_halt_again < num_retries) {
5431 Error halt_error;
5432 if (do_halt) {
5433 if (log)
5434 log->Printf("Process::RunThreadPlan(): Running Halt.");
5435 const bool clear_thread_plans = false;
5436 const bool use_run_lock = false;
5437 Halt(clear_thread_plans, use_run_lock);
5438 }
5439 if (halt_error.Success()) {
5440 if (log)
5441 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5442
Pavel Labathd35031e12016-11-30 10:41:42 +00005443 got_event =
5444 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005445
5446 if (got_event) {
5447 stop_state =
5448 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5449 if (log) {
5450 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5451 StateAsCString(stop_state));
5452 if (stop_state == lldb::eStateStopped &&
5453 Process::ProcessEventData::GetInterruptedFromEvent(
5454 event_sp.get()))
5455 log->PutCString(" Event was the Halt interruption event.");
5456 }
5457
5458 if (stop_state == lldb::eStateStopped) {
5459 // Between the time we initiated the Halt and the time we
5460 // delivered it, the process could have
5461 // already finished its job. Check that here:
5462
5463 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5464 if (log)
5465 log->PutCString("Process::RunThreadPlan(): Even though we "
5466 "timed out, the call plan was done. "
5467 "Exiting wait loop.");
5468 return_value = eExpressionCompleted;
5469 back_to_top = false;
5470 break;
5471 }
5472
5473 if (Process::ProcessEventData::GetRestartedFromEvent(
5474 event_sp.get())) {
5475 if (log)
5476 log->PutCString("Process::RunThreadPlan(): Went to halt "
5477 "but got a restarted event, there must be "
5478 "an un-restarted stopped event so try "
5479 "again... "
5480 "Exiting wait loop.");
5481 try_halt_again++;
5482 do_halt = false;
5483 continue;
5484 }
5485
5486 if (!options.GetTryAllThreads()) {
5487 if (log)
5488 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5489 "was false, we stopped so now we're "
5490 "quitting.");
5491 return_value = eExpressionInterrupted;
5492 back_to_top = false;
5493 break;
5494 }
5495
5496 if (before_first_timeout) {
5497 // Set all the other threads to run, and return to the top of
5498 // the loop, which will continue;
5499 before_first_timeout = false;
5500 thread_plan_sp->SetStopOthers(false);
5501 if (log)
5502 log->PutCString(
5503 "Process::RunThreadPlan(): about to resume.");
5504
5505 back_to_top = true;
5506 break;
5507 } else {
5508 // Running all threads failed, so return Interrupted.
5509 if (log)
5510 log->PutCString("Process::RunThreadPlan(): running all "
5511 "threads timed out.");
5512 return_value = eExpressionInterrupted;
5513 back_to_top = false;
5514 break;
5515 }
5516 }
5517 } else {
5518 if (log)
5519 log->PutCString("Process::RunThreadPlan(): halt said it "
5520 "succeeded, but I got no event. "
5521 "I'm getting out of here passing Interrupted.");
5522 return_value = eExpressionInterrupted;
5523 back_to_top = false;
5524 break;
5525 }
5526 } else {
5527 try_halt_again++;
5528 continue;
5529 }
5530 }
5531
5532 if (!back_to_top || try_halt_again > num_retries)
5533 break;
5534 else
5535 continue;
5536 }
5537 } // END WAIT LOOP
5538
5539 // If we had to start up a temporary private state thread to run this thread
5540 // plan, shut it down now.
5541 if (backup_private_state_thread.IsJoinable()) {
5542 StopPrivateStateThread();
5543 Error error;
5544 m_private_state_thread = backup_private_state_thread;
5545 if (stopper_base_plan_sp) {
5546 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5547 }
5548 if (old_state != eStateInvalid)
5549 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005550 }
5551
Kate Stoneb9c1b512016-09-06 20:57:50 +00005552 if (return_value != eExpressionCompleted && log) {
5553 // Print a backtrace into the log so we can figure out where we are:
5554 StreamString s;
5555 s.PutCString("Thread state after unsuccessful completion: \n");
5556 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005557 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005558 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005559 // Restore the thread state if we are going to discard the plan execution.
5560 // There are three cases where this
5561 // could happen:
5562 // 1) The execution successfully completed
5563 // 2) We hit a breakpoint, and ignore_breakpoints was true
5564 // 3) We got some other error, and discard_on_error was true
5565 bool should_unwind = (return_value == eExpressionInterrupted &&
5566 options.DoesUnwindOnError()) ||
5567 (return_value == eExpressionHitBreakpoint &&
5568 options.DoesIgnoreBreakpoints());
5569
5570 if (return_value == eExpressionCompleted || should_unwind) {
5571 thread_plan_sp->RestoreThreadState();
5572 }
5573
5574 // Now do some processing on the results of the run:
5575 if (return_value == eExpressionInterrupted ||
5576 return_value == eExpressionHitBreakpoint) {
5577 if (log) {
5578 StreamString s;
5579 if (event_sp)
5580 event_sp->Dump(&s);
5581 else {
5582 log->PutCString("Process::RunThreadPlan(): Stop event that "
5583 "interrupted us is NULL.");
5584 }
5585
5586 StreamString ts;
5587
5588 const char *event_explanation = nullptr;
5589
5590 do {
5591 if (!event_sp) {
5592 event_explanation = "<no event>";
5593 break;
5594 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5595 event_explanation = "<user interrupt>";
5596 break;
5597 } else {
5598 const Process::ProcessEventData *event_data =
5599 Process::ProcessEventData::GetEventDataFromEvent(
5600 event_sp.get());
5601
5602 if (!event_data) {
5603 event_explanation = "<no event data>";
5604 break;
5605 }
5606
5607 Process *process = event_data->GetProcessSP().get();
5608
5609 if (!process) {
5610 event_explanation = "<no process>";
5611 break;
5612 }
5613
5614 ThreadList &thread_list = process->GetThreadList();
5615
5616 uint32_t num_threads = thread_list.GetSize();
5617 uint32_t thread_index;
5618
5619 ts.Printf("<%u threads> ", num_threads);
5620
5621 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5622 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5623
5624 if (!thread) {
5625 ts.Printf("<?> ");
5626 continue;
5627 }
5628
5629 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5630 RegisterContext *register_context =
5631 thread->GetRegisterContext().get();
5632
5633 if (register_context)
5634 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5635 else
5636 ts.Printf("[ip unknown] ");
5637
5638 // Show the private stop info here, the public stop info will be
5639 // from the last natural stop.
5640 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5641 if (stop_info_sp) {
5642 const char *stop_desc = stop_info_sp->GetDescription();
5643 if (stop_desc)
5644 ts.PutCString(stop_desc);
5645 }
5646 ts.Printf(">");
5647 }
5648
5649 event_explanation = ts.GetData();
5650 }
5651 } while (0);
5652
5653 if (event_explanation)
5654 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5655 s.GetData(), event_explanation);
5656 else
5657 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5658 s.GetData());
5659 }
5660
5661 if (should_unwind) {
5662 if (log)
5663 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5664 "discarding thread plans up to %p.",
5665 static_cast<void *>(thread_plan_sp.get()));
5666 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5667 } else {
5668 if (log)
5669 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5670 "plan: %p not discarding.",
5671 static_cast<void *>(thread_plan_sp.get()));
5672 }
5673 } else if (return_value == eExpressionSetupError) {
5674 if (log)
5675 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5676
5677 if (options.DoesUnwindOnError()) {
5678 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5679 }
5680 } else {
5681 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5682 if (log)
5683 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5684 return_value = eExpressionCompleted;
5685 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5686 if (log)
5687 log->PutCString(
5688 "Process::RunThreadPlan(): thread plan was discarded");
5689 return_value = eExpressionDiscarded;
5690 } else {
5691 if (log)
5692 log->PutCString(
5693 "Process::RunThreadPlan(): thread plan stopped in mid course");
5694 if (options.DoesUnwindOnError() && thread_plan_sp) {
5695 if (log)
5696 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5697 "'cause unwind_on_error is set.");
5698 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5699 }
5700 }
5701 }
5702
5703 // Thread we ran the function in may have gone away because we ran the
5704 // target
5705 // Check that it's still there, and if it is put it back in the context.
5706 // Also restore the
5707 // frame in the context if it is still present.
5708 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5709 if (thread) {
5710 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5711 }
5712
5713 // Also restore the current process'es selected frame & thread, since this
5714 // function calling may
5715 // be done behind the user's back.
5716
5717 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5718 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5719 selected_stack_id.IsValid()) {
5720 // We were able to restore the selected thread, now restore the frame:
5721 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5722 StackFrameSP old_frame_sp =
5723 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5724 selected_stack_id);
5725 if (old_frame_sp)
5726 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5727 old_frame_sp.get());
5728 }
5729 }
5730 }
5731
5732 // If the process exited during the run of the thread plan, notify everyone.
5733
5734 if (event_to_broadcast_sp) {
5735 if (log)
5736 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5737 BroadcastEvent(event_to_broadcast_sp);
5738 }
5739
5740 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005741}
5742
Kate Stoneb9c1b512016-09-06 20:57:50 +00005743const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5744 const char *result_name;
5745
5746 switch (result) {
5747 case eExpressionCompleted:
5748 result_name = "eExpressionCompleted";
5749 break;
5750 case eExpressionDiscarded:
5751 result_name = "eExpressionDiscarded";
5752 break;
5753 case eExpressionInterrupted:
5754 result_name = "eExpressionInterrupted";
5755 break;
5756 case eExpressionHitBreakpoint:
5757 result_name = "eExpressionHitBreakpoint";
5758 break;
5759 case eExpressionSetupError:
5760 result_name = "eExpressionSetupError";
5761 break;
5762 case eExpressionParseError:
5763 result_name = "eExpressionParseError";
5764 break;
5765 case eExpressionResultUnavailable:
5766 result_name = "eExpressionResultUnavailable";
5767 break;
5768 case eExpressionTimedOut:
5769 result_name = "eExpressionTimedOut";
5770 break;
5771 case eExpressionStoppedForDebug:
5772 result_name = "eExpressionStoppedForDebug";
5773 break;
5774 }
5775 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005776}
5777
Kate Stoneb9c1b512016-09-06 20:57:50 +00005778void Process::GetStatus(Stream &strm) {
5779 const StateType state = GetState();
5780 if (StateIsStoppedState(state, false)) {
5781 if (state == eStateExited) {
5782 int exit_status = GetExitStatus();
5783 const char *exit_description = GetExitDescription();
5784 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5785 GetID(), exit_status, exit_status,
5786 exit_description ? exit_description : "");
5787 } else {
5788 if (state == eStateConnected)
5789 strm.Printf("Connected to remote target.\n");
5790 else
5791 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5792 }
5793 } else {
5794 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5795 }
Pavel Labatha933d512016-04-05 13:07:16 +00005796}
5797
Kate Stoneb9c1b512016-09-06 20:57:50 +00005798size_t Process::GetThreadStatus(Stream &strm,
5799 bool only_threads_with_stop_reason,
5800 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005801 uint32_t num_frames_with_source,
5802 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005803 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005804
Kate Stoneb9c1b512016-09-06 20:57:50 +00005805 // You can't hold the thread list lock while calling Thread::GetStatus. That
5806 // very well might run code (e.g. if we need it
5807 // to get return values or arguments.) For that to work the process has to be
5808 // able to acquire it. So instead copy the thread
5809 // ID's, and look them up one by one:
5810
5811 uint32_t num_threads;
5812 std::vector<lldb::tid_t> thread_id_array;
5813 // Scope for thread list locker;
5814 {
5815 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5816 ThreadList &curr_thread_list = GetThreadList();
5817 num_threads = curr_thread_list.GetSize();
5818 uint32_t idx;
5819 thread_id_array.resize(num_threads);
5820 for (idx = 0; idx < num_threads; ++idx)
5821 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5822 }
5823
5824 for (uint32_t i = 0; i < num_threads; i++) {
5825 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5826 if (thread_sp) {
5827 if (only_threads_with_stop_reason) {
5828 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5829 if (!stop_info_sp || !stop_info_sp->IsValid())
5830 continue;
5831 }
5832 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005833 num_frames_with_source,
5834 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005835 ++num_thread_infos_dumped;
5836 } else {
5837 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5838 if (log)
5839 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5840 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005841 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005842 }
5843 return num_thread_infos_dumped;
5844}
5845
5846void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5847 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5848}
5849
5850bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5851 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5852 region.GetByteSize());
5853}
5854
5855void Process::AddPreResumeAction(PreResumeActionCallback callback,
5856 void *baton) {
5857 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5858}
5859
5860bool Process::RunPreResumeActions() {
5861 bool result = true;
5862 while (!m_pre_resume_actions.empty()) {
5863 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5864 m_pre_resume_actions.pop_back();
5865 bool this_result = action.callback(action.baton);
5866 if (result)
5867 result = this_result;
5868 }
5869 return result;
5870}
5871
5872void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5873
Jim Inghamffd91752016-10-20 22:50:00 +00005874void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5875{
5876 PreResumeCallbackAndBaton element(callback, baton);
5877 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5878 if (found_iter != m_pre_resume_actions.end())
5879 {
5880 m_pre_resume_actions.erase(found_iter);
5881 }
5882}
5883
Kate Stoneb9c1b512016-09-06 20:57:50 +00005884ProcessRunLock &Process::GetRunLock() {
5885 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5886 return m_private_run_lock;
5887 else
5888 return m_public_run_lock;
5889}
5890
5891void Process::Flush() {
5892 m_thread_list.Flush();
5893 m_extended_thread_list.Flush();
5894 m_extended_thread_stop_id = 0;
5895 m_queue_list.Clear();
5896 m_queue_list_stop_id = 0;
5897}
5898
5899void Process::DidExec() {
5900 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5901 if (log)
5902 log->Printf("Process::%s()", __FUNCTION__);
5903
5904 Target &target = GetTarget();
5905 target.CleanupProcess();
5906 target.ClearModules(false);
5907 m_dynamic_checkers_ap.reset();
5908 m_abi_sp.reset();
5909 m_system_runtime_ap.reset();
5910 m_os_ap.reset();
5911 m_dyld_ap.reset();
5912 m_jit_loaders_ap.reset();
5913 m_image_tokens.clear();
5914 m_allocated_memory_cache.Clear();
5915 m_language_runtimes.clear();
5916 m_instrumentation_runtimes.clear();
5917 m_thread_list.DiscardThreadPlans();
5918 m_memory_cache.Clear(true);
5919 m_stop_info_override_callback = nullptr;
5920 DoDidExec();
5921 CompleteAttach();
5922 // Flush the process (threads and all stack frames) after running
5923 // CompleteAttach()
5924 // in case the dynamic loader loaded things in new locations.
5925 Flush();
5926
5927 // After we figure out what was loaded/unloaded in CompleteAttach,
5928 // we need to let the target know so it can do any cleanup it needs to.
5929 target.DidExec();
5930}
5931
5932addr_t Process::ResolveIndirectFunction(const Address *address, Error &error) {
5933 if (address == nullptr) {
5934 error.SetErrorString("Invalid address argument");
5935 return LLDB_INVALID_ADDRESS;
5936 }
5937
5938 addr_t function_addr = LLDB_INVALID_ADDRESS;
5939
5940 addr_t addr = address->GetLoadAddress(&GetTarget());
5941 std::map<addr_t, addr_t>::const_iterator iter =
5942 m_resolved_indirect_addresses.find(addr);
5943 if (iter != m_resolved_indirect_addresses.end()) {
5944 function_addr = (*iter).second;
5945 } else {
5946 if (!InferiorCall(this, address, function_addr)) {
5947 Symbol *symbol = address->CalculateSymbolContextSymbol();
5948 error.SetErrorStringWithFormat(
5949 "Unable to call resolver for indirect function %s",
5950 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5951 function_addr = LLDB_INVALID_ADDRESS;
5952 } else {
5953 m_resolved_indirect_addresses.insert(
5954 std::pair<addr_t, addr_t>(addr, function_addr));
5955 }
5956 }
5957 return function_addr;
5958}
5959
5960void Process::ModulesDidLoad(ModuleList &module_list) {
5961 SystemRuntime *sys_runtime = GetSystemRuntime();
5962 if (sys_runtime) {
5963 sys_runtime->ModulesDidLoad(module_list);
5964 }
5965
5966 GetJITLoaders().ModulesDidLoad(module_list);
5967
5968 // Give runtimes a chance to be created.
5969 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5970 m_instrumentation_runtimes);
5971
5972 // Tell runtimes about new modules.
5973 for (auto pos = m_instrumentation_runtimes.begin();
5974 pos != m_instrumentation_runtimes.end(); ++pos) {
5975 InstrumentationRuntimeSP runtime = pos->second;
5976 runtime->ModulesDidLoad(module_list);
5977 }
5978
5979 // Let any language runtimes we have already created know
5980 // about the modules that loaded.
5981
5982 // Iterate over a copy of this language runtime list in case
5983 // the language runtime ModulesDidLoad somehow causes the language
5984 // riuntime to be unloaded.
5985 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5986 for (const auto &pair : language_runtimes) {
5987 // We must check language_runtime_sp to make sure it is not
5988 // nullptr as we might cache the fact that we didn't have a
5989 // language runtime for a language.
5990 LanguageRuntimeSP language_runtime_sp = pair.second;
5991 if (language_runtime_sp)
5992 language_runtime_sp->ModulesDidLoad(module_list);
5993 }
5994
5995 // If we don't have an operating system plug-in, try to load one since
5996 // loading shared libraries might cause a new one to try and load
5997 if (!m_os_ap)
5998 LoadOperatingSystemPlugin(false);
5999
6000 // Give structured-data plugins a chance to see the modified modules.
6001 for (auto pair : m_structured_data_plugin_map) {
6002 if (pair.second)
6003 pair.second->ModulesDidLoad(*this, module_list);
6004 }
6005}
6006
6007void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
6008 const char *fmt, ...) {
6009 bool print_warning = true;
6010
6011 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
6012 if (!stream_sp)
6013 return;
6014 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
6015 return;
6016 }
6017
6018 if (repeat_key != nullptr) {
6019 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
6020 if (it == m_warnings_issued.end()) {
6021 m_warnings_issued[warning_type] = WarningsPointerSet();
6022 m_warnings_issued[warning_type].insert(repeat_key);
6023 } else {
6024 if (it->second.find(repeat_key) != it->second.end()) {
6025 print_warning = false;
6026 } else {
6027 it->second.insert(repeat_key);
6028 }
6029 }
6030 }
6031
6032 if (print_warning) {
6033 va_list args;
6034 va_start(args, fmt);
6035 stream_sp->PrintfVarArg(fmt, args);
6036 va_end(args);
6037 }
6038}
6039
6040void Process::PrintWarningOptimization(const SymbolContext &sc) {
6041 if (GetWarningsOptimization() && sc.module_sp &&
6042 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
6043 sc.function->GetIsOptimized()) {
6044 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
6045 "%s was compiled with optimization - stepping may behave "
6046 "oddly; variables may not be available.\n",
6047 sc.module_sp->GetFileSpec().GetFilename().GetCString());
6048 }
6049}
6050
6051bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
6052 info.Clear();
6053
6054 PlatformSP platform_sp = GetTarget().GetPlatform();
6055 if (!platform_sp)
6056 return false;
6057
6058 return platform_sp->GetProcessInfo(GetID(), info);
6059}
6060
6061ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
6062 ThreadCollectionSP threads;
6063
6064 const MemoryHistorySP &memory_history =
6065 MemoryHistory::FindPlugin(shared_from_this());
6066
6067 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00006068 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006069 }
6070
6071 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6072
6073 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00006074}
Kuba Brecka63927542014-10-11 01:59:32 +00006075
6076InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00006077Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
6078 InstrumentationRuntimeCollection::iterator pos;
6079 pos = m_instrumentation_runtimes.find(type);
6080 if (pos == m_instrumentation_runtimes.end()) {
6081 return InstrumentationRuntimeSP();
6082 } else
6083 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00006084}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006085
Kate Stoneb9c1b512016-09-06 20:57:50 +00006086bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6087 const ArchSpec &arch, ModuleSpec &module_spec) {
6088 module_spec.Clear();
6089 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006090}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006091
Kate Stoneb9c1b512016-09-06 20:57:50 +00006092size_t Process::AddImageToken(lldb::addr_t image_ptr) {
6093 m_image_tokens.push_back(image_ptr);
6094 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006095}
6096
Kate Stoneb9c1b512016-09-06 20:57:50 +00006097lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
6098 if (token < m_image_tokens.size())
6099 return m_image_tokens[token];
6100 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006101}
6102
Kate Stoneb9c1b512016-09-06 20:57:50 +00006103void Process::ResetImageToken(size_t token) {
6104 if (token < m_image_tokens.size())
6105 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00006106}
Jason Molendafd4cea52016-01-08 21:40:11 +00006107
6108Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00006109Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
6110 AddressRange range_bounds) {
6111 Target &target = GetTarget();
6112 DisassemblerSP disassembler_sp;
6113 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006114
Kate Stoneb9c1b512016-09-06 20:57:50 +00006115 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006116
Kate Stoneb9c1b512016-09-06 20:57:50 +00006117 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00006118 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006119 if (!default_stop_addr.IsValid())
6120 return retval;
6121
6122 ExecutionContext exe_ctx(this);
6123 const char *plugin_name = nullptr;
6124 const char *flavor = nullptr;
6125 const bool prefer_file_cache = true;
6126 disassembler_sp = Disassembler::DisassembleRange(
6127 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6128 prefer_file_cache);
6129 if (disassembler_sp)
6130 insn_list = &disassembler_sp->GetInstructionList();
6131
6132 if (insn_list == nullptr) {
6133 return retval;
6134 }
6135
6136 size_t insn_offset =
6137 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6138 if (insn_offset == UINT32_MAX) {
6139 return retval;
6140 }
6141
6142 uint32_t branch_index =
6143 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6144 if (branch_index == UINT32_MAX) {
6145 return retval;
6146 }
6147
6148 if (branch_index > insn_offset) {
6149 Address next_branch_insn_address =
6150 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6151 if (next_branch_insn_address.IsValid() &&
6152 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6153 retval = next_branch_insn_address;
6154 }
6155 }
6156
6157 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00006158}
Howard Hellyerad007562016-07-07 08:21:28 +00006159
Kate Stoneb9c1b512016-09-06 20:57:50 +00006160Error Process::GetMemoryRegions(
6161 std::vector<lldb::MemoryRegionInfoSP> &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00006162
Kate Stoneb9c1b512016-09-06 20:57:50 +00006163 Error error;
Howard Hellyerad007562016-07-07 08:21:28 +00006164
Kate Stoneb9c1b512016-09-06 20:57:50 +00006165 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00006166
Kate Stoneb9c1b512016-09-06 20:57:50 +00006167 region_list.clear();
6168 do {
6169 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6170 error = GetMemoryRegionInfo(range_end, *region_info);
6171 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6172 if (error.Fail()) {
6173 region_list.clear();
6174 break;
Todd Fiala75930012016-08-19 04:21:48 +00006175 }
6176
Kate Stoneb9c1b512016-09-06 20:57:50 +00006177 range_end = region_info->GetRange().GetRangeEnd();
6178 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6179 region_list.push_back(region_info);
6180 }
6181 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00006182
Kate Stoneb9c1b512016-09-06 20:57:50 +00006183 return error;
6184}
6185
6186Error Process::ConfigureStructuredData(
6187 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
6188 // If you get this, the Process-derived class needs to implement a method
6189 // to enable an already-reported asynchronous structured data feature.
6190 // See ProcessGDBRemote for an example implementation over gdb-remote.
6191 return Error("unimplemented");
6192}
6193
6194void Process::MapSupportedStructuredDataPlugins(
6195 const StructuredData::Array &supported_type_names) {
6196 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6197
6198 // Bail out early if there are no type names to map.
6199 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00006200 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006201 log->Printf("Process::%s(): no structured data types supported",
6202 __FUNCTION__);
6203 return;
6204 }
Todd Fiala75930012016-08-19 04:21:48 +00006205
Kate Stoneb9c1b512016-09-06 20:57:50 +00006206 // Convert StructuredData type names to ConstString instances.
6207 std::set<ConstString> const_type_names;
6208
6209 if (log)
6210 log->Printf("Process::%s(): the process supports the following async "
6211 "structured data types:",
6212 __FUNCTION__);
6213
6214 supported_type_names.ForEach(
6215 [&const_type_names, &log](StructuredData::Object *object) {
6216 if (!object) {
6217 // Invalid - shouldn't be null objects in the array.
6218 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006219 }
6220
6221 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006222 if (!type_name) {
6223 // Invalid format - all type names should be strings.
6224 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006225 }
6226
6227 const_type_names.insert(ConstString(type_name->GetValue()));
6228 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006229 log->Printf("- %s", type_name->GetValue().c_str());
Todd Fiala75930012016-08-19 04:21:48 +00006230 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006231 });
Todd Fiala75930012016-08-19 04:21:48 +00006232
Kate Stoneb9c1b512016-09-06 20:57:50 +00006233 // For each StructuredDataPlugin, if the plugin handles any of the
6234 // types in the supported_type_names, map that type name to that plugin.
6235 uint32_t plugin_index = 0;
6236 for (auto create_instance =
6237 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6238 plugin_index);
6239 create_instance && !const_type_names.empty(); ++plugin_index) {
6240 // Create the plugin.
6241 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6242 if (!plugin_sp) {
6243 // This plugin doesn't think it can work with the process.
6244 // Move on to the next.
6245 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006246 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006247
6248 // For any of the remaining type names, map any that this plugin
6249 // supports.
6250 std::vector<ConstString> names_to_remove;
6251 for (auto &type_name : const_type_names) {
6252 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6253 m_structured_data_plugin_map.insert(
6254 std::make_pair(type_name, plugin_sp));
6255 names_to_remove.push_back(type_name);
6256 if (log)
6257 log->Printf("Process::%s(): using plugin %s for type name "
6258 "%s",
6259 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6260 type_name.GetCString());
6261 }
6262 }
6263
6264 // Remove the type names that were consumed by this plugin.
6265 for (auto &type_name : names_to_remove)
6266 const_type_names.erase(type_name);
6267 }
Todd Fiala75930012016-08-19 04:21:48 +00006268}
6269
Kate Stoneb9c1b512016-09-06 20:57:50 +00006270bool Process::RouteAsyncStructuredData(
6271 const StructuredData::ObjectSP object_sp) {
6272 // Nothing to do if there's no data.
6273 if (!object_sp)
6274 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006275
Kate Stoneb9c1b512016-09-06 20:57:50 +00006276 // The contract is this must be a dictionary, so we can look up the
6277 // routing key via the top-level 'type' string value within the dictionary.
6278 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6279 if (!dictionary)
6280 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006281
Kate Stoneb9c1b512016-09-06 20:57:50 +00006282 // Grab the async structured type name (i.e. the feature/plugin name).
6283 ConstString type_name;
6284 if (!dictionary->GetValueForKeyAsString("type", type_name))
6285 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006286
Kate Stoneb9c1b512016-09-06 20:57:50 +00006287 // Check if there's a plugin registered for this type name.
6288 auto find_it = m_structured_data_plugin_map.find(type_name);
6289 if (find_it == m_structured_data_plugin_map.end()) {
6290 // We don't have a mapping for this structured data type.
6291 return false;
6292 }
Todd Fiala75930012016-08-19 04:21:48 +00006293
Kate Stoneb9c1b512016-09-06 20:57:50 +00006294 // Route the structured data to the plugin.
6295 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6296 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006297}