blob: 0bc58f073bf1a6f2075cd88443ac00bacdd5adc2 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Eugene Zelenko8f30a652015-10-23 18:39:37 +000010// C Includes
11// C++ Includes
Greg Clayton5cc45e02016-02-26 19:41:49 +000012#include <atomic>
Greg Clayton04df8ee2016-02-26 19:38:18 +000013#include <mutex>
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +000014
Eugene Zelenko8f30a652015-10-23 18:39:37 +000015// Other libraries and framework includes
Pavel Labath2ce22162016-12-01 10:57:30 +000016#include "llvm/Support/ScopedPrinter.h"
Zachary Turner777de772017-03-04 16:42:25 +000017#include "llvm/Support/Threading.h"
18
Eugene Zelenko8f30a652015-10-23 18:39:37 +000019// Project includes
Sean Callanan579e70c2016-03-19 00:03:59 +000020#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include "lldb/Breakpoint/BreakpointLocation.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000022#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include "lldb/Core/Debugger.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000024#include "lldb/Core/Event.h"
Greg Clayton1f746072012-08-29 21:13:06 +000025#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000026#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027#include "lldb/Core/PluginManager.h"
28#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000029#include "lldb/Core/StreamFile.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000030#include "lldb/Expression/DiagnosticManager.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000031#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000032#include "lldb/Expression/UserExpression.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000033#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000034#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000036#include "lldb/Host/HostInfo.h"
Zachary Turner3eb2b442017-03-22 23:33:16 +000037#include "lldb/Host/OptionParser.h"
Greg Clayton100eb932014-07-02 21:10:39 +000038#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000039#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000040#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000041#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000042#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000043#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000044#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000045#include "lldb/Target/ABI.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000046#include "lldb/Target/CPPLanguageRuntime.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000047#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000048#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000049#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000050#include "lldb/Target/JITLoaderList.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000051#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000052#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000053#include "lldb/Target/MemoryRegionInfo.h"
Jim Ingham22777012010-09-23 02:01:19 +000054#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000055#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000056#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000057#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000058#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000059#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000060#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000061#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000062#include "lldb/Target/Target.h"
63#include "lldb/Target/TargetList.h"
64#include "lldb/Target/Thread.h"
65#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000066#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000067#include "lldb/Target/UnixSignals.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000068#include "lldb/Utility/Log.h"
Zachary Turner50232572015-03-18 21:31:45 +000069#include "lldb/Utility/NameMatches.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000070#include "lldb/Utility/SelectHelper.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071
72using namespace lldb;
73using namespace lldb_private;
Pavel Labathe3e21cf2016-11-30 11:56:32 +000074using namespace std::chrono;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075
Kate Stoneb9c1b512016-09-06 20:57:50 +000076// Comment out line below to disable memory caching, overriding the process
Pavel Labath43d35412016-12-06 11:24:51 +000077// setting target.process.disable-memory-cache
Greg Clayton67cc0632012-08-22 17:17:09 +000078#define ENABLE_MEMORY_CACHING
79
80#ifdef ENABLE_MEMORY_CACHING
81#define DISABLE_MEM_CACHE_DEFAULT false
82#else
83#define DISABLE_MEM_CACHE_DEFAULT true
84#endif
85
Kate Stoneb9c1b512016-09-06 20:57:50 +000086class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000087public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 ProcessOptionValueProperties(const ConstString &name)
89 : OptionValueProperties(name) {}
90
91 // This constructor is used when creating ProcessOptionValueProperties when it
92 // is part of a new lldb_private::Process instance. It will copy all current
93 // global property values as needed
94 ProcessOptionValueProperties(ProcessProperties *global_properties)
95 : OptionValueProperties(*global_properties->GetValueProperties()) {}
96
97 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
98 bool will_modify,
99 uint32_t idx) const override {
100 // When getting the value for a key from the process options, we will always
101 // try and grab the setting from the current process if there is one. Else
102 // we just
103 // use the one from this instance.
104 if (exe_ctx) {
105 Process *process = exe_ctx->GetProcessPtr();
106 if (process) {
107 ProcessOptionValueProperties *instance_properties =
108 static_cast<ProcessOptionValueProperties *>(
109 process->GetValueProperties().get());
110 if (this != instance_properties)
111 return instance_properties->ProtectedGetPropertyAtIndex(idx);
112 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000113 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 return ProtectedGetPropertyAtIndex(idx);
115 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000116};
117
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118static PropertyDefinition g_properties[] = {
119 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
120 DISABLE_MEM_CACHE_DEFAULT, nullptr, nullptr,
121 "Disable reading and caching of memory in fixed-size units."},
122 {"extra-startup-command", OptionValue::eTypeArray, false,
123 OptionValue::eTypeString, nullptr, nullptr,
124 "A list containing extra commands understood by the particular process "
125 "plugin used. "
126 "For instance, to turn on debugserver logging set this to "
127 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
128 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
129 nullptr, nullptr,
130 "If true, breakpoints will be ignored during expression evaluation."},
131 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
132 nullptr, nullptr, "If true, errors in expression evaluation will unwind "
133 "the stack back to the state before the call."},
134 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
135 nullptr, "A path to a python OS plug-in module file that contains a "
136 "OperatingSystemPlugIn class."},
137 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
138 nullptr, nullptr,
139 "If true, stop when a shared library is loaded or unloaded."},
140 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
141 nullptr, "If true, detach will attempt to keep the process stopped."},
142 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
143 nullptr, "The memory cache line size"},
144 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
145 nullptr, "If true, warn when stopped in code that is optimized where "
146 "stepping and variable availability may not behave as expected."},
147 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000148
149enum {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 ePropertyDisableMemCache,
151 ePropertyExtraStartCommand,
152 ePropertyIgnoreBreakpointsInExpressions,
153 ePropertyUnwindOnErrorInExpressions,
154 ePropertyPythonOSPluginPath,
155 ePropertyStopOnSharedLibraryEvents,
156 ePropertyDetachKeepsStopped,
157 ePropertyMemCacheLineSize,
158 ePropertyWarningOptimization
Greg Clayton67cc0632012-08-22 17:17:09 +0000159};
160
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161ProcessProperties::ProcessProperties(lldb_private::Process *process)
162 : Properties(),
163 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000164{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165 if (process == nullptr) {
166 // Global process properties, set them up one time
167 m_collection_sp.reset(
168 new ProcessOptionValueProperties(ConstString("process")));
169 m_collection_sp->Initialize(g_properties);
170 m_collection_sp->AppendProperty(
171 ConstString("thread"), ConstString("Settings specific to threads."),
172 true, Thread::GetGlobalProperties()->GetValueProperties());
173 } else {
174 m_collection_sp.reset(
175 new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
176 m_collection_sp->SetValueChangedCallback(
177 ePropertyPythonOSPluginPath,
178 ProcessProperties::OptionValueChangedCallback, this);
179 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000180}
181
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000182ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000183
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184void ProcessProperties::OptionValueChangedCallback(void *baton,
185 OptionValue *option_value) {
186 ProcessProperties *properties = (ProcessProperties *)baton;
187 if (properties->m_process)
188 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000189}
190
Kate Stoneb9c1b512016-09-06 20:57:50 +0000191bool ProcessProperties::GetDisableMemoryCache() const {
192 const uint32_t idx = ePropertyDisableMemCache;
193 return m_collection_sp->GetPropertyAtIndexAsBoolean(
194 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000195}
196
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
198 const uint32_t idx = ePropertyMemCacheLineSize;
199 return m_collection_sp->GetPropertyAtIndexAsUInt64(
200 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000201}
202
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203Args ProcessProperties::GetExtraStartupCommands() const {
204 Args args;
205 const uint32_t idx = ePropertyExtraStartCommand;
206 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
207 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000208}
209
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210void ProcessProperties::SetExtraStartupCommands(const Args &args) {
211 const uint32_t idx = ePropertyExtraStartCommand;
212 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000213}
214
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215FileSpec ProcessProperties::GetPythonOSPluginPath() const {
216 const uint32_t idx = ePropertyPythonOSPluginPath;
217 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000218}
219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
221 const uint32_t idx = ePropertyPythonOSPluginPath;
222 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000223}
224
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
226 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
227 return m_collection_sp->GetPropertyAtIndexAsBoolean(
228 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000229}
230
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
232 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
233 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000234}
235
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
237 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
238 return m_collection_sp->GetPropertyAtIndexAsBoolean(
239 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000240}
241
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
243 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
244 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000245}
246
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
248 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
249 return m_collection_sp->GetPropertyAtIndexAsBoolean(
250 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000251}
252
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
254 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
255 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
256}
257
258bool ProcessProperties::GetDetachKeepsStopped() const {
259 const uint32_t idx = ePropertyDetachKeepsStopped;
260 return m_collection_sp->GetPropertyAtIndexAsBoolean(
261 nullptr, idx, g_properties[idx].default_uint_value != 0);
262}
263
264void ProcessProperties::SetDetachKeepsStopped(bool stop) {
265 const uint32_t idx = ePropertyDetachKeepsStopped;
266 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
267}
268
269bool ProcessProperties::GetWarningsOptimization() const {
270 const uint32_t idx = ePropertyWarningOptimization;
271 return m_collection_sp->GetPropertyAtIndexAsBoolean(
272 nullptr, idx, g_properties[idx].default_uint_value != 0);
273}
274
275void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const {
276 const char *cstr;
277 if (m_pid != LLDB_INVALID_PROCESS_ID)
278 s.Printf(" pid = %" PRIu64 "\n", m_pid);
279
280 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
281 s.Printf(" parent = %" PRIu64 "\n", m_parent_pid);
282
283 if (m_executable) {
284 s.Printf(" name = %s\n", m_executable.GetFilename().GetCString());
285 s.PutCString(" file = ");
286 m_executable.Dump(&s);
287 s.EOL();
288 }
289 const uint32_t argc = m_arguments.GetArgumentCount();
290 if (argc > 0) {
291 for (uint32_t i = 0; i < argc; i++) {
292 const char *arg = m_arguments.GetArgumentAtIndex(i);
293 if (i < 10)
294 s.Printf(" arg[%u] = %s\n", i, arg);
295 else
296 s.Printf("arg[%u] = %s\n", i, arg);
297 }
298 }
299
300 const uint32_t envc = m_environment.GetArgumentCount();
301 if (envc > 0) {
302 for (uint32_t i = 0; i < envc; i++) {
303 const char *env = m_environment.GetArgumentAtIndex(i);
304 if (i < 10)
305 s.Printf(" env[%u] = %s\n", i, env);
306 else
307 s.Printf("env[%u] = %s\n", i, env);
308 }
309 }
310
311 if (m_arch.IsValid()) {
312 s.Printf(" arch = ");
313 m_arch.DumpTriple(s);
314 s.EOL();
315 }
316
317 if (m_uid != UINT32_MAX) {
318 cstr = platform->GetUserName(m_uid);
319 s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
320 }
321 if (m_gid != UINT32_MAX) {
322 cstr = platform->GetGroupName(m_gid);
323 s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
324 }
325 if (m_euid != UINT32_MAX) {
326 cstr = platform->GetUserName(m_euid);
327 s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
328 }
329 if (m_egid != UINT32_MAX) {
330 cstr = platform->GetGroupName(m_egid);
331 s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
332 }
333}
334
335void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform,
336 bool show_args, bool verbose) {
337 const char *label;
338 if (show_args || verbose)
339 label = "ARGUMENTS";
340 else
341 label = "NAME";
342
343 if (verbose) {
344 s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE "
345 " %s\n",
346 label);
347 s.PutCString("====== ====== ========== ========== ========== ========== "
348 "======================== ============================\n");
349 } else {
350 s.Printf("PID PARENT USER TRIPLE %s\n", label);
351 s.PutCString("====== ====== ========== ======================== "
352 "============================\n");
353 }
354}
355
356void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform,
357 bool show_args, bool verbose) const {
358 if (m_pid != LLDB_INVALID_PROCESS_ID) {
Greg Clayton32e0a752011-03-30 18:16:51 +0000359 const char *cstr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000361
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 StreamString arch_strm;
Todd Fiala7df337f2015-10-13 23:41:19 +0000363 if (m_arch.IsValid())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 m_arch.DumpTriple(arch_strm);
365
366 if (verbose) {
367 cstr = platform->GetUserName(m_uid);
368 if (cstr &&
369 cstr[0]) // Watch for empty string that indicates lookup failed
370 s.Printf("%-10s ", cstr);
371 else
372 s.Printf("%-10u ", m_uid);
373
374 cstr = platform->GetGroupName(m_gid);
375 if (cstr &&
376 cstr[0]) // Watch for empty string that indicates lookup failed
377 s.Printf("%-10s ", cstr);
378 else
379 s.Printf("%-10u ", m_gid);
380
381 cstr = platform->GetUserName(m_euid);
382 if (cstr &&
383 cstr[0]) // Watch for empty string that indicates lookup failed
384 s.Printf("%-10s ", cstr);
385 else
386 s.Printf("%-10u ", m_euid);
387
388 cstr = platform->GetGroupName(m_egid);
389 if (cstr &&
390 cstr[0]) // Watch for empty string that indicates lookup failed
391 s.Printf("%-10s ", cstr);
392 else
393 s.Printf("%-10u ", m_egid);
394
Zachary Turnerc1564272016-11-16 21:15:24 +0000395 s.Printf("%-24s ", arch_strm.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 } else {
397 s.Printf("%-10s %-24s ", platform->GetUserName(m_euid),
Zachary Turnerc1564272016-11-16 21:15:24 +0000398 arch_strm.GetData());
Todd Fiala7df337f2015-10-13 23:41:19 +0000399 }
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 if (verbose || show_args) {
402 const uint32_t argc = m_arguments.GetArgumentCount();
403 if (argc > 0) {
404 for (uint32_t i = 0; i < argc; i++) {
405 if (i > 0)
406 s.PutChar(' ');
407 s.PutCString(m_arguments.GetArgumentAtIndex(i));
408 }
409 }
410 } else {
411 s.PutCString(GetName());
Greg Clayton32e0a752011-03-30 18:16:51 +0000412 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413
414 s.EOL();
415 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000416}
417
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418Error ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000419 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 ExecutionContext *execution_context) {
421 Error error;
422 const int short_option = m_getopt_table[option_idx].val;
423
424 switch (short_option) {
425 case 's': // Stop at program entry point
426 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
427 break;
428
429 case 'i': // STDIN for read only
430 {
431 FileAction action;
432 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
433 launch_info.AppendFileAction(action);
434 break;
435 }
436
437 case 'o': // Open STDOUT for write only
438 {
439 FileAction action;
440 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
441 launch_info.AppendFileAction(action);
442 break;
443 }
444
445 case 'e': // STDERR for write only
446 {
447 FileAction action;
448 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
449 launch_info.AppendFileAction(action);
450 break;
451 }
452
453 case 'p': // Process plug-in name
454 launch_info.SetProcessPluginName(option_arg);
455 break;
456
457 case 'n': // Disable STDIO
458 {
459 FileAction action;
460 const FileSpec dev_null{FileSystem::DEV_NULL, false};
461 if (action.Open(STDIN_FILENO, dev_null, true, false))
462 launch_info.AppendFileAction(action);
463 if (action.Open(STDOUT_FILENO, dev_null, false, true))
464 launch_info.AppendFileAction(action);
465 if (action.Open(STDERR_FILENO, dev_null, false, true))
466 launch_info.AppendFileAction(action);
467 break;
468 }
469
470 case 'w':
471 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
472 break;
473
474 case 't': // Open process in new terminal window
475 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
476 break;
477
478 case 'a': {
479 TargetSP target_sp =
480 execution_context ? execution_context->GetTargetSP() : TargetSP();
481 PlatformSP platform_sp =
482 target_sp ? target_sp->GetPlatform() : PlatformSP();
483 if (!launch_info.GetArchitecture().SetTriple(option_arg, platform_sp.get()))
484 launch_info.GetArchitecture().SetTriple(option_arg);
485 } break;
486
487 case 'A': // Disable ASLR.
488 {
489 bool success;
490 const bool disable_aslr_arg =
Zachary Turnerfe114832016-11-12 16:56:47 +0000491 Args::StringToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 if (success)
493 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000494 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495 error.SetErrorStringWithFormat(
496 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000497 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498 break;
499 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000500
Kate Stoneb9c1b512016-09-06 20:57:50 +0000501 case 'X': // shell expand args.
502 {
503 bool success;
Zachary Turnerfe114832016-11-12 16:56:47 +0000504 const bool expand_args = Args::StringToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 if (success)
506 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000507 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 error.SetErrorStringWithFormat(
509 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000510 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511 break;
512 }
513
514 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000515 if (!option_arg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 launch_info.SetShell(FileSpec(option_arg, false));
517 else
518 launch_info.SetShell(HostInfo::GetDefaultShell());
519 break;
520
521 case 'v':
Zachary Turnerfe114832016-11-12 16:56:47 +0000522 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523 break;
524
525 default:
526 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
527 short_option);
528 break;
529 }
530 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000531}
532
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000533static OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
535 nullptr, nullptr, 0, eArgTypeNone,
536 "Stop at the entry point of the program when launching a process."},
537 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
538 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
539 "Set whether to disable address space layout randomization when launching "
540 "a process."},
541 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
542 nullptr, nullptr, 0, eArgTypePlugin,
543 "Name of the process plugin you want to use."},
544 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
545 OptionParser::eRequiredArgument, nullptr, nullptr, 0,
546 eArgTypeDirectoryName,
547 "Set the current working directory to <path> when running the inferior."},
548 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
549 nullptr, nullptr, 0, eArgTypeArchitecture,
550 "Set the architecture for the process to launch when ambiguous."},
551 {LLDB_OPT_SET_ALL, false, "environment", 'v',
552 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone,
553 "Specify an environment variable name/value string (--environment "
554 "NAME=VALUE). Can be specified multiple times for subsequent environment "
555 "entries."},
556 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
557 OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeFilename,
558 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
561 nullptr, nullptr, 0, eArgTypeFilename,
562 "Redirect stdin for the process to <filename>."},
563 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
564 nullptr, nullptr, 0, eArgTypeFilename,
565 "Redirect stdout for the process to <filename>."},
566 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
567 nullptr, nullptr, 0, eArgTypeFilename,
568 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000569
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
571 nullptr, 0, eArgTypeNone,
572 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000573
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
575 nullptr, 0, eArgTypeNone,
576 "Do not set up for terminal I/O to go to running process."},
577 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
578 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
579 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000580};
581
582llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000583 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000584}
Greg Clayton32e0a752011-03-30 18:16:51 +0000585
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
Pavel Labathc4a33952017-02-20 11:35:33 +0000587 if (m_name_match_type == NameMatch::Ignore || process_name == nullptr)
Greg Clayton32e0a752011-03-30 18:16:51 +0000588 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589 const char *match_name = m_match_info.GetName();
590 if (!match_name)
Greg Clayton32e0a752011-03-30 18:16:51 +0000591 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592
593 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
Greg Clayton32e0a752011-03-30 18:16:51 +0000594}
595
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596bool ProcessInstanceInfoMatch::Matches(
597 const ProcessInstanceInfo &proc_info) const {
598 if (!NameMatches(proc_info.GetName()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600
601 if (m_match_info.ProcessIDIsValid() &&
602 m_match_info.GetProcessID() != proc_info.GetProcessID())
603 return false;
604
605 if (m_match_info.ParentProcessIDIsValid() &&
606 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
607 return false;
608
609 if (m_match_info.UserIDIsValid() &&
610 m_match_info.GetUserID() != proc_info.GetUserID())
611 return false;
612
613 if (m_match_info.GroupIDIsValid() &&
614 m_match_info.GetGroupID() != proc_info.GetGroupID())
615 return false;
616
617 if (m_match_info.EffectiveUserIDIsValid() &&
618 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
619 return false;
620
621 if (m_match_info.EffectiveGroupIDIsValid() &&
622 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
623 return false;
624
625 if (m_match_info.GetArchitecture().IsValid() &&
626 !m_match_info.GetArchitecture().IsCompatibleMatch(
627 proc_info.GetArchitecture()))
628 return false;
629 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000630}
631
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
Pavel Labathc4a33952017-02-20 11:35:33 +0000633 if (m_name_match_type != NameMatch::Ignore)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634 return false;
635
636 if (m_match_info.ProcessIDIsValid())
637 return false;
638
639 if (m_match_info.ParentProcessIDIsValid())
640 return false;
641
642 if (m_match_info.UserIDIsValid())
643 return false;
644
645 if (m_match_info.GroupIDIsValid())
646 return false;
647
648 if (m_match_info.EffectiveUserIDIsValid())
649 return false;
650
651 if (m_match_info.EffectiveGroupIDIsValid())
652 return false;
653
654 if (m_match_info.GetArchitecture().IsValid())
655 return false;
656
657 if (m_match_all_users)
658 return false;
659
660 return true;
661}
662
663void ProcessInstanceInfoMatch::Clear() {
664 m_match_info.Clear();
Pavel Labathc4a33952017-02-20 11:35:33 +0000665 m_name_match_type = NameMatch::Ignore;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000666 m_match_all_users = false;
667}
668
Zachary Turner31659452016-11-17 21:15:14 +0000669ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
670 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671 ListenerSP listener_sp,
672 const FileSpec *crash_file_path) {
673 static uint32_t g_process_unique_id = 0;
674
675 ProcessSP process_sp;
676 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000677 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678 ConstString const_plugin_name(plugin_name);
679 create_callback =
680 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
681 if (create_callback) {
682 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
683 if (process_sp) {
684 if (process_sp->CanDebug(target_sp, true)) {
685 process_sp->m_process_unique_id = ++g_process_unique_id;
686 } else
687 process_sp.reset();
688 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000689 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690 } else {
691 for (uint32_t idx = 0;
692 (create_callback =
693 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
694 ++idx) {
695 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
696 if (process_sp) {
697 if (process_sp->CanDebug(target_sp, false)) {
698 process_sp->m_process_unique_id = ++g_process_unique_id;
699 break;
700 } else
701 process_sp.reset();
702 }
703 }
704 }
705 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000706}
707
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708ConstString &Process::GetStaticBroadcasterClass() {
709 static ConstString class_name("lldb.process");
710 return class_name;
711}
712
713Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
714 : Process(target_sp, listener_sp,
715 UnixSignals::Create(HostInfo::GetArchitecture())) {
716 // This constructor just delegates to the full Process constructor,
717 // defaulting to using the Host's UnixSignals.
718}
719
720Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
721 const UnixSignalsSP &unix_signals_sp)
722 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
723 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
724 Process::GetStaticBroadcasterClass().AsCString()),
725 m_target_sp(target_sp), m_public_state(eStateUnloaded),
726 m_private_state(eStateUnloaded),
727 m_private_state_broadcaster(nullptr,
728 "lldb.process.internal_state_broadcaster"),
729 m_private_state_control_broadcaster(
730 nullptr, "lldb.process.internal_state_control_broadcaster"),
731 m_private_state_listener_sp(
732 Listener::MakeListener("lldb.process.internal_state_listener")),
733 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
734 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
735 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
736 m_thread_list(this), m_extended_thread_list(this),
737 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
738 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
739 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
740 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
741 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
742 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
743 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
744 m_memory_cache(*this), m_allocated_memory_cache(*this),
745 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
746 m_private_run_lock(), m_stop_info_override_callback(nullptr),
747 m_finalizing(false), m_finalize_called(false),
748 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
749 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
750 m_can_interpret_function_calls(false), m_warnings_issued(),
751 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
752 CheckInWithManager();
753
754 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
755 if (log)
756 log->Printf("%p Process::Process()", static_cast<void *>(this));
757
758 if (!m_unix_signals_sp)
759 m_unix_signals_sp = std::make_shared<UnixSignals>();
760
761 SetEventName(eBroadcastBitStateChanged, "state-changed");
762 SetEventName(eBroadcastBitInterrupt, "interrupt");
763 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
764 SetEventName(eBroadcastBitSTDERR, "stderr-available");
765 SetEventName(eBroadcastBitProfileData, "profile-data-available");
766 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
767
768 m_private_state_control_broadcaster.SetEventName(
769 eBroadcastInternalStateControlStop, "control-stop");
770 m_private_state_control_broadcaster.SetEventName(
771 eBroadcastInternalStateControlPause, "control-pause");
772 m_private_state_control_broadcaster.SetEventName(
773 eBroadcastInternalStateControlResume, "control-resume");
774
775 m_listener_sp->StartListeningForEvents(
776 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
777 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
778 eBroadcastBitProfileData | eBroadcastBitStructuredData);
779
780 m_private_state_listener_sp->StartListeningForEvents(
781 &m_private_state_broadcaster,
782 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
783
784 m_private_state_listener_sp->StartListeningForEvents(
785 &m_private_state_control_broadcaster,
786 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
787 eBroadcastInternalStateControlResume);
788 // We need something valid here, even if just the default UnixSignalsSP.
789 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
790
791 // Allow the platform to override the default cache line size
792 OptionValueSP value_sp =
793 m_collection_sp
794 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
795 ->GetValue();
796 uint32_t platform_cache_line_size =
797 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
798 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
799 value_sp->SetUInt64Value(platform_cache_line_size);
800}
801
802Process::~Process() {
803 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
804 if (log)
805 log->Printf("%p Process::~Process()", static_cast<void *>(this));
806 StopPrivateStateThread();
807
808 // ThreadList::Clear() will try to acquire this process's mutex, so
809 // explicitly clear the thread list here to ensure that the mutex
810 // is not destroyed before the thread list.
811 m_thread_list.Clear();
812}
813
814const ProcessPropertiesSP &Process::GetGlobalProperties() {
815 // NOTE: intentional leak so we don't crash if global destructor chain gets
816 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000817 static ProcessPropertiesSP *g_settings_sp_ptr =
818 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000819 return *g_settings_sp_ptr;
820}
821
822void Process::Finalize() {
823 m_finalizing = true;
824
825 // Destroy this process if needed
826 switch (GetPrivateState()) {
827 case eStateConnected:
828 case eStateAttaching:
829 case eStateLaunching:
830 case eStateStopped:
831 case eStateRunning:
832 case eStateStepping:
833 case eStateCrashed:
834 case eStateSuspended:
835 Destroy(false);
836 break;
837
838 case eStateInvalid:
839 case eStateUnloaded:
840 case eStateDetached:
841 case eStateExited:
842 break;
843 }
844
845 // Clear our broadcaster before we proceed with destroying
846 Broadcaster::Clear();
847
848 // Do any cleanup needed prior to being destructed... Subclasses
849 // that override this method should call this superclass method as well.
850
851 // We need to destroy the loader before the derived Process class gets
852 // destroyed
853 // since it is very likely that undoing the loader will require access to the
854 // real process.
855 m_dynamic_checkers_ap.reset();
856 m_abi_sp.reset();
857 m_os_ap.reset();
858 m_system_runtime_ap.reset();
859 m_dyld_ap.reset();
860 m_jit_loaders_ap.reset();
861 m_thread_list_real.Destroy();
862 m_thread_list.Destroy();
863 m_extended_thread_list.Destroy();
864 m_queue_list.Clear();
865 m_queue_list_stop_id = 0;
866 std::vector<Notifications> empty_notifications;
867 m_notifications.swap(empty_notifications);
868 m_image_tokens.clear();
869 m_memory_cache.Clear();
870 m_allocated_memory_cache.Clear();
871 m_language_runtimes.clear();
872 m_instrumentation_runtimes.clear();
873 m_next_event_action_ap.reset();
874 m_stop_info_override_callback = nullptr;
875 // Clear the last natural stop ID since it has a strong
876 // reference to this process
877 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
878 //#ifdef LLDB_CONFIGURATION_DEBUG
879 // StreamFile s(stdout, false);
880 // EventSP event_sp;
881 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
882 // {
883 // event_sp->Dump (&s);
884 // s.EOL();
885 // }
886 //#endif
887 // We have to be very careful here as the m_private_state_listener might
888 // contain events that have ProcessSP values in them which can keep this
889 // process around forever. These events need to be cleared out.
890 m_private_state_listener_sp->Clear();
891 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
892 m_public_run_lock.SetStopped();
893 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
894 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000895 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 m_finalize_called = true;
897}
898
899void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
900 m_notifications.push_back(callbacks);
901 if (callbacks.initialize != nullptr)
902 callbacks.initialize(callbacks.baton, this);
903}
904
905bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
906 std::vector<Notifications>::iterator pos, end = m_notifications.end();
907 for (pos = m_notifications.begin(); pos != end; ++pos) {
908 if (pos->baton == callbacks.baton &&
909 pos->initialize == callbacks.initialize &&
910 pos->process_state_changed == callbacks.process_state_changed) {
911 m_notifications.erase(pos);
912 return true;
913 }
914 }
915 return false;
916}
917
918void Process::SynchronouslyNotifyStateChanged(StateType state) {
919 std::vector<Notifications>::iterator notification_pos,
920 notification_end = m_notifications.end();
921 for (notification_pos = m_notifications.begin();
922 notification_pos != notification_end; ++notification_pos) {
923 if (notification_pos->process_state_changed)
924 notification_pos->process_state_changed(notification_pos->baton, this,
925 state);
926 }
927}
928
929// FIXME: We need to do some work on events before the general Listener sees
930// them.
931// For instance if we are continuing from a breakpoint, we need to ensure that
932// we do
933// the little "insert real insn, step & stop" trick. But we can't do that when
934// the
935// event is delivered by the broadcaster - since that is done on the thread that
936// is
937// waiting for new events, so if we needed more than one event for our handling,
938// we would
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000939// stall. So instead we do it when we fetch the event off of the queue.
940//
941
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942StateType Process::GetNextEvent(EventSP &event_sp) {
943 StateType state = eStateInvalid;
944
Pavel Labathd35031e12016-11-30 10:41:42 +0000945 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
946 std::chrono::seconds(0)) &&
947 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
949
950 return state;
951}
952
953void Process::SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec) {
954 // don't sync (potentially context switch) in case where there is no process
955 // IO
956 if (!m_process_input_reader)
957 return;
958
959 uint32_t new_iohandler_id = 0;
960 m_iohandler_sync.WaitForValueNotEqualTo(
961 iohandler_id, new_iohandler_id, std::chrono::milliseconds(timeout_msec));
962
963 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
964 if (log)
965 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, "
966 "new value is %u",
967 __FUNCTION__, iohandler_id, new_iohandler_id);
968}
969
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000970StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
971 EventSP *event_sp_ptr, bool wait_always,
972 ListenerSP hijack_listener_sp,
973 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 // We can't just wait for a "stopped" event, because the stopped event may
975 // have restarted the target.
976 // We have to actually check each event, and in the case of a stopped event
977 // check the restarted flag
978 // on the event.
979 if (event_sp_ptr)
980 event_sp_ptr->reset();
981 StateType state = GetState();
982 // If we are exited or detached, we won't ever get back to any
983 // other valid state...
984 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000985 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000986
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000988 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000989
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 if (!wait_always && StateIsStoppedState(state, true) &&
991 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000992 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 log->Printf("Process::%s returning without waiting for events; process "
994 "private and public states are already 'stopped'.",
995 __FUNCTION__);
996 // We need to toggle the run lock as this won't get done in
997 // SetPublicState() if the process is hijacked.
998 if (hijack_listener_sp && use_run_lock)
999 m_public_run_lock.SetStopped();
1000 return state;
1001 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 while (state != eStateInvalid) {
1004 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001005 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 if (event_sp_ptr && event_sp)
1007 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001008
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1010 Process::HandleProcessStateChangedEvent(event_sp, stream,
1011 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +00001012
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013 switch (state) {
1014 case eStateCrashed:
1015 case eStateDetached:
1016 case eStateExited:
1017 case eStateUnloaded:
1018 // We need to toggle the run lock as this won't get done in
1019 // SetPublicState() if the process is hijacked.
1020 if (hijack_listener_sp && use_run_lock)
1021 m_public_run_lock.SetStopped();
1022 return state;
1023 case eStateStopped:
1024 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1025 continue;
1026 else {
Pavel Labath78521ef2015-03-06 10:52:47 +00001027 // We need to toggle the run lock as this won't get done in
1028 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001029 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 m_public_run_lock.SetStopped();
1031 return state;
1032 }
1033 default:
1034 continue;
1035 }
1036 }
1037 return state;
1038}
1039
1040bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1041 Stream *stream,
1042 bool &pop_process_io_handler) {
1043 const bool handle_pop = pop_process_io_handler;
1044
1045 pop_process_io_handler = false;
1046 ProcessSP process_sp =
1047 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1048
1049 if (!process_sp)
1050 return false;
1051
1052 StateType event_state =
1053 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1054 if (event_state == eStateInvalid)
1055 return false;
1056
1057 switch (event_state) {
1058 case eStateInvalid:
1059 case eStateUnloaded:
1060 case eStateAttaching:
1061 case eStateLaunching:
1062 case eStateStepping:
1063 case eStateDetached:
1064 if (stream)
1065 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1066 StateAsCString(event_state));
1067 if (event_state == eStateDetached)
1068 pop_process_io_handler = true;
1069 break;
1070
1071 case eStateConnected:
1072 case eStateRunning:
1073 // Don't be chatty when we run...
1074 break;
1075
1076 case eStateExited:
1077 if (stream)
1078 process_sp->GetStatus(*stream);
1079 pop_process_io_handler = true;
1080 break;
1081
1082 case eStateStopped:
1083 case eStateCrashed:
1084 case eStateSuspended:
1085 // Make sure the program hasn't been auto-restarted:
1086 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1087 if (stream) {
1088 size_t num_reasons =
1089 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1090 if (num_reasons > 0) {
1091 // FIXME: Do we want to report this, or would that just be annoyingly
1092 // chatty?
1093 if (num_reasons == 1) {
1094 const char *reason =
1095 Process::ProcessEventData::GetRestartedReasonAtIndex(
1096 event_sp.get(), 0);
1097 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1098 process_sp->GetID(),
1099 reason ? reason : "<UNKNOWN REASON>");
1100 } else {
1101 stream->Printf("Process %" PRIu64
1102 " stopped and restarted, reasons:\n",
1103 process_sp->GetID());
1104
1105 for (size_t i = 0; i < num_reasons; i++) {
1106 const char *reason =
1107 Process::ProcessEventData::GetRestartedReasonAtIndex(
1108 event_sp.get(), i);
1109 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1110 }
1111 }
1112 }
1113 }
1114 } else {
1115 StopInfoSP curr_thread_stop_info_sp;
1116 // Lock the thread list so it doesn't change on us, this is the scope for
1117 // the locker:
1118 {
1119 ThreadList &thread_list = process_sp->GetThreadList();
1120 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1121
1122 ThreadSP curr_thread(thread_list.GetSelectedThread());
1123 ThreadSP thread;
1124 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1125 if (curr_thread) {
1126 curr_thread_stop_reason = curr_thread->GetStopReason();
1127 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1128 }
1129 if (!curr_thread || !curr_thread->IsValid() ||
1130 curr_thread_stop_reason == eStopReasonInvalid ||
1131 curr_thread_stop_reason == eStopReasonNone) {
1132 // Prefer a thread that has just completed its plan over another
1133 // thread as current thread.
1134 ThreadSP plan_thread;
1135 ThreadSP other_thread;
1136
1137 const size_t num_threads = thread_list.GetSize();
1138 size_t i;
1139 for (i = 0; i < num_threads; ++i) {
1140 thread = thread_list.GetThreadAtIndex(i);
1141 StopReason thread_stop_reason = thread->GetStopReason();
1142 switch (thread_stop_reason) {
1143 case eStopReasonInvalid:
1144 case eStopReasonNone:
1145 break;
1146
1147 case eStopReasonSignal: {
1148 // Don't select a signal thread if we weren't going to stop at
1149 // that
1150 // signal. We have to have had another reason for stopping here,
1151 // and
1152 // the user doesn't want to see this thread.
1153 uint64_t signo = thread->GetStopInfo()->GetValue();
1154 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1155 if (!other_thread)
1156 other_thread = thread;
1157 }
1158 break;
1159 }
1160 case eStopReasonTrace:
1161 case eStopReasonBreakpoint:
1162 case eStopReasonWatchpoint:
1163 case eStopReasonException:
1164 case eStopReasonExec:
1165 case eStopReasonThreadExiting:
1166 case eStopReasonInstrumentation:
1167 if (!other_thread)
1168 other_thread = thread;
1169 break;
1170 case eStopReasonPlanComplete:
1171 if (!plan_thread)
1172 plan_thread = thread;
1173 break;
1174 }
1175 }
1176 if (plan_thread)
1177 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1178 else if (other_thread)
1179 thread_list.SetSelectedThreadByID(other_thread->GetID());
1180 else {
1181 if (curr_thread && curr_thread->IsValid())
1182 thread = curr_thread;
1183 else
1184 thread = thread_list.GetThreadAtIndex(0);
1185
1186 if (thread)
1187 thread_list.SetSelectedThreadByID(thread->GetID());
1188 }
1189 }
1190 }
1191 // Drop the ThreadList mutex by here, since GetThreadStatus below might
1192 // have to run code,
1193 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the
1194 // process is going to
1195 // have a hard time restarting the process.
1196 if (stream) {
1197 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1198 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1199 &process_sp->GetTarget()) {
1200 const bool only_threads_with_stop_reason = true;
1201 const uint32_t start_frame = 0;
1202 const uint32_t num_frames = 1;
1203 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001204 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 process_sp->GetStatus(*stream);
1206 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1207 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001208 num_frames_with_source,
1209 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 if (curr_thread_stop_info_sp) {
1211 lldb::addr_t crashing_address;
1212 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1213 curr_thread_stop_info_sp, &crashing_address);
1214 if (valobj_sp) {
1215 const bool qualify_cxx_base_classes = false;
1216
1217 const ValueObject::GetExpressionPathFormat format =
1218 ValueObject::GetExpressionPathFormat::
1219 eGetExpressionPathFormatHonorPointers;
1220 stream->PutCString("Likely cause: ");
1221 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1222 format);
1223 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1224 }
1225 }
1226 } else {
1227 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1228 process_sp->GetTarget().shared_from_this());
1229 if (target_idx != UINT32_MAX)
1230 stream->Printf("Target %d: (", target_idx);
1231 else
1232 stream->Printf("Target <unknown index>: (");
1233 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1234 stream->Printf(") stopped.\n");
1235 }
1236 }
1237
1238 // Pop the process IO handler
1239 pop_process_io_handler = true;
1240 }
1241 break;
1242 }
1243
1244 if (handle_pop && pop_process_io_handler)
1245 process_sp->PopProcessIOHandler();
1246
1247 return true;
1248}
1249
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1251 if (listener_sp) {
1252 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1253 eBroadcastBitInterrupt);
1254 } else
1255 return false;
1256}
Greg Claytondc6224e2014-10-21 01:00:42 +00001257
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001259
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001260StateType Process::GetStateChangedEvents(EventSP &event_sp,
1261 const Timeout<std::micro> &timeout,
1262 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001264 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001265
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 ListenerSP listener_sp = hijack_listener_sp;
1267 if (!listener_sp)
1268 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001269
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001271 if (listener_sp->GetEventForBroadcasterWithType(
1272 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001273 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1275 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001276 else
1277 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001279
Pavel Labathd02b1c82017-02-10 11:49:33 +00001280 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001281 return state;
1282}
Greg Claytondc6224e2014-10-21 01:00:42 +00001283
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284Event *Process::PeekAtStateChangedEvents() {
1285 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001286
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 if (log)
1288 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001289
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 Event *event_ptr;
1291 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1292 this, eBroadcastBitStateChanged);
1293 if (log) {
1294 if (event_ptr) {
1295 log->Printf(
1296 "Process::%s (event_ptr) => %s", __FUNCTION__,
1297 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1298 } else {
1299 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001300 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301 }
1302 return event_ptr;
1303}
Greg Claytondc6224e2014-10-21 01:00:42 +00001304
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001305StateType
1306Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1307 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001308 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001309 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001310
1311 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001312 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1313 &m_private_state_broadcaster,
1314 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001315 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1317 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1318
Pavel Labathd02b1c82017-02-10 11:49:33 +00001319 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1320 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001321 return state;
1322}
1323
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001324bool Process::GetEventsPrivate(EventSP &event_sp,
1325 const Timeout<std::micro> &timeout,
1326 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001327 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001328 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001329
1330 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001331 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001332 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001334 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335}
1336
1337bool Process::IsRunning() const {
1338 return StateIsRunningState(m_public_state.GetValue());
1339}
1340
1341int Process::GetExitStatus() {
1342 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1343
1344 if (m_public_state.GetValue() == eStateExited)
1345 return m_exit_status;
1346 return -1;
1347}
1348
1349const char *Process::GetExitDescription() {
1350 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1351
1352 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1353 return m_exit_string.c_str();
1354 return nullptr;
1355}
1356
1357bool Process::SetExitStatus(int status, const char *cstr) {
1358 // Use a mutex to protect setting the exit status.
1359 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1360
1361 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1362 LIBLLDB_LOG_PROCESS));
1363 if (log)
1364 log->Printf(
1365 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1366 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1367 cstr ? "\"" : "");
1368
1369 // We were already in the exited state
1370 if (m_private_state.GetValue() == eStateExited) {
1371 if (log)
1372 log->Printf("Process::SetExitStatus () ignoring exit status because "
1373 "state was already set to eStateExited");
1374 return false;
1375 }
1376
1377 m_exit_status = status;
1378 if (cstr)
1379 m_exit_string = cstr;
1380 else
1381 m_exit_string.clear();
1382
1383 // Clear the last natural stop ID since it has a strong
1384 // reference to this process
1385 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1386
1387 SetPrivateState(eStateExited);
1388
1389 // Allow subclasses to do some cleanup
1390 DidExit();
1391
1392 return true;
1393}
1394
1395bool Process::IsAlive() {
1396 switch (m_private_state.GetValue()) {
1397 case eStateConnected:
1398 case eStateAttaching:
1399 case eStateLaunching:
1400 case eStateStopped:
1401 case eStateRunning:
1402 case eStateStepping:
1403 case eStateCrashed:
1404 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001405 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 default:
1407 return false;
1408 }
Jason Molendaa814f702015-11-05 23:03:44 +00001409}
1410
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001411// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001412// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001413// found in the global target list (we want to be completely sure that the
1414// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001415bool Process::SetProcessExitStatus(
1416 lldb::pid_t pid, bool exited,
1417 int signo, // Zero for no signal
1418 int exit_status // Exit value of process if signal is zero
1419 ) {
1420 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1421 if (log)
1422 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1423 ", exited=%i, signal=%i, exit_status=%i)\n",
1424 pid, exited, signo, exit_status);
1425
1426 if (exited) {
1427 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1428 if (target_sp) {
1429 ProcessSP process_sp(target_sp->GetProcessSP());
1430 if (process_sp) {
1431 const char *signal_cstr = nullptr;
1432 if (signo)
1433 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1434
1435 process_sp->SetExitStatus(exit_status, signal_cstr);
1436 }
1437 }
1438 return true;
1439 }
1440 return false;
1441}
1442
1443void Process::UpdateThreadListIfNeeded() {
1444 const uint32_t stop_id = GetStopID();
1445 if (m_thread_list.GetSize(false) == 0 ||
1446 stop_id != m_thread_list.GetStopID()) {
1447 const StateType state = GetPrivateState();
1448 if (StateIsStoppedState(state, true)) {
1449 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1450 // m_thread_list does have its own mutex, but we need to
1451 // hold onto the mutex between the call to UpdateThreadList(...)
1452 // and the os->UpdateThreadList(...) so it doesn't change on us
1453 ThreadList &old_thread_list = m_thread_list;
1454 ThreadList real_thread_list(this);
1455 ThreadList new_thread_list(this);
1456 // Always update the thread list with the protocol specific
1457 // thread list, but only update if "true" is returned
1458 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1459 // Don't call into the OperatingSystem to update the thread list if we
1460 // are shutting down, since
1461 // that may call back into the SBAPI's, requiring the API lock which is
1462 // already held by whoever is
1463 // shutting us down, causing a deadlock.
1464 OperatingSystem *os = GetOperatingSystem();
1465 if (os && !m_destroy_in_process) {
1466 // Clear any old backing threads where memory threads might have been
1467 // backed by actual threads from the lldb_private::Process subclass
1468 size_t num_old_threads = old_thread_list.GetSize(false);
1469 for (size_t i = 0; i < num_old_threads; ++i)
1470 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1471
1472 // Turn off dynamic types to ensure we don't run any expressions.
1473 // Objective C
1474 // can run an expression to determine if a SBValue is a dynamic type
1475 // or not
1476 // and we need to avoid this. OperatingSystem plug-ins can't run
1477 // expressions
1478 // that require running code...
1479
1480 Target &target = GetTarget();
1481 const lldb::DynamicValueType saved_prefer_dynamic =
1482 target.GetPreferDynamicValue();
1483 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1484 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1485
1486 // Now let the OperatingSystem plug-in update the thread list
1487
1488 os->UpdateThreadList(
1489 old_thread_list, // Old list full of threads created by OS plug-in
1490 real_thread_list, // The actual thread list full of threads
1491 // created by each lldb_private::Process
1492 // subclass
1493 new_thread_list); // The new thread list that we will show to the
1494 // user that gets filled in
1495
1496 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1497 target.SetPreferDynamicValue(saved_prefer_dynamic);
1498 } else {
1499 // No OS plug-in, the new thread list is the same as the real thread
1500 // list
1501 new_thread_list = real_thread_list;
1502 }
1503
1504 m_thread_list_real.Update(real_thread_list);
1505 m_thread_list.Update(new_thread_list);
1506 m_thread_list.SetStopID(stop_id);
1507
1508 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1509 // Clear any extended threads that we may have accumulated previously
1510 m_extended_thread_list.Clear();
1511 m_extended_thread_stop_id = GetLastNaturalStopID();
1512
1513 m_queue_list.Clear();
1514 m_queue_list_stop_id = GetLastNaturalStopID();
1515 }
1516 }
1517 }
1518 }
1519}
1520
1521void Process::UpdateQueueListIfNeeded() {
1522 if (m_system_runtime_ap) {
1523 if (m_queue_list.GetSize() == 0 ||
1524 m_queue_list_stop_id != GetLastNaturalStopID()) {
1525 const StateType state = GetPrivateState();
1526 if (StateIsStoppedState(state, true)) {
1527 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1528 m_queue_list_stop_id = GetLastNaturalStopID();
1529 }
1530 }
1531 }
1532}
1533
1534ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1535 OperatingSystem *os = GetOperatingSystem();
1536 if (os)
1537 return os->CreateThread(tid, context);
1538 return ThreadSP();
1539}
1540
1541uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1542 return AssignIndexIDToThread(thread_id);
1543}
1544
1545bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1546 return (m_thread_id_to_index_id_map.find(thread_id) !=
1547 m_thread_id_to_index_id_map.end());
1548}
1549
1550uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1551 uint32_t result = 0;
1552 std::map<uint64_t, uint32_t>::iterator iterator =
1553 m_thread_id_to_index_id_map.find(thread_id);
1554 if (iterator == m_thread_id_to_index_id_map.end()) {
1555 result = ++m_thread_index_id;
1556 m_thread_id_to_index_id_map[thread_id] = result;
1557 } else {
1558 result = iterator->second;
1559 }
1560
1561 return result;
1562}
1563
1564StateType Process::GetState() {
1565 // If any other threads access this we will need a mutex for it
1566 return m_public_state.GetValue();
1567}
1568
1569bool Process::StateChangedIsExternallyHijacked() {
1570 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1571 const char *hijacking_name = GetHijackingListenerName();
1572 if (hijacking_name &&
1573 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1574 return true;
1575 }
1576 return false;
1577}
1578
1579void Process::SetPublicState(StateType new_state, bool restarted) {
1580 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1581 LIBLLDB_LOG_PROCESS));
1582 if (log)
1583 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1584 StateAsCString(new_state), restarted);
1585 const StateType old_state = m_public_state.GetValue();
1586 m_public_state.SetValue(new_state);
1587
1588 // On the transition from Run to Stopped, we unlock the writer end of the
1589 // run lock. The lock gets locked in Resume, which is the public API
1590 // to tell the program to run.
1591 if (!StateChangedIsExternallyHijacked()) {
1592 if (new_state == eStateDetached) {
1593 if (log)
1594 log->Printf(
1595 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1596 StateAsCString(new_state));
1597 m_public_run_lock.SetStopped();
1598 } else {
1599 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1600 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1601 if ((old_state_is_stopped != new_state_is_stopped)) {
1602 if (new_state_is_stopped && !restarted) {
1603 if (log)
1604 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1605 StateAsCString(new_state));
1606 m_public_run_lock.SetStopped();
1607 }
1608 }
1609 }
1610 }
1611}
1612
1613Error Process::Resume() {
1614 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1615 LIBLLDB_LOG_PROCESS));
1616 if (log)
1617 log->Printf("Process::Resume -- locking run lock");
1618 if (!m_public_run_lock.TrySetRunning()) {
1619 Error error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001620 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001621 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001622 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001623 }
1624 return PrivateResume();
Greg Claytondc6224e2014-10-21 01:00:42 +00001625}
1626
Kate Stoneb9c1b512016-09-06 20:57:50 +00001627Error Process::ResumeSynchronous(Stream *stream) {
1628 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1629 LIBLLDB_LOG_PROCESS));
1630 if (log)
1631 log->Printf("Process::ResumeSynchronous -- locking run lock");
1632 if (!m_public_run_lock.TrySetRunning()) {
1633 Error error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001634 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001635 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1636 return error;
1637 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001638
Kate Stoneb9c1b512016-09-06 20:57:50 +00001639 ListenerSP listener_sp(
1640 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1641 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001642
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643 Error error = PrivateResume();
1644 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001645 StateType state =
1646 WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001647 const bool must_be_alive =
1648 false; // eStateExited is ok, so this must be false
1649 if (!StateIsStoppedState(state, must_be_alive))
1650 error.SetErrorStringWithFormat(
1651 "process not in stopped state after synchronous resume: %s",
1652 StateAsCString(state));
1653 }
Ed Mastec29693f2013-07-02 16:35:47 +00001654
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655 // Undo the hijacking of process events...
1656 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001657
Kate Stoneb9c1b512016-09-06 20:57:50 +00001658 return error;
1659}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001660
Kate Stoneb9c1b512016-09-06 20:57:50 +00001661StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001662
Kate Stoneb9c1b512016-09-06 20:57:50 +00001663void Process::SetPrivateState(StateType new_state) {
1664 if (m_finalize_called)
1665 return;
1666
1667 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1668 LIBLLDB_LOG_PROCESS));
1669 bool state_changed = false;
1670
1671 if (log)
1672 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1673
1674 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1675 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1676
1677 const StateType old_state = m_private_state.GetValueNoLock();
1678 state_changed = old_state != new_state;
1679
1680 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1681 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1682 if (old_state_is_stopped != new_state_is_stopped) {
1683 if (new_state_is_stopped)
1684 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001685 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001686 m_private_run_lock.SetRunning();
1687 }
1688
1689 if (state_changed) {
1690 m_private_state.SetValueNoLock(new_state);
1691 EventSP event_sp(
1692 new Event(eBroadcastBitStateChanged,
1693 new ProcessEventData(shared_from_this(), new_state)));
1694 if (StateIsStoppedState(new_state, false)) {
1695 // Note, this currently assumes that all threads in the list
1696 // stop when the process stops. In the future we will want to
1697 // support a debugging model where some threads continue to run
1698 // while others are stopped. When that happens we will either need
1699 // a way for the thread list to identify which threads are stopping
1700 // or create a special thread list containing only threads which
1701 // actually stopped.
1702 //
1703 // The process plugin is responsible for managing the actual
1704 // behavior of the threads and should have stopped any threads
1705 // that are going to stop before we get here.
1706 m_thread_list.DidStop();
1707
1708 m_mod_id.BumpStopID();
1709 if (!m_mod_id.IsLastResumeForUserExpression())
1710 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1711 m_memory_cache.Clear();
1712 if (log)
1713 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1714 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001715 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001716
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717 // Use our target to get a shared pointer to ourselves...
1718 if (m_finalize_called && !PrivateStateThreadIsValid())
1719 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001720 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001721 m_private_state_broadcaster.BroadcastEvent(event_sp);
1722 } else {
1723 if (log)
1724 log->Printf(
1725 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1726 StateAsCString(new_state));
1727 }
Jim Ingham22777012010-09-23 02:01:19 +00001728}
1729
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730void Process::SetRunningUserExpression(bool on) {
1731 m_mod_id.SetRunningUserExpression(on);
1732}
1733
1734addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1735
1736const lldb::ABISP &Process::GetABI() {
1737 if (!m_abi_sp)
1738 m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture());
1739 return m_abi_sp;
1740}
1741
1742LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1743 bool retry_if_null) {
1744 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001745 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001746
1747 LanguageRuntimeCollection::iterator pos;
1748 pos = m_language_runtimes.find(language);
1749 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1750 lldb::LanguageRuntimeSP runtime_sp(
1751 LanguageRuntime::FindPlugin(this, language));
1752
1753 m_language_runtimes[language] = runtime_sp;
1754 return runtime_sp.get();
1755 } else
1756 return (*pos).second.get();
Jim Ingham22777012010-09-23 02:01:19 +00001757}
1758
Kate Stoneb9c1b512016-09-06 20:57:50 +00001759CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1760 LanguageRuntime *runtime =
1761 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1762 if (runtime != nullptr &&
1763 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1764 return static_cast<CPPLanguageRuntime *>(runtime);
1765 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001766}
1767
Kate Stoneb9c1b512016-09-06 20:57:50 +00001768ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1769 LanguageRuntime *runtime =
1770 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1771 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1772 return static_cast<ObjCLanguageRuntime *>(runtime);
1773 return nullptr;
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001774}
1775
Kate Stoneb9c1b512016-09-06 20:57:50 +00001776bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1777 if (m_finalizing)
1778 return false;
1779
1780 if (in_value.IsDynamic())
1781 return false;
1782 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1783
1784 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1785 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1786 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1787 }
1788
1789 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1790 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1791 return true;
1792
1793 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1794 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001795}
1796
Kate Stoneb9c1b512016-09-06 20:57:50 +00001797void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1798 m_dynamic_checkers_ap.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001799}
1800
Kate Stoneb9c1b512016-09-06 20:57:50 +00001801BreakpointSiteList &Process::GetBreakpointSiteList() {
1802 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803}
1804
Kate Stoneb9c1b512016-09-06 20:57:50 +00001805const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1806 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001807}
1808
Kate Stoneb9c1b512016-09-06 20:57:50 +00001809void Process::DisableAllBreakpointSites() {
1810 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1811 // bp_site->SetEnabled(true);
1812 DisableBreakpointSite(bp_site);
1813 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001814}
1815
Kate Stoneb9c1b512016-09-06 20:57:50 +00001816Error Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1817 Error error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001818
Kate Stoneb9c1b512016-09-06 20:57:50 +00001819 if (error.Success())
1820 m_breakpoint_site_list.Remove(break_id);
1821
1822 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001823}
1824
Kate Stoneb9c1b512016-09-06 20:57:50 +00001825Error Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1826 Error error;
1827 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1828 if (bp_site_sp) {
1829 if (bp_site_sp->IsEnabled())
1830 error = DisableBreakpointSite(bp_site_sp.get());
1831 } else {
1832 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1833 break_id);
1834 }
1835
1836 return error;
1837}
1838
1839Error Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1840 Error error;
1841 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1842 if (bp_site_sp) {
1843 if (!bp_site_sp->IsEnabled())
1844 error = EnableBreakpointSite(bp_site_sp.get());
1845 } else {
1846 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1847 break_id);
1848 }
1849 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001850}
1851
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001852lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001853Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1854 bool use_hardware) {
1855 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001856
Kate Stoneb9c1b512016-09-06 20:57:50 +00001857 bool show_error = true;
1858 switch (GetState()) {
1859 case eStateInvalid:
1860 case eStateUnloaded:
1861 case eStateConnected:
1862 case eStateAttaching:
1863 case eStateLaunching:
1864 case eStateDetached:
1865 case eStateExited:
1866 show_error = false;
1867 break;
1868
1869 case eStateStopped:
1870 case eStateRunning:
1871 case eStateStepping:
1872 case eStateCrashed:
1873 case eStateSuspended:
1874 show_error = IsAlive();
1875 break;
1876 }
1877
1878 // Reset the IsIndirect flag here, in case the location changes from
1879 // pointing to a indirect symbol to a regular symbol.
1880 owner->SetIsIndirect(false);
1881
1882 if (owner->ShouldResolveIndirectFunctions()) {
1883 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1884 if (symbol && symbol->IsIndirect()) {
1885 Error error;
1886 Address symbol_address = symbol->GetAddress();
1887 load_addr = ResolveIndirectFunction(&symbol_address, error);
1888 if (!error.Success() && show_error) {
1889 GetTarget().GetDebugger().GetErrorFile()->Printf(
1890 "warning: failed to resolve indirect function at 0x%" PRIx64
1891 " for breakpoint %i.%i: %s\n",
1892 symbol->GetLoadAddress(&GetTarget()),
1893 owner->GetBreakpoint().GetID(), owner->GetID(),
1894 error.AsCString() ? error.AsCString() : "unknown error");
1895 return LLDB_INVALID_BREAK_ID;
1896 }
1897 Address resolved_address(load_addr);
1898 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1899 owner->SetIsIndirect(true);
1900 } else
1901 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1902 } else
1903 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1904
1905 if (load_addr != LLDB_INVALID_ADDRESS) {
1906 BreakpointSiteSP bp_site_sp;
1907
1908 // Look up this breakpoint site. If it exists, then add this new owner,
1909 // otherwise
1910 // create a new breakpoint site and add it.
1911
1912 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1913
1914 if (bp_site_sp) {
1915 bp_site_sp->AddOwner(owner);
1916 owner->SetBreakpointSite(bp_site_sp);
1917 return bp_site_sp->GetID();
1918 } else {
1919 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1920 load_addr, use_hardware));
1921 if (bp_site_sp) {
1922 Error error = EnableBreakpointSite(bp_site_sp.get());
1923 if (error.Success()) {
1924 owner->SetBreakpointSite(bp_site_sp);
1925 return m_breakpoint_site_list.Add(bp_site_sp);
1926 } else {
1927 if (show_error) {
1928 // Report error for setting breakpoint...
1929 GetTarget().GetDebugger().GetErrorFile()->Printf(
1930 "warning: failed to set breakpoint site at 0x%" PRIx64
1931 " for breakpoint %i.%i: %s\n",
1932 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1933 error.AsCString() ? error.AsCString() : "unknown error");
1934 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001935 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001936 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001937 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001938 }
1939 // We failed to enable the breakpoint
1940 return LLDB_INVALID_BREAK_ID;
1941}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001942
Kate Stoneb9c1b512016-09-06 20:57:50 +00001943void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1944 lldb::user_id_t owner_loc_id,
1945 BreakpointSiteSP &bp_site_sp) {
1946 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1947 if (num_owners == 0) {
1948 // Don't try to disable the site if we don't have a live process anymore.
1949 if (IsAlive())
1950 DisableBreakpointSite(bp_site_sp.get());
1951 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1952 }
1953}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001954
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1956 uint8_t *buf) const {
1957 size_t bytes_removed = 0;
1958 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001959
Kate Stoneb9c1b512016-09-06 20:57:50 +00001960 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1961 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001962 bp_sites_in_range.ForEach([bp_addr, size,
1963 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001964 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1965 addr_t intersect_addr;
1966 size_t intersect_size;
1967 size_t opcode_offset;
1968 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1969 &intersect_size, &opcode_offset)) {
1970 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1971 assert(bp_addr < intersect_addr + intersect_size &&
1972 intersect_addr + intersect_size <= bp_addr + size);
1973 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1974 size_t buf_offset = intersect_addr - bp_addr;
1975 ::memcpy(buf + buf_offset,
1976 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1977 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001978 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001979 }
1980 });
1981 }
1982 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001983}
1984
Kate Stoneb9c1b512016-09-06 20:57:50 +00001985size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1986 PlatformSP platform_sp(GetTarget().GetPlatform());
1987 if (platform_sp)
1988 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1989 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001990}
1991
Kate Stoneb9c1b512016-09-06 20:57:50 +00001992Error Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1993 Error error;
1994 assert(bp_site != nullptr);
1995 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1996 const addr_t bp_addr = bp_site->GetLoadAddress();
1997 if (log)
1998 log->Printf(
1999 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
2000 bp_site->GetID(), (uint64_t)bp_addr);
2001 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002002 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002003 log->Printf(
2004 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2005 " -- already enabled",
2006 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002007 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002008 }
2009
2010 if (bp_addr == LLDB_INVALID_ADDRESS) {
2011 error.SetErrorString("BreakpointSite contains an invalid load address.");
2012 return error;
2013 }
2014 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2015 // trap for the breakpoint site
2016 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2017
2018 if (bp_opcode_size == 0) {
2019 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2020 "returned zero, unable to get breakpoint "
2021 "trap for address 0x%" PRIx64,
2022 bp_addr);
2023 } else {
2024 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2025
2026 if (bp_opcode_bytes == nullptr) {
2027 error.SetErrorString(
2028 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2029 return error;
2030 }
2031
2032 // Save the original opcode by reading it
2033 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2034 error) == bp_opcode_size) {
2035 // Write a software breakpoint in place of the original opcode
2036 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2037 bp_opcode_size) {
2038 uint8_t verify_bp_opcode_bytes[64];
2039 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2040 error) == bp_opcode_size) {
2041 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2042 bp_opcode_size) == 0) {
2043 bp_site->SetEnabled(true);
2044 bp_site->SetType(BreakpointSite::eSoftware);
2045 if (log)
2046 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2047 "addr = 0x%" PRIx64 " -- SUCCESS",
2048 bp_site->GetID(), (uint64_t)bp_addr);
2049 } else
2050 error.SetErrorString(
2051 "failed to verify the breakpoint trap in memory.");
2052 } else
2053 error.SetErrorString(
2054 "Unable to read memory to verify breakpoint trap.");
2055 } else
2056 error.SetErrorString("Unable to write breakpoint trap to memory.");
2057 } else
2058 error.SetErrorString("Unable to read memory at breakpoint address.");
2059 }
2060 if (log && error.Fail())
2061 log->Printf(
2062 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2063 " -- FAILED: %s",
2064 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2065 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066}
2067
Kate Stoneb9c1b512016-09-06 20:57:50 +00002068Error Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2069 Error error;
2070 assert(bp_site != nullptr);
2071 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2072 addr_t bp_addr = bp_site->GetLoadAddress();
2073 lldb::user_id_t breakID = bp_site->GetID();
2074 if (log)
2075 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2076 ") addr = 0x%" PRIx64,
2077 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002078
Kate Stoneb9c1b512016-09-06 20:57:50 +00002079 if (bp_site->IsHardware()) {
2080 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2081 } else if (bp_site->IsEnabled()) {
2082 const size_t break_op_size = bp_site->GetByteSize();
2083 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2084 if (break_op_size > 0) {
2085 // Clear a software breakpoint instruction
2086 uint8_t curr_break_op[8];
2087 assert(break_op_size <= sizeof(curr_break_op));
2088 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002089
Kate Stoneb9c1b512016-09-06 20:57:50 +00002090 // Read the breakpoint opcode
2091 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2092 break_op_size) {
2093 bool verify = false;
2094 // Make sure the breakpoint opcode exists at this address
2095 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2096 break_op_found = true;
2097 // We found a valid breakpoint opcode at this address, now restore
2098 // the saved opcode.
2099 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2100 break_op_size, error) == break_op_size) {
2101 verify = true;
2102 } else
2103 error.SetErrorString(
2104 "Memory write failed when restoring original opcode.");
2105 } else {
2106 error.SetErrorString(
2107 "Original breakpoint trap is no longer in memory.");
2108 // Set verify to true and so we can check if the original opcode has
2109 // already been restored
2110 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002112
Kate Stoneb9c1b512016-09-06 20:57:50 +00002113 if (verify) {
2114 uint8_t verify_opcode[8];
2115 assert(break_op_size < sizeof(verify_opcode));
2116 // Verify that our original opcode made it back to the inferior
2117 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2118 break_op_size) {
2119 // compare the memory we just read with the original opcode
2120 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2121 break_op_size) == 0) {
2122 // SUCCESS
2123 bp_site->SetEnabled(false);
2124 if (log)
2125 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2126 "addr = 0x%" PRIx64 " -- SUCCESS",
2127 bp_site->GetID(), (uint64_t)bp_addr);
2128 return error;
2129 } else {
2130 if (break_op_found)
2131 error.SetErrorString("Failed to restore original opcode.");
2132 }
2133 } else
2134 error.SetErrorString("Failed to read memory to verify that "
2135 "breakpoint trap was restored.");
2136 }
2137 } else
2138 error.SetErrorString(
2139 "Unable to read memory that should contain the breakpoint trap.");
2140 }
2141 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002142 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143 log->Printf(
2144 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2145 " -- already disabled",
2146 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002147 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002148 }
2149
2150 if (log)
2151 log->Printf(
2152 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2153 " -- FAILED: %s",
2154 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2155 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002156}
2157
Greg Clayton58be07b2011-01-07 06:08:19 +00002158// Uncomment to verify memory caching works after making changes to caching code
2159//#define VERIFY_MEMORY_READS
2160
Kate Stoneb9c1b512016-09-06 20:57:50 +00002161size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Error &error) {
2162 error.Clear();
2163 if (!GetDisableMemoryCache()) {
2164#if defined(VERIFY_MEMORY_READS)
2165 // Memory caching is enabled, with debug verification
2166
2167 if (buf && size) {
2168 // Uncomment the line below to make sure memory caching is working.
2169 // I ran this through the test suite and got no assertions, so I am
2170 // pretty confident this is working well. If any changes are made to
2171 // memory caching, uncomment the line below and test your changes!
2172
2173 // Verify all memory reads by using the cache first, then redundantly
2174 // reading the same memory from the inferior and comparing to make sure
2175 // everything is exactly the same.
2176 std::string verify_buf(size, '\0');
2177 assert(verify_buf.size() == size);
2178 const size_t cache_bytes_read =
2179 m_memory_cache.Read(this, addr, buf, size, error);
2180 Error verify_error;
2181 const size_t verify_bytes_read =
2182 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2183 verify_buf.size(), verify_error);
2184 assert(cache_bytes_read == verify_bytes_read);
2185 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2186 assert(verify_error.Success() == error.Success());
2187 return cache_bytes_read;
2188 }
2189 return 0;
2190#else // !defined(VERIFY_MEMORY_READS)
2191 // Memory caching is enabled, without debug verification
2192
2193 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002194#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002195 } else {
2196 // Memory caching is disabled
2197
2198 return ReadMemoryFromInferior(addr, buf, size, error);
2199 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002200}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002201
2202size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2203 Error &error) {
2204 char buf[256];
2205 out_str.clear();
2206 addr_t curr_addr = addr;
2207 while (true) {
2208 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2209 if (length == 0)
2210 break;
2211 out_str.append(buf, length);
2212 // If we got "length - 1" bytes, we didn't get the whole C string, we
2213 // need to read some more characters
2214 if (length == sizeof(buf) - 1)
2215 curr_addr += length;
2216 else
2217 break;
2218 }
2219 return out_str.size();
2220}
2221
2222size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
2223 Error &error, size_t type_width) {
2224 size_t total_bytes_read = 0;
2225 if (dst && max_bytes && type_width && max_bytes >= type_width) {
2226 // Ensure a null terminator independent of the number of bytes that is read.
2227 memset(dst, 0, max_bytes);
2228 size_t bytes_left = max_bytes - type_width;
2229
2230 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2231 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2232 "string with more than 4 bytes "
2233 "per character!");
2234
Greg Clayton4c82d422012-05-18 23:20:01 +00002235 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002236 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2237 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002238
Kate Stoneb9c1b512016-09-06 20:57:50 +00002239 error.Clear();
2240 while (bytes_left > 0 && error.Success()) {
2241 addr_t cache_line_bytes_left =
2242 cache_line_size - (curr_addr % cache_line_size);
2243 addr_t bytes_to_read =
2244 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2245 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002246
Kate Stoneb9c1b512016-09-06 20:57:50 +00002247 if (bytes_read == 0)
2248 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002249
Kate Stoneb9c1b512016-09-06 20:57:50 +00002250 // Search for a null terminator of correct size and alignment in
2251 // bytes_read
2252 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2253 for (size_t i = aligned_start;
2254 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2255 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2256 error.Clear();
2257 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002258 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002259
2260 total_bytes_read += bytes_read;
2261 curr_dst += bytes_read;
2262 curr_addr += bytes_read;
2263 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002264 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265 } else {
2266 if (max_bytes)
2267 error.SetErrorString("invalid arguments");
2268 }
2269 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002270}
2271
Kate Stoneb9c1b512016-09-06 20:57:50 +00002272// Deprecated in favor of ReadStringFromMemory which has wchar support and
2273// correct code to find
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002274// null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002275size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
2276 size_t dst_max_len, Error &result_error) {
2277 size_t total_cstr_len = 0;
2278 if (dst && dst_max_len) {
2279 result_error.Clear();
2280 // NULL out everything just to be safe
2281 memset(dst, 0, dst_max_len);
2282 Error error;
2283 addr_t curr_addr = addr;
2284 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2285 size_t bytes_left = dst_max_len - 1;
2286 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002287
Kate Stoneb9c1b512016-09-06 20:57:50 +00002288 while (bytes_left > 0) {
2289 addr_t cache_line_bytes_left =
2290 cache_line_size - (curr_addr % cache_line_size);
2291 addr_t bytes_to_read =
2292 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2293 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002294
Kate Stoneb9c1b512016-09-06 20:57:50 +00002295 if (bytes_read == 0) {
2296 result_error = error;
2297 dst[total_cstr_len] = '\0';
2298 break;
2299 }
2300 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002301
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302 total_cstr_len += len;
2303
2304 if (len < bytes_to_read)
2305 break;
2306
2307 curr_dst += bytes_read;
2308 curr_addr += bytes_read;
2309 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002310 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002311 } else {
2312 if (dst == nullptr)
2313 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002314 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002315 result_error.Clear();
2316 }
2317 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002318}
2319
Kate Stoneb9c1b512016-09-06 20:57:50 +00002320size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2321 Error &error) {
2322 if (buf == nullptr || size == 0)
2323 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324
Kate Stoneb9c1b512016-09-06 20:57:50 +00002325 size_t bytes_read = 0;
2326 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002327
Kate Stoneb9c1b512016-09-06 20:57:50 +00002328 while (bytes_read < size) {
2329 const size_t curr_size = size - bytes_read;
2330 const size_t curr_bytes_read =
2331 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2332 bytes_read += curr_bytes_read;
2333 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2334 break;
2335 }
2336
2337 // Replace any software breakpoint opcodes that fall into this range back
2338 // into "buf" before we return
2339 if (bytes_read > 0)
2340 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2341 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002342}
2343
Kate Stoneb9c1b512016-09-06 20:57:50 +00002344uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2345 size_t integer_byte_size,
2346 uint64_t fail_value,
2347 Error &error) {
2348 Scalar scalar;
2349 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2350 error))
2351 return scalar.ULongLong(fail_value);
2352 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002353}
2354
Kate Stoneb9c1b512016-09-06 20:57:50 +00002355int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2356 size_t integer_byte_size,
2357 int64_t fail_value, Error &error) {
2358 Scalar scalar;
2359 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2360 error))
2361 return scalar.SLongLong(fail_value);
2362 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002363}
2364
Kate Stoneb9c1b512016-09-06 20:57:50 +00002365addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error) {
2366 Scalar scalar;
2367 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2368 error))
2369 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2370 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002371}
2372
Kate Stoneb9c1b512016-09-06 20:57:50 +00002373bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
2374 Error &error) {
2375 Scalar scalar;
2376 const uint32_t addr_byte_size = GetAddressByteSize();
2377 if (addr_byte_size <= 4)
2378 scalar = (uint32_t)ptr_value;
2379 else
2380 scalar = ptr_value;
2381 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2382 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002383}
2384
Kate Stoneb9c1b512016-09-06 20:57:50 +00002385size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2386 Error &error) {
2387 size_t bytes_written = 0;
2388 const uint8_t *bytes = (const uint8_t *)buf;
2389
2390 while (bytes_written < size) {
2391 const size_t curr_size = size - bytes_written;
2392 const size_t curr_bytes_written = DoWriteMemory(
2393 addr + bytes_written, bytes + bytes_written, curr_size, error);
2394 bytes_written += curr_bytes_written;
2395 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2396 break;
2397 }
2398 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002399}
2400
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2402 Error &error) {
2403#if defined(ENABLE_MEMORY_CACHING)
2404 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002405#endif
2406
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407 if (buf == nullptr || size == 0)
2408 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002409
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002411
Kate Stoneb9c1b512016-09-06 20:57:50 +00002412 // We need to write any data that would go where any current software traps
2413 // (enabled software breakpoints) any software traps (breakpoints) that we
2414 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415
Kate Stoneb9c1b512016-09-06 20:57:50 +00002416 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002417
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2419 bp_sites_in_range)) {
2420 // No breakpoint sites overlap
2421 if (bp_sites_in_range.IsEmpty())
2422 return WriteMemoryPrivate(addr, buf, size, error);
2423 else {
2424 const uint8_t *ubuf = (const uint8_t *)buf;
2425 uint64_t bytes_written = 0;
2426
2427 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2428 &error](BreakpointSite *bp) -> void {
2429
2430 if (error.Success()) {
2431 addr_t intersect_addr;
2432 size_t intersect_size;
2433 size_t opcode_offset;
2434 const bool intersects = bp->IntersectsRange(
2435 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2436 UNUSED_IF_ASSERT_DISABLED(intersects);
2437 assert(intersects);
2438 assert(addr <= intersect_addr && intersect_addr < addr + size);
2439 assert(addr < intersect_addr + intersect_size &&
2440 intersect_addr + intersect_size <= addr + size);
2441 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2442
2443 // Check for bytes before this breakpoint
2444 const addr_t curr_addr = addr + bytes_written;
2445 if (intersect_addr > curr_addr) {
2446 // There are some bytes before this breakpoint that we need to
2447 // just write to memory
2448 size_t curr_size = intersect_addr - curr_addr;
2449 size_t curr_bytes_written = WriteMemoryPrivate(
2450 curr_addr, ubuf + bytes_written, curr_size, error);
2451 bytes_written += curr_bytes_written;
2452 if (curr_bytes_written != curr_size) {
2453 // We weren't able to write all of the requested bytes, we
2454 // are done looping and will return the number of bytes that
2455 // we have written so far.
2456 if (error.Success())
2457 error.SetErrorToGenericError();
2458 }
2459 }
2460 // Now write any bytes that would cover up any software breakpoints
2461 // directly into the breakpoint opcode buffer
2462 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2463 ubuf + bytes_written, intersect_size);
2464 bytes_written += intersect_size;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002465 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002466 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002467
Kate Stoneb9c1b512016-09-06 20:57:50 +00002468 if (bytes_written < size)
2469 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2470 size - bytes_written, error);
2471 }
2472 } else {
2473 return WriteMemoryPrivate(addr, buf, size, error);
2474 }
2475
2476 // Write any remaining bytes after the last breakpoint if we have any left
2477 return 0; // bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002478}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002479
Kate Stoneb9c1b512016-09-06 20:57:50 +00002480size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2481 size_t byte_size, Error &error) {
2482 if (byte_size == UINT32_MAX)
2483 byte_size = scalar.GetByteSize();
2484 if (byte_size > 0) {
2485 uint8_t buf[32];
2486 const size_t mem_size =
2487 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2488 if (mem_size > 0)
2489 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002490 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002491 error.SetErrorString("failed to get scalar as memory data");
2492 } else {
2493 error.SetErrorString("invalid scalar value");
2494 }
2495 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002496}
2497
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2499 bool is_signed, Scalar &scalar,
2500 Error &error) {
2501 uint64_t uval = 0;
2502 if (byte_size == 0) {
2503 error.SetErrorString("byte size is zero");
2504 } else if (byte_size & (byte_size - 1)) {
2505 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2506 byte_size);
2507 } else if (byte_size <= sizeof(uval)) {
2508 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2509 if (bytes_read == byte_size) {
2510 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2511 GetAddressByteSize());
2512 lldb::offset_t offset = 0;
2513 if (byte_size <= 4)
2514 scalar = data.GetMaxU32(&offset, byte_size);
2515 else
2516 scalar = data.GetMaxU64(&offset, byte_size);
2517 if (is_signed)
2518 scalar.SignExtend(byte_size * 8);
2519 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002520 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002521 } else {
2522 error.SetErrorStringWithFormat(
2523 "byte size of %u is too large for integer scalar type", byte_size);
2524 }
2525 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002526}
2527
Greg Claytond495c532011-05-17 03:37:42 +00002528#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002529addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2530 Error &error) {
2531 if (GetPrivateState() != eStateStopped)
2532 return LLDB_INVALID_ADDRESS;
2533
2534#if defined(USE_ALLOCATE_MEMORY_CACHE)
2535 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002536#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002537 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2538 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2539 if (log)
2540 log->Printf("Process::AllocateMemory(size=%" PRIu64
2541 ", permissions=%s) => 0x%16.16" PRIx64
2542 " (m_stop_id = %u m_memory_id = %u)",
2543 (uint64_t)size, GetPermissionsAsCString(permissions),
2544 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2545 m_mod_id.GetMemoryID());
2546 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002547#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002548}
2549
Kate Stoneb9c1b512016-09-06 20:57:50 +00002550addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2551 Error &error) {
2552 addr_t return_addr = AllocateMemory(size, permissions, error);
2553 if (error.Success()) {
2554 std::string buffer(size, 0);
2555 WriteMemory(return_addr, buffer.c_str(), size, error);
2556 }
2557 return return_addr;
2558}
2559
2560bool Process::CanJIT() {
2561 if (m_can_jit == eCanJITDontKnow) {
2562 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2563 Error err;
2564
2565 uint64_t allocated_memory = AllocateMemory(
2566 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2567 err);
2568
2569 if (err.Success()) {
2570 m_can_jit = eCanJITYes;
2571 if (log)
2572 log->Printf("Process::%s pid %" PRIu64
2573 " allocation test passed, CanJIT () is true",
2574 __FUNCTION__, GetID());
2575 } else {
2576 m_can_jit = eCanJITNo;
2577 if (log)
2578 log->Printf("Process::%s pid %" PRIu64
2579 " allocation test failed, CanJIT () is false: %s",
2580 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002582
2583 DeallocateMemory(allocated_memory);
2584 }
2585
2586 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002587}
2588
Kate Stoneb9c1b512016-09-06 20:57:50 +00002589void Process::SetCanJIT(bool can_jit) {
2590 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002591}
2592
Kate Stoneb9c1b512016-09-06 20:57:50 +00002593void Process::SetCanRunCode(bool can_run_code) {
2594 SetCanJIT(can_run_code);
2595 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002596}
2597
Kate Stoneb9c1b512016-09-06 20:57:50 +00002598Error Process::DeallocateMemory(addr_t ptr) {
2599 Error error;
2600#if defined(USE_ALLOCATE_MEMORY_CACHE)
2601 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2602 error.SetErrorStringWithFormat(
2603 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2604 }
Greg Claytond495c532011-05-17 03:37:42 +00002605#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002606 error = DoDeallocateMemory(ptr);
2607
2608 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2609 if (log)
2610 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2611 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2612 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2613 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002614#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002615 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002616}
2617
Kate Stoneb9c1b512016-09-06 20:57:50 +00002618ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2619 lldb::addr_t header_addr,
2620 size_t size_to_read) {
2621 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2622 if (log) {
2623 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2624 file_spec.GetPath().c_str());
2625 }
2626 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2627 if (module_sp) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002628 Error error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002629 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2630 shared_from_this(), header_addr, error, size_to_read);
2631 if (objfile)
2632 return module_sp;
2633 }
2634 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002635}
2636
Kate Stoneb9c1b512016-09-06 20:57:50 +00002637bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2638 uint32_t &permissions) {
2639 MemoryRegionInfo range_info;
2640 permissions = 0;
2641 Error error(GetMemoryRegionInfo(load_addr, range_info));
2642 if (!error.Success())
2643 return false;
2644 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2645 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2646 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2647 return false;
2648 }
2649
2650 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2651 permissions |= lldb::ePermissionsReadable;
2652
2653 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2654 permissions |= lldb::ePermissionsWritable;
2655
2656 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2657 permissions |= lldb::ePermissionsExecutable;
2658
2659 return true;
2660}
2661
2662Error Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2663 Error error;
2664 error.SetErrorString("watchpoints are not supported");
2665 return error;
2666}
2667
2668Error Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2669 Error error;
2670 error.SetErrorString("watchpoints are not supported");
2671 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002672}
2673
2674StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002675Process::WaitForProcessStopPrivate(EventSP &event_sp,
2676 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002677 StateType state;
2678 // Now wait for the process to launch and return control to us, and then
2679 // call DidLaunch:
2680 while (true) {
2681 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002682 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002683
Kate Stoneb9c1b512016-09-06 20:57:50 +00002684 if (StateIsStoppedState(state, false))
2685 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002686
Kate Stoneb9c1b512016-09-06 20:57:50 +00002687 // If state is invalid, then we timed out
2688 if (state == eStateInvalid)
2689 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002690
Kate Stoneb9c1b512016-09-06 20:57:50 +00002691 if (event_sp)
2692 HandlePrivateEvent(event_sp);
2693 }
2694 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002695}
2696
Kate Stoneb9c1b512016-09-06 20:57:50 +00002697void Process::LoadOperatingSystemPlugin(bool flush) {
2698 if (flush)
2699 m_thread_list.Clear();
2700 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2701 if (flush)
2702 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002703}
2704
Kate Stoneb9c1b512016-09-06 20:57:50 +00002705Error Process::Launch(ProcessLaunchInfo &launch_info) {
2706 Error error;
2707 m_abi_sp.reset();
2708 m_dyld_ap.reset();
2709 m_jit_loaders_ap.reset();
2710 m_system_runtime_ap.reset();
2711 m_os_ap.reset();
2712 m_process_input_reader.reset();
2713 m_stop_info_override_callback = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002714
Kate Stoneb9c1b512016-09-06 20:57:50 +00002715 Module *exe_module = GetTarget().GetExecutableModulePointer();
2716 if (exe_module) {
2717 char local_exec_file_path[PATH_MAX];
2718 char platform_exec_file_path[PATH_MAX];
2719 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2720 sizeof(local_exec_file_path));
2721 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2722 sizeof(platform_exec_file_path));
2723 if (exe_module->GetFileSpec().Exists()) {
2724 // Install anything that might need to be installed prior to launching.
2725 // For host systems, this will do nothing, but if we are connected to a
2726 // remote platform it will install any needed binaries
2727 error = GetTarget().Install(&launch_info);
2728 if (error.Fail())
2729 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002730
Kate Stoneb9c1b512016-09-06 20:57:50 +00002731 if (PrivateStateThreadIsValid())
2732 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002733
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 error = WillLaunch(exe_module);
2735 if (error.Success()) {
2736 const bool restarted = false;
2737 SetPublicState(eStateLaunching, restarted);
2738 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739
Kate Stoneb9c1b512016-09-06 20:57:50 +00002740 if (m_public_run_lock.TrySetRunning()) {
2741 // Now launch using these arguments.
2742 error = DoLaunch(exe_module, launch_info);
2743 } else {
2744 // This shouldn't happen
2745 error.SetErrorString("failed to acquire process run lock");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002746 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002747
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748 if (error.Fail()) {
2749 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2750 SetID(LLDB_INVALID_PROCESS_ID);
2751 const char *error_string = error.AsCString();
2752 if (error_string == nullptr)
2753 error_string = "launch failed";
2754 SetExitStatus(-1, error_string);
2755 }
2756 } else {
2757 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002758 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Greg Clayton35824e32015-02-20 20:59:47 +00002759
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 if (state == eStateInvalid || !event_sp) {
2761 // We were able to launch the process, but we failed to
2762 // catch the initial stop.
2763 error.SetErrorString("failed to catch stop after launch");
2764 SetExitStatus(0, "failed to catch stop after launch");
2765 Destroy(false);
2766 } else if (state == eStateStopped || state == eStateCrashed) {
2767 DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002768
Kate Stoneb9c1b512016-09-06 20:57:50 +00002769 DynamicLoader *dyld = GetDynamicLoader();
2770 if (dyld)
2771 dyld->DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002772
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 GetJITLoaders().DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002774
Kate Stoneb9c1b512016-09-06 20:57:50 +00002775 SystemRuntime *system_runtime = GetSystemRuntime();
2776 if (system_runtime)
2777 system_runtime->DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002778
Greg Clayton29eeea02017-02-09 18:55:41 +00002779 if (!m_os_ap)
2780 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002781
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002782 // We successfully launched the process and stopped,
2783 // now it the right time to set up signal filters before resuming.
2784 UpdateAutomaticSignalFiltering();
2785
Kate Stoneb9c1b512016-09-06 20:57:50 +00002786 // Note, the stop event was consumed above, but not handled. This
2787 // was done
2788 // to give DidLaunch a chance to run. The target is either stopped
2789 // or crashed.
2790 // Directly set the state. This is done to prevent a stop message
2791 // with a bunch
2792 // of spurious output on thread status, as well as not pop a
2793 // ProcessIOHandler.
2794 SetPublicState(state, false);
Greg Claytonc3776bf2012-02-09 06:16:32 +00002795
Kate Stoneb9c1b512016-09-06 20:57:50 +00002796 if (PrivateStateThreadIsValid())
2797 ResumePrivateStateThread();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002798 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799 StartPrivateStateThread();
Todd Fiala76e0fc92014-08-27 22:58:26 +00002800
Kate Stoneb9c1b512016-09-06 20:57:50 +00002801 m_stop_info_override_callback =
2802 GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002803
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 // Target was stopped at entry as was intended. Need to notify the
2805 // listeners
2806 // about it.
2807 if (state == eStateStopped &&
2808 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2809 HandlePrivateEvent(event_sp);
2810 } else if (state == eStateExited) {
2811 // We exited while trying to launch somehow. Don't call DidLaunch
2812 // as that's
2813 // not likely to work, and return an invalid pid.
2814 HandlePrivateEvent(event_sp);
2815 }
2816 }
2817 }
2818 } else {
2819 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2820 local_exec_file_path);
Jim Inghambb3a2832011-01-29 01:49:25 +00002821 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 }
2823 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002824}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002825
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826Error Process::LoadCore() {
2827 Error error = DoLoadCore();
2828 if (error.Success()) {
2829 ListenerSP listener_sp(
2830 Listener::MakeListener("lldb.process.load_core_listener"));
2831 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002832
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833 if (PrivateStateThreadIsValid())
2834 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002835 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002836 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002837
Kate Stoneb9c1b512016-09-06 20:57:50 +00002838 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002839 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002840 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002841
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002842 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002843
Kate Stoneb9c1b512016-09-06 20:57:50 +00002844 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002845 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002846 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002847
Greg Clayton29eeea02017-02-09 18:55:41 +00002848 if (!m_os_ap)
2849 LoadOperatingSystemPlugin(false);
2850
Kate Stoneb9c1b512016-09-06 20:57:50 +00002851 // We successfully loaded a core file, now pretend we stopped so we can
2852 // show all of the threads in the core file and explore the crashed
2853 // state.
2854 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002855
Kate Stoneb9c1b512016-09-06 20:57:50 +00002856 // Wait indefinitely for a stopped event since we just posted one above...
2857 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00002858 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002859 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2860
2861 if (!StateIsStoppedState(state, false)) {
2862 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2863 if (log)
2864 log->Printf("Process::Halt() failed to stop, state is: %s",
2865 StateAsCString(state));
2866 error.SetErrorString(
2867 "Did not get stopped event after loading the core file.");
2868 }
2869 RestoreProcessEvents();
2870 }
2871 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002872}
2873
Kate Stoneb9c1b512016-09-06 20:57:50 +00002874DynamicLoader *Process::GetDynamicLoader() {
2875 if (!m_dyld_ap)
2876 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2877 return m_dyld_ap.get();
2878}
2879
2880const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2881
2882JITLoaderList &Process::GetJITLoaders() {
2883 if (!m_jit_loaders_ap) {
2884 m_jit_loaders_ap.reset(new JITLoaderList());
2885 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2886 }
2887 return *m_jit_loaders_ap;
2888}
2889
2890SystemRuntime *Process::GetSystemRuntime() {
2891 if (!m_system_runtime_ap)
2892 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2893 return m_system_runtime_ap.get();
2894}
2895
2896Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2897 uint32_t exec_count)
2898 : NextEventAction(process), m_exec_count(exec_count) {
2899 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2900 if (log)
2901 log->Printf(
2902 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2903 __FUNCTION__, static_cast<void *>(process), exec_count);
2904}
2905
2906Process::NextEventAction::EventActionResult
2907Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2908 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2909
2910 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2911 if (log)
2912 log->Printf(
2913 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2914 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2915
2916 switch (state) {
2917 case eStateAttaching:
2918 return eEventActionSuccess;
2919
2920 case eStateRunning:
2921 case eStateConnected:
2922 return eEventActionRetry;
2923
2924 case eStateStopped:
2925 case eStateCrashed:
2926 // During attach, prior to sending the eStateStopped event,
2927 // lldb_private::Process subclasses must set the new process ID.
2928 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2929 // We don't want these events to be reported, so go set the ShouldReportStop
2930 // here:
2931 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2932
2933 if (m_exec_count > 0) {
2934 --m_exec_count;
2935
2936 if (log)
2937 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2938 "remaining exec count to %" PRIu32 ", requesting resume",
2939 __FUNCTION__, StateAsCString(state), m_exec_count);
2940
2941 RequestResume();
2942 return eEventActionRetry;
2943 } else {
2944 if (log)
2945 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2946 "execs expected to start, continuing with attach",
2947 __FUNCTION__, StateAsCString(state));
2948
2949 m_process->CompleteAttach();
2950 return eEventActionSuccess;
2951 }
2952 break;
2953
2954 default:
2955 case eStateExited:
2956 case eStateInvalid:
2957 break;
2958 }
2959
2960 m_exit_string.assign("No valid Process");
2961 return eEventActionExit;
2962}
2963
2964Process::NextEventAction::EventActionResult
2965Process::AttachCompletionHandler::HandleBeingInterrupted() {
2966 return eEventActionSuccess;
2967}
2968
2969const char *Process::AttachCompletionHandler::GetExitString() {
2970 return m_exit_string.c_str();
2971}
2972
2973ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2974 if (m_listener_sp)
2975 return m_listener_sp;
2976 else
2977 return debugger.GetListener();
2978}
2979
2980Error Process::Attach(ProcessAttachInfo &attach_info) {
2981 m_abi_sp.reset();
2982 m_process_input_reader.reset();
2983 m_dyld_ap.reset();
2984 m_jit_loaders_ap.reset();
2985 m_system_runtime_ap.reset();
2986 m_os_ap.reset();
2987 m_stop_info_override_callback = nullptr;
2988
2989 lldb::pid_t attach_pid = attach_info.GetProcessID();
2990 Error error;
2991 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2992 char process_name[PATH_MAX];
2993
2994 if (attach_info.GetExecutableFile().GetPath(process_name,
2995 sizeof(process_name))) {
2996 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2997
2998 if (wait_for_launch) {
2999 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3000 if (error.Success()) {
3001 if (m_public_run_lock.TrySetRunning()) {
3002 m_should_detach = true;
3003 const bool restarted = false;
3004 SetPublicState(eStateAttaching, restarted);
3005 // Now attach using these arguments.
3006 error = DoAttachToProcessWithName(process_name, attach_info);
3007 } else {
3008 // This shouldn't happen
3009 error.SetErrorString("failed to acquire process run lock");
3010 }
3011
3012 if (error.Fail()) {
3013 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3014 SetID(LLDB_INVALID_PROCESS_ID);
3015 if (error.AsCString() == nullptr)
3016 error.SetErrorString("attach failed");
3017
3018 SetExitStatus(-1, error.AsCString());
3019 }
3020 } else {
3021 SetNextEventAction(new Process::AttachCompletionHandler(
3022 this, attach_info.GetResumeCount()));
3023 StartPrivateStateThread();
3024 }
3025 return error;
3026 }
3027 } else {
3028 ProcessInstanceInfoList process_infos;
3029 PlatformSP platform_sp(GetTarget().GetPlatform());
3030
3031 if (platform_sp) {
3032 ProcessInstanceInfoMatch match_info;
3033 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00003034 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003035 platform_sp->FindProcesses(match_info, process_infos);
3036 const uint32_t num_matches = process_infos.GetSize();
3037 if (num_matches == 1) {
3038 attach_pid = process_infos.GetProcessIDAtIndex(0);
3039 // Fall through and attach using the above process ID
3040 } else {
3041 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3042 process_name, sizeof(process_name));
3043 if (num_matches > 1) {
3044 StreamString s;
3045 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3046 false);
3047 for (size_t i = 0; i < num_matches; i++) {
3048 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3049 s, platform_sp.get(), true, false);
3050 }
3051 error.SetErrorStringWithFormat(
3052 "more than one process named %s:\n%s", process_name,
3053 s.GetData());
3054 } else
3055 error.SetErrorStringWithFormat(
3056 "could not find a process named %s", process_name);
3057 }
3058 } else {
3059 error.SetErrorString(
3060 "invalid platform, can't find processes by name");
3061 return error;
3062 }
3063 }
3064 } else {
3065 error.SetErrorString("invalid process name");
3066 }
3067 }
3068
3069 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3070 error = WillAttachToProcessWithID(attach_pid);
3071 if (error.Success()) {
3072
3073 if (m_public_run_lock.TrySetRunning()) {
3074 // Now attach using these arguments.
3075 m_should_detach = true;
3076 const bool restarted = false;
3077 SetPublicState(eStateAttaching, restarted);
3078 error = DoAttachToProcessWithID(attach_pid, attach_info);
3079 } else {
3080 // This shouldn't happen
3081 error.SetErrorString("failed to acquire process run lock");
3082 }
3083
3084 if (error.Success()) {
3085 SetNextEventAction(new Process::AttachCompletionHandler(
3086 this, attach_info.GetResumeCount()));
3087 StartPrivateStateThread();
3088 } else {
Greg Clayton71337622011-02-24 22:24:29 +00003089 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003090 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003091
Kate Stoneb9c1b512016-09-06 20:57:50 +00003092 const char *error_string = error.AsCString();
3093 if (error_string == nullptr)
3094 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00003095
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096 SetExitStatus(-1, error_string);
3097 }
Greg Claytonb766a732011-02-04 01:58:07 +00003098 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 }
3100 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00003101}
3102
Kate Stoneb9c1b512016-09-06 20:57:50 +00003103void Process::CompleteAttach() {
3104 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3105 LIBLLDB_LOG_TARGET));
3106 if (log)
3107 log->Printf("Process::%s()", __FUNCTION__);
3108
3109 // Let the process subclass figure out at much as it can about the process
3110 // before we go looking for a dynamic loader plug-in.
3111 ArchSpec process_arch;
3112 DidAttach(process_arch);
3113
3114 if (process_arch.IsValid()) {
3115 GetTarget().SetArchitecture(process_arch);
3116 if (log) {
3117 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3118 log->Printf("Process::%s replacing process architecture with DidAttach() "
3119 "architecture: %s",
3120 __FUNCTION__, triple_str ? triple_str : "<null>");
3121 }
3122 }
3123
3124 // We just attached. If we have a platform, ask it for the process
3125 // architecture, and if it isn't
3126 // the same as the one we've already set, switch architectures.
3127 PlatformSP platform_sp(GetTarget().GetPlatform());
3128 assert(platform_sp);
3129 if (platform_sp) {
3130 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3131 if (target_arch.IsValid() &&
3132 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3133 ArchSpec platform_arch;
3134 platform_sp =
3135 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3136 if (platform_sp) {
3137 GetTarget().SetPlatform(platform_sp);
3138 GetTarget().SetArchitecture(platform_arch);
3139 if (log)
3140 log->Printf("Process::%s switching platform to %s and architecture "
3141 "to %s based on info from attach",
3142 __FUNCTION__, platform_sp->GetName().AsCString(""),
3143 platform_arch.GetTriple().getTriple().c_str());
3144 }
3145 } else if (!process_arch.IsValid()) {
3146 ProcessInstanceInfo process_info;
3147 GetProcessInfo(process_info);
3148 const ArchSpec &process_arch = process_info.GetArchitecture();
3149 if (process_arch.IsValid() &&
3150 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3151 GetTarget().SetArchitecture(process_arch);
3152 if (log)
3153 log->Printf("Process::%s switching architecture to %s based on info "
3154 "the platform retrieved for pid %" PRIu64,
3155 __FUNCTION__,
3156 process_arch.GetTriple().getTriple().c_str(), GetID());
3157 }
3158 }
3159 }
3160
3161 // We have completed the attach, now it is time to find the dynamic loader
3162 // plug-in
3163 DynamicLoader *dyld = GetDynamicLoader();
3164 if (dyld) {
3165 dyld->DidAttach();
3166 if (log) {
3167 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3168 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3169 "executable is %s (using %s plugin)",
3170 __FUNCTION__,
3171 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3172 : "<none>",
3173 dyld->GetPluginName().AsCString("<unnamed>"));
3174 }
3175 }
3176
3177 GetJITLoaders().DidAttach();
3178
3179 SystemRuntime *system_runtime = GetSystemRuntime();
3180 if (system_runtime) {
3181 system_runtime->DidAttach();
3182 if (log) {
3183 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3184 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3185 "executable is %s (using %s plugin)",
3186 __FUNCTION__,
3187 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3188 : "<none>",
3189 system_runtime->GetPluginName().AsCString("<unnamed>"));
3190 }
3191 }
3192
Greg Clayton29eeea02017-02-09 18:55:41 +00003193 if (!m_os_ap)
3194 LoadOperatingSystemPlugin(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003195 // Figure out which one is the executable, and set that in our target:
3196 const ModuleList &target_modules = GetTarget().GetImages();
3197 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3198 size_t num_modules = target_modules.GetSize();
3199 ModuleSP new_executable_module_sp;
3200
3201 for (size_t i = 0; i < num_modules; i++) {
3202 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3203 if (module_sp && module_sp->IsExecutable()) {
3204 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3205 new_executable_module_sp = module_sp;
3206 break;
3207 }
3208 }
3209 if (new_executable_module_sp) {
3210 GetTarget().SetExecutableModule(new_executable_module_sp, false);
3211 if (log) {
3212 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3213 log->Printf(
3214 "Process::%s after looping through modules, target executable is %s",
3215 __FUNCTION__,
3216 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3217 : "<none>");
3218 }
3219 }
3220
3221 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
3222}
3223
Zachary Turner31659452016-11-17 21:15:14 +00003224Error Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003225 m_abi_sp.reset();
3226 m_process_input_reader.reset();
3227
3228 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003229 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003230
3231 Error error(DoConnectRemote(strm, remote_url));
3232 if (error.Success()) {
3233 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3234 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003235 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003236
3237 if (state == eStateStopped || state == eStateCrashed) {
3238 // If we attached and actually have a process on the other end, then
3239 // this ended up being the equivalent of an attach.
3240 CompleteAttach();
3241
3242 // This delays passing the stopped event to listeners till
3243 // CompleteAttach gets a chance to complete...
3244 HandlePrivateEvent(event_sp);
3245 }
3246 }
3247
3248 if (PrivateStateThreadIsValid())
3249 ResumePrivateStateThread();
3250 else
3251 StartPrivateStateThread();
3252 }
3253 return error;
3254}
3255
3256Error Process::PrivateResume() {
3257 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3258 LIBLLDB_LOG_STEP));
3259 if (log)
3260 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3261 "private state: %s",
3262 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3263 StateAsCString(m_private_state.GetValue()));
3264
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003265 // If signals handing status changed we might want to update
3266 // our signal filters before resuming.
3267 UpdateAutomaticSignalFiltering();
3268
Kate Stoneb9c1b512016-09-06 20:57:50 +00003269 Error error(WillResume());
3270 // Tell the process it is about to resume before the thread list
3271 if (error.Success()) {
3272 // Now let the thread list know we are about to resume so it
3273 // can let all of our threads know that they are about to be
3274 // resumed. Threads will each be called with
3275 // Thread::WillResume(StateType) where StateType contains the state
3276 // that they are supposed to have when the process is resumed
3277 // (suspended/running/stepping). Threads should also check
3278 // their resume signal in lldb::Thread::GetResumeSignal()
3279 // to see if they are supposed to start back up with a signal.
3280 if (m_thread_list.WillResume()) {
3281 // Last thing, do the PreResumeActions.
3282 if (!RunPreResumeActions()) {
3283 error.SetErrorStringWithFormat(
3284 "Process::PrivateResume PreResumeActions failed, not resuming.");
3285 } else {
3286 m_mod_id.BumpResumeID();
3287 error = DoResume();
3288 if (error.Success()) {
3289 DidResume();
3290 m_thread_list.DidResume();
3291 if (log)
3292 log->Printf("Process thinks the process has resumed.");
3293 }
3294 }
3295 } else {
3296 // Somebody wanted to run without running (e.g. we were faking a step from
3297 // one frame of a set of inlined
3298 // frames that share the same PC to another.) So generate a continue & a
3299 // stopped event,
3300 // and let the world handle them.
3301 if (log)
3302 log->Printf(
3303 "Process::PrivateResume() asked to simulate a start & stop.");
3304
3305 SetPrivateState(eStateRunning);
3306 SetPrivateState(eStateStopped);
3307 }
3308 } else if (log)
3309 log->Printf("Process::PrivateResume() got an error \"%s\".",
3310 error.AsCString("<unknown error>"));
3311 return error;
3312}
3313
3314Error Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3315 if (!StateIsRunningState(m_public_state.GetValue()))
3316 return Error("Process is not running.");
3317
3318 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3319 // in case it was already set and some thread plan logic calls halt on its
3320 // own.
3321 m_clear_thread_plans_on_stop |= clear_thread_plans;
3322
3323 ListenerSP halt_listener_sp(
3324 Listener::MakeListener("lldb.process.halt_listener"));
3325 HijackProcessEvents(halt_listener_sp);
3326
3327 EventSP event_sp;
3328
3329 SendAsyncInterrupt();
3330
3331 if (m_public_state.GetValue() == eStateAttaching) {
3332 // Don't hijack and eat the eStateExited as the code that was doing
3333 // the attach will be waiting for this event...
3334 RestoreProcessEvents();
3335 SetExitStatus(SIGKILL, "Cancelled async attach.");
3336 Destroy(false);
Mehdi Aminic1edf562016-11-11 04:29:25 +00003337 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003338 }
3339
3340 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003341 StateType state = WaitForProcessToStop(
3342 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003343 RestoreProcessEvents();
3344
3345 if (state == eStateInvalid || !event_sp) {
3346 // We timed out and didn't get a stop event...
3347 return Error("Halt timed out. State = %s", StateAsCString(GetState()));
3348 }
3349
3350 BroadcastEvent(event_sp);
3351
Mehdi Aminic1edf562016-11-11 04:29:25 +00003352 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003353}
3354
3355Error Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3356 Error error;
3357
3358 // Check both the public & private states here. If we're hung evaluating an
3359 // expression, for instance, then
3360 // the public state will be stopped, but we still need to interrupt.
3361 if (m_public_state.GetValue() == eStateRunning ||
3362 m_private_state.GetValue() == eStateRunning) {
3363 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003364 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003365 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003366
Kate Stoneb9c1b512016-09-06 20:57:50 +00003367 ListenerSP listener_sp(
3368 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3369 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003370
Pavel Labath19da1f12015-12-07 12:36:52 +00003371 SendAsyncInterrupt();
3372
Kate Stoneb9c1b512016-09-06 20:57:50 +00003373 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003374 StateType state =
3375 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003376
Pavel Labath19da1f12015-12-07 12:36:52 +00003377 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003378
Kate Stoneb9c1b512016-09-06 20:57:50 +00003379 // If the process exited while we were waiting for it to stop, put the
3380 // exited event into
3381 // the shared pointer passed in and return. Our caller doesn't need to do
3382 // anything else, since
3383 // they don't have a process anymore...
3384
3385 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3386 if (log)
3387 log->Printf("Process::%s() Process exited while waiting to stop.",
3388 __FUNCTION__);
3389 return error;
3390 } else
3391 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3392
3393 if (state != eStateStopped) {
3394 if (log)
3395 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3396 StateAsCString(state));
3397 // If we really couldn't stop the process then we should just error out
3398 // here, but if the
3399 // lower levels just bobbled sending the event and we really are stopped,
3400 // then continue on.
3401 StateType private_state = m_private_state.GetValue();
3402 if (private_state != eStateStopped) {
3403 return Error("Attempt to stop the target in order to detach timed out. "
3404 "State = %s",
3405 StateAsCString(GetState()));
3406 }
3407 }
3408 }
3409 return error;
3410}
3411
3412Error Process::Detach(bool keep_stopped) {
3413 EventSP exit_event_sp;
3414 Error error;
3415 m_destroy_in_process = true;
3416
3417 error = WillDetach();
3418
3419 if (error.Success()) {
3420 if (DetachRequiresHalt()) {
3421 error = StopForDestroyOrDetach(exit_event_sp);
3422 if (!error.Success()) {
3423 m_destroy_in_process = false;
3424 return error;
3425 } else if (exit_event_sp) {
3426 // We shouldn't need to do anything else here. There's no process left
3427 // to detach from...
3428 StopPrivateStateThread();
3429 m_destroy_in_process = false;
3430 return error;
3431 }
3432 }
3433
3434 m_thread_list.DiscardThreadPlans();
3435 DisableAllBreakpointSites();
3436
3437 error = DoDetach(keep_stopped);
3438 if (error.Success()) {
3439 DidDetach();
3440 StopPrivateStateThread();
3441 } else {
3442 return error;
3443 }
3444 }
3445 m_destroy_in_process = false;
3446
3447 // If we exited when we were waiting for a process to stop, then
3448 // forward the event here so we don't lose the event
3449 if (exit_event_sp) {
3450 // Directly broadcast our exited event because we shut down our
3451 // private state thread above
3452 BroadcastEvent(exit_event_sp);
3453 }
3454
3455 // If we have been interrupted (to kill us) in the middle of running, we may
3456 // not end up propagating
3457 // the last events through the event system, in which case we might strand the
3458 // write lock. Unlock
3459 // it here so when we do to tear down the process we don't get an error
3460 // destroying the lock.
3461
3462 m_public_run_lock.SetStopped();
3463 return error;
3464}
3465
3466Error Process::Destroy(bool force_kill) {
3467
3468 // Tell ourselves we are in the process of destroying the process, so that we
3469 // don't do any unnecessary work
3470 // that might hinder the destruction. Remember to set this back to false when
3471 // we are done. That way if the attempt
3472 // failed and the process stays around for some reason it won't be in a
3473 // confused state.
3474
3475 if (force_kill)
3476 m_should_detach = false;
3477
3478 if (GetShouldDetach()) {
3479 // FIXME: This will have to be a process setting:
3480 bool keep_stopped = false;
3481 Detach(keep_stopped);
3482 }
3483
3484 m_destroy_in_process = true;
3485
3486 Error error(WillDestroy());
3487 if (error.Success()) {
3488 EventSP exit_event_sp;
3489 if (DestroyRequiresHalt()) {
3490 error = StopForDestroyOrDetach(exit_event_sp);
3491 }
3492
3493 if (m_public_state.GetValue() != eStateRunning) {
3494 // Ditch all thread plans, and remove all our breakpoints: in case we have
3495 // to restart the target to
3496 // kill it, we don't want it hitting a breakpoint...
3497 // Only do this if we've stopped, however, since if we didn't manage to
3498 // halt it above, then
3499 // we're not going to have much luck doing this now.
3500 m_thread_list.DiscardThreadPlans();
3501 DisableAllBreakpointSites();
3502 }
3503
3504 error = DoDestroy();
3505 if (error.Success()) {
3506 DidDestroy();
3507 StopPrivateStateThread();
3508 }
3509 m_stdio_communication.Disconnect();
3510 m_stdio_communication.StopReadThread();
3511 m_stdin_forward = false;
3512
3513 if (m_process_input_reader) {
3514 m_process_input_reader->SetIsDone(true);
3515 m_process_input_reader->Cancel();
3516 m_process_input_reader.reset();
3517 }
3518
3519 // If we exited when we were waiting for a process to stop, then
3520 // forward the event here so we don't lose the event
3521 if (exit_event_sp) {
3522 // Directly broadcast our exited event because we shut down our
3523 // private state thread above
3524 BroadcastEvent(exit_event_sp);
3525 }
3526
3527 // If we have been interrupted (to kill us) in the middle of running, we may
3528 // not end up propagating
3529 // the last events through the event system, in which case we might strand
3530 // the write lock. Unlock
3531 // it here so when we do to tear down the process we don't get an error
3532 // destroying the lock.
3533 m_public_run_lock.SetStopped();
3534 }
3535
3536 m_destroy_in_process = false;
3537
3538 return error;
3539}
3540
3541Error Process::Signal(int signal) {
3542 Error error(WillSignal());
3543 if (error.Success()) {
3544 error = DoSignal(signal);
3545 if (error.Success())
3546 DidSignal();
3547 }
3548 return error;
3549}
3550
3551void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3552 assert(signals_sp && "null signals_sp");
3553 m_unix_signals_sp = signals_sp;
3554}
3555
3556const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3557 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3558 return m_unix_signals_sp;
3559}
3560
3561lldb::ByteOrder Process::GetByteOrder() const {
3562 return GetTarget().GetArchitecture().GetByteOrder();
3563}
3564
3565uint32_t Process::GetAddressByteSize() const {
3566 return GetTarget().GetArchitecture().GetAddressByteSize();
3567}
3568
3569bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3570 const StateType state =
3571 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3572 bool return_value = true;
3573 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3574 LIBLLDB_LOG_PROCESS));
3575
3576 switch (state) {
3577 case eStateDetached:
3578 case eStateExited:
3579 case eStateUnloaded:
3580 m_stdio_communication.SynchronizeWithReadThread();
3581 m_stdio_communication.Disconnect();
3582 m_stdio_communication.StopReadThread();
3583 m_stdin_forward = false;
3584
3585 LLVM_FALLTHROUGH;
3586 case eStateConnected:
3587 case eStateAttaching:
3588 case eStateLaunching:
3589 // These events indicate changes in the state of the debugging session,
3590 // always report them.
3591 return_value = true;
3592 break;
3593 case eStateInvalid:
3594 // We stopped for no apparent reason, don't report it.
3595 return_value = false;
3596 break;
3597 case eStateRunning:
3598 case eStateStepping:
3599 // If we've started the target running, we handle the cases where we
3600 // are already running and where there is a transition from stopped to
3601 // running differently.
3602 // running -> running: Automatically suppress extra running events
3603 // stopped -> running: Report except when there is one or more no votes
3604 // and no yes votes.
3605 SynchronouslyNotifyStateChanged(state);
3606 if (m_force_next_event_delivery)
3607 return_value = true;
3608 else {
3609 switch (m_last_broadcast_state) {
3610 case eStateRunning:
3611 case eStateStepping:
3612 // We always suppress multiple runnings with no PUBLIC stop in between.
3613 return_value = false;
3614 break;
3615 default:
3616 // TODO: make this work correctly. For now always report
3617 // run if we aren't running so we don't miss any running
3618 // events. If I run the lldb/test/thread/a.out file and
3619 // break at main.cpp:58, run and hit the breakpoints on
3620 // multiple threads, then somehow during the stepping over
3621 // of all breakpoints no run gets reported.
3622
3623 // This is a transition from stop to run.
3624 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3625 case eVoteYes:
3626 case eVoteNoOpinion:
3627 return_value = true;
3628 break;
3629 case eVoteNo:
3630 return_value = false;
3631 break;
3632 }
3633 break;
3634 }
3635 }
3636 break;
3637 case eStateStopped:
3638 case eStateCrashed:
3639 case eStateSuspended:
3640 // We've stopped. First see if we're going to restart the target.
3641 // If we are going to stop, then we always broadcast the event.
3642 // If we aren't going to stop, let the thread plans decide if we're going to
3643 // report this event.
3644 // If no thread has an opinion, we don't report it.
3645
3646 m_stdio_communication.SynchronizeWithReadThread();
3647 RefreshStateAfterStop();
3648 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3649 if (log)
3650 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3651 "interrupt, state: %s",
3652 static_cast<void *>(event_ptr), StateAsCString(state));
3653 // Even though we know we are going to stop, we should let the threads
3654 // have a look at the stop,
3655 // so they can properly set their state.
3656 m_thread_list.ShouldStop(event_ptr);
3657 return_value = true;
3658 } else {
3659 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3660 bool should_resume = false;
3661
3662 // It makes no sense to ask "ShouldStop" if we've already been
3663 // restarted...
3664 // Asking the thread list is also not likely to go well, since we are
3665 // running again.
3666 // So in that case just report the event.
3667
3668 if (!was_restarted)
3669 should_resume = !m_thread_list.ShouldStop(event_ptr);
3670
3671 if (was_restarted || should_resume || m_resume_requested) {
3672 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3673 if (log)
3674 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3675 "%s was_restarted: %i stop_vote: %d.",
3676 should_resume, StateAsCString(state), was_restarted,
3677 stop_vote);
3678
3679 switch (stop_vote) {
3680 case eVoteYes:
3681 return_value = true;
3682 break;
3683 case eVoteNoOpinion:
3684 case eVoteNo:
3685 return_value = false;
3686 break;
3687 }
3688
3689 if (!was_restarted) {
3690 if (log)
3691 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3692 "from state: %s",
3693 static_cast<void *>(event_ptr), StateAsCString(state));
3694 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3695 PrivateResume();
3696 }
3697 } else {
3698 return_value = true;
3699 SynchronouslyNotifyStateChanged(state);
3700 }
3701 }
3702 break;
3703 }
3704
3705 // Forcing the next event delivery is a one shot deal. So reset it here.
3706 m_force_next_event_delivery = false;
3707
3708 // We do some coalescing of events (for instance two consecutive running
3709 // events get coalesced.)
3710 // But we only coalesce against events we actually broadcast. So we use
3711 // m_last_broadcast_state
3712 // to track that. NB - you can't use "m_public_state.GetValue()" for that
3713 // purpose, as was originally done,
3714 // because the PublicState reflects the last event pulled off the queue, and
3715 // there may be several
3716 // events stacked up on the queue unserviced. So the PublicState may not
3717 // reflect the last broadcasted event
3718 // yet. m_last_broadcast_state gets updated here.
3719
3720 if (return_value)
3721 m_last_broadcast_state = state;
3722
3723 if (log)
3724 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3725 "broadcast state: %s - %s",
3726 static_cast<void *>(event_ptr), StateAsCString(state),
3727 StateAsCString(m_last_broadcast_state),
3728 return_value ? "YES" : "NO");
3729 return return_value;
3730}
3731
3732bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3733 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3734
3735 bool already_running = PrivateStateThreadIsValid();
3736 if (log)
3737 log->Printf("Process::%s()%s ", __FUNCTION__,
3738 already_running ? " already running"
3739 : " starting private state thread");
3740
3741 if (!is_secondary_thread && already_running)
3742 return true;
3743
3744 // Create a thread that watches our internal state and controls which
3745 // events make it to clients (into the DCProcess event queue).
3746 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003747 uint32_t max_len = llvm::get_max_thread_name_length();
3748 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003749 // On platforms with abbreviated thread name lengths, choose thread names
3750 // that fit within the limit.
3751 if (already_running)
3752 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3753 else
3754 snprintf(thread_name, sizeof(thread_name), "intern-state");
3755 } else {
3756 if (already_running)
3757 snprintf(thread_name, sizeof(thread_name),
3758 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3759 GetID());
3760 else
3761 snprintf(thread_name, sizeof(thread_name),
3762 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3763 }
3764
3765 // Create the private state thread, and start it running.
3766 PrivateStateThreadArgs *args_ptr =
3767 new PrivateStateThreadArgs(this, is_secondary_thread);
3768 m_private_state_thread =
3769 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3770 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3771 if (m_private_state_thread.IsJoinable()) {
3772 ResumePrivateStateThread();
3773 return true;
3774 } else
3775 return false;
3776}
3777
3778void Process::PausePrivateStateThread() {
3779 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3780}
3781
3782void Process::ResumePrivateStateThread() {
3783 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3784}
3785
3786void Process::StopPrivateStateThread() {
3787 if (m_private_state_thread.IsJoinable())
3788 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3789 else {
3790 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3791 if (log)
3792 log->Printf(
3793 "Went to stop the private state thread, but it was already invalid.");
3794 }
3795}
3796
3797void Process::ControlPrivateStateThread(uint32_t signal) {
3798 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3799
3800 assert(signal == eBroadcastInternalStateControlStop ||
3801 signal == eBroadcastInternalStateControlPause ||
3802 signal == eBroadcastInternalStateControlResume);
3803
3804 if (log)
3805 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3806
3807 // Signal the private state thread
3808 if (m_private_state_thread.IsJoinable()) {
3809 // Broadcast the event.
3810 // It is important to do this outside of the if below, because
3811 // it's possible that the thread state is invalid but that the
3812 // thread is waiting on a control event instead of simply being
3813 // on its way out (this should not happen, but it apparently can).
3814 if (log)
3815 log->Printf("Sending control event of type: %d.", signal);
3816 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3817 m_private_state_control_broadcaster.BroadcastEvent(signal,
3818 event_receipt_sp);
3819
3820 // Wait for the event receipt or for the private state thread to exit
3821 bool receipt_received = false;
3822 if (PrivateStateThreadIsValid()) {
3823 while (!receipt_received) {
3824 bool timed_out = false;
3825 // Check for a receipt for 2 seconds and then check if the private state
3826 // thread is still around.
3827 receipt_received = event_receipt_sp->WaitForEventReceived(
3828 std::chrono::seconds(2), &timed_out);
3829 if (!receipt_received) {
3830 // Check if the private state thread is still around. If it isn't then
3831 // we are done waiting
3832 if (!PrivateStateThreadIsValid())
3833 break; // Private state thread exited or is exiting, we are done
3834 }
3835 }
3836 }
3837
3838 if (signal == eBroadcastInternalStateControlStop) {
3839 thread_result_t result = NULL;
3840 m_private_state_thread.Join(&result);
3841 m_private_state_thread.Reset();
3842 }
3843 } else {
3844 if (log)
3845 log->Printf(
3846 "Private state thread already dead, no need to signal it to stop.");
3847 }
3848}
3849
3850void Process::SendAsyncInterrupt() {
3851 if (PrivateStateThreadIsValid())
3852 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3853 nullptr);
3854 else
3855 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3856}
3857
3858void Process::HandlePrivateEvent(EventSP &event_sp) {
3859 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3860 m_resume_requested = false;
3861
3862 const StateType new_state =
3863 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3864
3865 // First check to see if anybody wants a shot at this event:
3866 if (m_next_event_action_ap) {
3867 NextEventAction::EventActionResult action_result =
3868 m_next_event_action_ap->PerformAction(event_sp);
3869 if (log)
3870 log->Printf("Ran next event action, result was %d.", action_result);
3871
3872 switch (action_result) {
3873 case NextEventAction::eEventActionSuccess:
3874 SetNextEventAction(nullptr);
3875 break;
3876
3877 case NextEventAction::eEventActionRetry:
3878 break;
3879
3880 case NextEventAction::eEventActionExit:
3881 // Handle Exiting Here. If we already got an exited event,
3882 // we should just propagate it. Otherwise, swallow this event,
3883 // and set our state to exit so the next event will kill us.
3884 if (new_state != eStateExited) {
3885 // FIXME: should cons up an exited event, and discard this one.
3886 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3887 SetNextEventAction(nullptr);
3888 return;
3889 }
3890 SetNextEventAction(nullptr);
3891 break;
3892 }
3893 }
3894
3895 // See if we should broadcast this state to external clients?
3896 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3897
3898 if (should_broadcast) {
3899 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3900 if (log) {
3901 log->Printf("Process::%s (pid = %" PRIu64
3902 ") broadcasting new state %s (old state %s) to %s",
3903 __FUNCTION__, GetID(), StateAsCString(new_state),
3904 StateAsCString(GetState()),
3905 is_hijacked ? "hijacked" : "public");
3906 }
3907 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3908 if (StateIsRunningState(new_state)) {
3909 // Only push the input handler if we aren't fowarding events,
3910 // as this means the curses GUI is in use...
3911 // Or don't push it if we are launching since it will come up stopped.
3912 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3913 new_state != eStateLaunching && new_state != eStateAttaching) {
3914 PushProcessIOHandler();
3915 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3916 eBroadcastAlways);
3917 if (log)
3918 log->Printf("Process::%s updated m_iohandler_sync to %d",
3919 __FUNCTION__, m_iohandler_sync.GetValue());
3920 }
3921 } else if (StateIsStoppedState(new_state, false)) {
3922 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3923 // If the lldb_private::Debugger is handling the events, we don't
3924 // want to pop the process IOHandler here, we want to do it when
3925 // we receive the stopped event so we can carefully control when
3926 // the process IOHandler is popped because when we stop we want to
3927 // display some text stating how and why we stopped, then maybe some
3928 // process/thread/frame info, and then we want the "(lldb) " prompt
3929 // to show up. If we pop the process IOHandler here, then we will
3930 // cause the command interpreter to become the top IOHandler after
3931 // the process pops off and it will update its prompt right away...
3932 // See the Debugger.cpp file where it calls the function as
3933 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3934 // Otherwise we end up getting overlapping "(lldb) " prompts and
3935 // garbled output.
3936 //
3937 // If we aren't handling the events in the debugger (which is indicated
3938 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3939 // are hijacked, then we always pop the process IO handler manually.
3940 // Hijacking happens when the internal process state thread is running
3941 // thread plans, or when commands want to run in synchronous mode
3942 // and they call "process->WaitForProcessToStop()". An example of
3943 // something
3944 // that will hijack the events is a simple expression:
3945 //
3946 // (lldb) expr (int)puts("hello")
3947 //
3948 // This will cause the internal process state thread to resume and halt
3949 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3950 // events) and we do need the IO handler to be pushed and popped
3951 // correctly.
3952
3953 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3954 PopProcessIOHandler();
3955 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003956 }
3957
3958 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003959 } else {
3960 if (log) {
3961 log->Printf(
3962 "Process::%s (pid = %" PRIu64
3963 ") suppressing state %s (old state %s): should_broadcast == false",
3964 __FUNCTION__, GetID(), StateAsCString(new_state),
3965 StateAsCString(GetState()));
3966 }
3967 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003968}
3969
Kate Stoneb9c1b512016-09-06 20:57:50 +00003970Error Process::HaltPrivate() {
3971 EventSP event_sp;
3972 Error error(WillHalt());
3973 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003974 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003975
3976 // Ask the process subclass to actually halt our process
3977 bool caused_stop;
3978 error = DoHalt(caused_stop);
3979
3980 DidHalt();
3981 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003982}
3983
Kate Stoneb9c1b512016-09-06 20:57:50 +00003984thread_result_t Process::PrivateStateThread(void *arg) {
3985 std::unique_ptr<PrivateStateThreadArgs> args_up(
3986 static_cast<PrivateStateThreadArgs *>(arg));
3987 thread_result_t result =
3988 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3989 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003990}
3991
Kate Stoneb9c1b512016-09-06 20:57:50 +00003992thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3993 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003994
Kate Stoneb9c1b512016-09-06 20:57:50 +00003995 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3996 if (log)
3997 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3998 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003999
Kate Stoneb9c1b512016-09-06 20:57:50 +00004000 bool exit_now = false;
4001 bool interrupt_requested = false;
4002 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00004003 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00004004 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004005 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4006 if (log)
4007 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4008 ") got a control event: %d",
4009 __FUNCTION__, static_cast<void *>(this), GetID(),
4010 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00004011
Kate Stoneb9c1b512016-09-06 20:57:50 +00004012 switch (event_sp->GetType()) {
4013 case eBroadcastInternalStateControlStop:
4014 exit_now = true;
4015 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00004016
Kate Stoneb9c1b512016-09-06 20:57:50 +00004017 case eBroadcastInternalStateControlPause:
4018 control_only = true;
4019 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004020
Kate Stoneb9c1b512016-09-06 20:57:50 +00004021 case eBroadcastInternalStateControlResume:
4022 control_only = false;
4023 break;
4024 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004025
Kate Stoneb9c1b512016-09-06 20:57:50 +00004026 continue;
4027 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4028 if (m_public_state.GetValue() == eStateAttaching) {
4029 if (log)
4030 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4031 ") woke up with an interrupt while attaching - "
4032 "forwarding interrupt.",
4033 __FUNCTION__, static_cast<void *>(this), GetID());
4034 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4035 } else if (StateIsRunningState(m_last_broadcast_state)) {
4036 if (log)
4037 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4038 ") woke up with an interrupt - Halting.",
4039 __FUNCTION__, static_cast<void *>(this), GetID());
4040 Error error = HaltPrivate();
4041 if (error.Fail() && log)
4042 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4043 ") failed to halt the process: %s",
4044 __FUNCTION__, static_cast<void *>(this), GetID(),
4045 error.AsCString());
4046 // Halt should generate a stopped event. Make a note of the fact that we
4047 // were
4048 // doing the interrupt, so we can set the interrupted flag after we
4049 // receive the
4050 // event. We deliberately set this to true even if HaltPrivate failed,
4051 // so that we
4052 // can interrupt on the next natural stop.
4053 interrupt_requested = true;
4054 } else {
4055 // This can happen when someone (e.g. Process::Halt) sees that we are
4056 // running and
4057 // sends an interrupt request, but the process actually stops before we
4058 // receive
4059 // it. In that case, we can just ignore the request. We use
4060 // m_last_broadcast_state, because the Stopped event may not have been
4061 // popped of
4062 // the event queue yet, which is when the public state gets updated.
4063 if (log)
4064 log->Printf(
4065 "Process::%s ignoring interrupt as we have already stopped.",
4066 __FUNCTION__);
4067 }
4068 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004069 }
4070
Kate Stoneb9c1b512016-09-06 20:57:50 +00004071 const StateType internal_state =
4072 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004073
Kate Stoneb9c1b512016-09-06 20:57:50 +00004074 if (internal_state != eStateInvalid) {
4075 if (m_clear_thread_plans_on_stop &&
4076 StateIsStoppedState(internal_state, true)) {
4077 m_clear_thread_plans_on_stop = false;
4078 m_thread_list.DiscardThreadPlans();
4079 }
4080
4081 if (interrupt_requested) {
4082 if (StateIsStoppedState(internal_state, true)) {
4083 // We requested the interrupt, so mark this as such in the stop event
4084 // so
4085 // clients can tell an interrupted process from a natural stop
4086 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4087 interrupt_requested = false;
4088 } else if (log) {
4089 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4090 "state '%s' received.",
4091 __FUNCTION__, StateAsCString(internal_state));
4092 }
4093 }
4094
4095 HandlePrivateEvent(event_sp);
4096 }
4097
4098 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4099 internal_state == eStateDetached) {
4100 if (log)
4101 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4102 ") about to exit with internal state %s...",
4103 __FUNCTION__, static_cast<void *>(this), GetID(),
4104 StateAsCString(internal_state));
4105
4106 break;
4107 }
4108 }
4109
4110 // Verify log is still enabled before attempting to write to it...
4111 if (log)
4112 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4113 __FUNCTION__, static_cast<void *>(this), GetID());
4114
4115 // If we are a secondary thread, then the primary thread we are working for
4116 // will have already
4117 // acquired the public_run_lock, and isn't done with what it was doing yet, so
4118 // don't
4119 // try to change it on the way out.
4120 if (!is_secondary_thread)
4121 m_public_run_lock.SetStopped();
4122 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004123}
4124
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004125//------------------------------------------------------------------
4126// Process Event Data
4127//------------------------------------------------------------------
4128
Kate Stoneb9c1b512016-09-06 20:57:50 +00004129Process::ProcessEventData::ProcessEventData()
4130 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4131 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004132
Kate Stoneb9c1b512016-09-06 20:57:50 +00004133Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4134 StateType state)
4135 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4136 m_update_state(0), m_interrupted(false) {
4137 if (process_sp)
4138 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004139}
4140
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004141Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004142
Kate Stoneb9c1b512016-09-06 20:57:50 +00004143const ConstString &Process::ProcessEventData::GetFlavorString() {
4144 static ConstString g_flavor("Process::ProcessEventData");
4145 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004146}
4147
Kate Stoneb9c1b512016-09-06 20:57:50 +00004148const ConstString &Process::ProcessEventData::GetFlavor() const {
4149 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004150}
4151
Kate Stoneb9c1b512016-09-06 20:57:50 +00004152void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4153 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004154
Kate Stoneb9c1b512016-09-06 20:57:50 +00004155 if (!process_sp)
4156 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004157
Kate Stoneb9c1b512016-09-06 20:57:50 +00004158 // This function gets called twice for each event, once when the event gets
4159 // pulled
4160 // off of the private process event queue, and then any number of times, first
4161 // when it gets pulled off of
4162 // the public event queue, then other times when we're pretending that this is
4163 // where we stopped at the
4164 // end of expression evaluation. m_update_state is used to distinguish these
4165 // three cases; it is 0 when we're just pulling it off for private handling,
4166 // and > 1 for expression evaluation, and we don't want to do the breakpoint
4167 // command handling then.
4168 if (m_update_state != 1)
4169 return;
4170
4171 process_sp->SetPublicState(
4172 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4173
Jason Molendab3a3cd12016-12-08 06:27:29 +00004174 if (m_state == eStateStopped && !m_restarted) {
4175 // Let process subclasses know we are about to do a public stop and
4176 // do anything they might need to in order to speed up register and
4177 // memory accesses.
4178 process_sp->WillPublicStop();
4179 }
4180
Kate Stoneb9c1b512016-09-06 20:57:50 +00004181 // If this is a halt event, even if the halt stopped with some reason other
4182 // than a plain interrupt (e.g. we had
4183 // already stopped for a breakpoint when the halt request came through) don't
4184 // do the StopInfo actions, as they may
4185 // end up restarting the process.
4186 if (m_interrupted)
4187 return;
4188
4189 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4190 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004191 ThreadList &curr_thread_list = process_sp->GetThreadList();
4192 uint32_t num_threads = curr_thread_list.GetSize();
4193 uint32_t idx;
4194
4195 // The actions might change one of the thread's stop_info's opinions about
4196 // whether we should
4197 // stop the process, so we need to query that as we go.
4198
4199 // One other complication here, is that we try to catch any case where the
4200 // target has run (except for expressions)
4201 // and immediately exit, but if we get that wrong (which is possible) then
4202 // the thread list might have changed, and
4203 // that would cause our iteration here to crash. We could make a copy of
4204 // the thread list, but we'd really like
4205 // to also know if it has changed at all, so we make up a vector of the
4206 // thread ID's and check what we get back
4207 // against this list & bag out if anything differs.
4208 std::vector<uint32_t> thread_index_array(num_threads);
4209 for (idx = 0; idx < num_threads; ++idx)
4210 thread_index_array[idx] =
4211 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4212
4213 // Use this to track whether we should continue from here. We will only
4214 // continue the target running if
4215 // no thread says we should stop. Of course if some thread's PerformAction
4216 // actually sets the target running,
4217 // then it doesn't matter what the other threads say...
4218
4219 bool still_should_stop = false;
4220
4221 // Sometimes - for instance if we have a bug in the stub we are talking to,
4222 // we stop but no thread has a
4223 // valid stop reason. In that case we should just stop, because we have no
4224 // way of telling what the right
4225 // thing to do is, and it's better to let the user decide than continue
4226 // behind their backs.
4227
4228 bool does_anybody_have_an_opinion = false;
4229
4230 for (idx = 0; idx < num_threads; ++idx) {
4231 curr_thread_list = process_sp->GetThreadList();
4232 if (curr_thread_list.GetSize() != num_threads) {
4233 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4234 LIBLLDB_LOG_PROCESS));
4235 if (log)
4236 log->Printf(
4237 "Number of threads changed from %u to %u while processing event.",
4238 num_threads, curr_thread_list.GetSize());
4239 break;
4240 }
4241
4242 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4243
4244 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4245 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4246 LIBLLDB_LOG_PROCESS));
4247 if (log)
4248 log->Printf("The thread at position %u changed from %u to %u while "
4249 "processing event.",
4250 idx, thread_index_array[idx], thread_sp->GetIndexID());
4251 break;
4252 }
4253
4254 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4255 if (stop_info_sp && stop_info_sp->IsValid()) {
4256 does_anybody_have_an_opinion = true;
4257 bool this_thread_wants_to_stop;
4258 if (stop_info_sp->GetOverrideShouldStop()) {
4259 this_thread_wants_to_stop =
4260 stop_info_sp->GetOverriddenShouldStopValue();
4261 } else {
4262 stop_info_sp->PerformAction(event_ptr);
4263 // The stop action might restart the target. If it does, then we want
4264 // to mark that in the
4265 // event so that whoever is receiving it will know to wait for the
4266 // running event and reflect
4267 // that state appropriately.
4268 // We also need to stop processing actions, since they aren't
4269 // expecting the target to be running.
4270
4271 // FIXME: we might have run.
4272 if (stop_info_sp->HasTargetRunSinceMe()) {
4273 SetRestarted(true);
4274 break;
4275 }
4276
4277 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004278 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004279
4280 if (!still_should_stop)
4281 still_should_stop = this_thread_wants_to_stop;
4282 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004283 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004284
4285 if (!GetRestarted()) {
4286 if (!still_should_stop && does_anybody_have_an_opinion) {
4287 // We've been asked to continue, so do that here.
4288 SetRestarted(true);
4289 // Use the public resume method here, since this is just
4290 // extending a public resume.
4291 process_sp->PrivateResume();
4292 } else {
4293 // If we didn't restart, run the Stop Hooks here:
4294 // They might also restart the target, so watch for that.
4295 process_sp->GetTarget().RunStopHooks();
4296 if (process_sp->GetPrivateState() == eStateRunning)
4297 SetRestarted(true);
4298 }
4299 }
4300 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004301}
4302
Kate Stoneb9c1b512016-09-06 20:57:50 +00004303void Process::ProcessEventData::Dump(Stream *s) const {
4304 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004305
Kate Stoneb9c1b512016-09-06 20:57:50 +00004306 if (process_sp)
4307 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4308 static_cast<void *>(process_sp.get()), process_sp->GetID());
4309 else
4310 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004311
Kate Stoneb9c1b512016-09-06 20:57:50 +00004312 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004313}
4314
4315const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004316Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4317 if (event_ptr) {
4318 const EventData *event_data = event_ptr->GetData();
4319 if (event_data &&
4320 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4321 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4322 }
4323 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004324}
4325
4326ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004327Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4328 ProcessSP process_sp;
4329 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4330 if (data)
4331 process_sp = data->GetProcessSP();
4332 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004333}
4334
Kate Stoneb9c1b512016-09-06 20:57:50 +00004335StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4336 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4337 if (data == nullptr)
4338 return eStateInvalid;
4339 else
4340 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004341}
4342
Kate Stoneb9c1b512016-09-06 20:57:50 +00004343bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4344 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4345 if (data == nullptr)
4346 return false;
4347 else
4348 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004349}
4350
Kate Stoneb9c1b512016-09-06 20:57:50 +00004351void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4352 bool new_value) {
4353 ProcessEventData *data =
4354 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4355 if (data != nullptr)
4356 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004357}
4358
Jim Ingham0161b492013-02-09 01:29:05 +00004359size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004360Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4361 ProcessEventData *data =
4362 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4363 if (data != nullptr)
4364 return data->GetNumRestartedReasons();
4365 else
4366 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004367}
4368
4369const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004370Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4371 size_t idx) {
4372 ProcessEventData *data =
4373 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4374 if (data != nullptr)
4375 return data->GetRestartedReasonAtIndex(idx);
4376 else
4377 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004378}
4379
Kate Stoneb9c1b512016-09-06 20:57:50 +00004380void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4381 const char *reason) {
4382 ProcessEventData *data =
4383 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4384 if (data != nullptr)
4385 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004386}
4387
Kate Stoneb9c1b512016-09-06 20:57:50 +00004388bool Process::ProcessEventData::GetInterruptedFromEvent(
4389 const Event *event_ptr) {
4390 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4391 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004392 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004393 else
4394 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004395}
4396
Kate Stoneb9c1b512016-09-06 20:57:50 +00004397void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4398 bool new_value) {
4399 ProcessEventData *data =
4400 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4401 if (data != nullptr)
4402 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004403}
4404
Kate Stoneb9c1b512016-09-06 20:57:50 +00004405bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4406 ProcessEventData *data =
4407 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4408 if (data) {
4409 data->SetUpdateStateOnRemoval();
4410 return true;
4411 }
4412 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004413}
4414
Kate Stoneb9c1b512016-09-06 20:57:50 +00004415lldb::TargetSP Process::CalculateTarget() { return m_target_sp.lock(); }
4416
4417void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4418 exe_ctx.SetTargetPtr(&GetTarget());
4419 exe_ctx.SetProcessPtr(this);
4420 exe_ctx.SetThreadPtr(nullptr);
4421 exe_ctx.SetFramePtr(nullptr);
4422}
4423
4424// uint32_t
4425// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4426// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004427//{
4428// return 0;
4429//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004430//
4431// ArchSpec
4432// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004433//{
4434// return Host::GetArchSpecForExistingProcess (pid);
4435//}
4436//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004437// ArchSpec
4438// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004439//{
4440// return Host::GetArchSpecForExistingProcess (process_name);
4441//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004442
Kate Stoneb9c1b512016-09-06 20:57:50 +00004443void Process::AppendSTDOUT(const char *s, size_t len) {
4444 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4445 m_stdout_data.append(s, len);
4446 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4447 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004448}
4449
Kate Stoneb9c1b512016-09-06 20:57:50 +00004450void Process::AppendSTDERR(const char *s, size_t len) {
4451 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4452 m_stderr_data.append(s, len);
4453 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4454 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004455}
4456
Kate Stoneb9c1b512016-09-06 20:57:50 +00004457void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4458 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4459 m_profile_data.push_back(one_profile_data);
4460 BroadcastEventIfUnique(eBroadcastBitProfileData,
4461 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004462}
4463
Kate Stoneb9c1b512016-09-06 20:57:50 +00004464void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4465 const StructuredDataPluginSP &plugin_sp) {
4466 BroadcastEvent(
4467 eBroadcastBitStructuredData,
4468 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004469}
4470
4471StructuredDataPluginSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004472Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4473 auto find_it = m_structured_data_plugin_map.find(type_name);
4474 if (find_it != m_structured_data_plugin_map.end())
4475 return find_it->second;
4476 else
4477 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004478}
4479
Kate Stoneb9c1b512016-09-06 20:57:50 +00004480size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Error &error) {
4481 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4482 if (m_profile_data.empty())
4483 return 0;
4484
4485 std::string &one_profile_data = m_profile_data.front();
4486 size_t bytes_available = one_profile_data.size();
4487 if (bytes_available > 0) {
4488 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4489 if (log)
4490 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4491 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4492 if (bytes_available > buf_size) {
4493 memcpy(buf, one_profile_data.c_str(), buf_size);
4494 one_profile_data.erase(0, buf_size);
4495 bytes_available = buf_size;
4496 } else {
4497 memcpy(buf, one_profile_data.c_str(), bytes_available);
4498 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004499 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004500 }
4501 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004502}
4503
Greg Clayton93e86192011-11-13 04:45:22 +00004504//------------------------------------------------------------------
4505// Process STDIO
4506//------------------------------------------------------------------
4507
Kate Stoneb9c1b512016-09-06 20:57:50 +00004508size_t Process::GetSTDOUT(char *buf, size_t buf_size, Error &error) {
4509 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4510 size_t bytes_available = m_stdout_data.size();
4511 if (bytes_available > 0) {
4512 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4513 if (log)
4514 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4515 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4516 if (bytes_available > buf_size) {
4517 memcpy(buf, m_stdout_data.c_str(), buf_size);
4518 m_stdout_data.erase(0, buf_size);
4519 bytes_available = buf_size;
4520 } else {
4521 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4522 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004523 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004524 }
4525 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004526}
4527
Kate Stoneb9c1b512016-09-06 20:57:50 +00004528size_t Process::GetSTDERR(char *buf, size_t buf_size, Error &error) {
4529 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4530 size_t bytes_available = m_stderr_data.size();
4531 if (bytes_available > 0) {
4532 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4533 if (log)
4534 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4535 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4536 if (bytes_available > buf_size) {
4537 memcpy(buf, m_stderr_data.c_str(), buf_size);
4538 m_stderr_data.erase(0, buf_size);
4539 bytes_available = buf_size;
4540 } else {
4541 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4542 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004543 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004544 }
4545 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004546}
4547
Kate Stoneb9c1b512016-09-06 20:57:50 +00004548void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4549 size_t src_len) {
4550 Process *process = (Process *)baton;
4551 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004552}
4553
Kate Stoneb9c1b512016-09-06 20:57:50 +00004554class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004555public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004556 IOHandlerProcessSTDIO(Process *process, int write_fd)
4557 : IOHandler(process->GetTarget().GetDebugger(),
4558 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004559 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004560 m_pipe.CreateNew(false);
4561 m_read_file.SetDescriptor(GetInputFD(), false);
4562 }
4563
4564 ~IOHandlerProcessSTDIO() override = default;
4565
4566 // Each IOHandler gets to run until it is done. It should read data
4567 // from the "in" and place output into "out" and "err and return
4568 // when done.
4569 void Run() override {
4570 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4571 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4572 SetIsDone(true);
4573 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004574 }
4575
Kate Stoneb9c1b512016-09-06 20:57:50 +00004576 SetIsDone(false);
4577 const int read_fd = m_read_file.GetDescriptor();
4578 TerminalState terminal_state;
4579 terminal_state.Save(read_fd, false);
4580 Terminal terminal(read_fd);
4581 terminal.SetCanonical(false);
4582 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004583// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004584#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004585 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4586 m_is_running = true;
4587 while (!GetIsDone()) {
4588 SelectHelper select_helper;
4589 select_helper.FDSetRead(read_fd);
4590 select_helper.FDSetRead(pipe_read_fd);
4591 Error error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004592
Kate Stoneb9c1b512016-09-06 20:57:50 +00004593 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004594 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004595 } else {
4596 char ch = 0;
4597 size_t n;
4598 if (select_helper.FDIsSetRead(read_fd)) {
4599 n = 1;
4600 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4601 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4602 SetIsDone(true);
4603 } else
4604 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004605 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004606 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4607 size_t bytes_read;
4608 // Consume the interrupt byte
4609 Error error = m_pipe.Read(&ch, 1, bytes_read);
4610 if (error.Success()) {
4611 switch (ch) {
4612 case 'q':
4613 SetIsDone(true);
4614 break;
4615 case 'i':
4616 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004617 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004618 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004619 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004620 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004621 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004622 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004623 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004624 m_is_running = false;
4625#endif
4626 terminal_state.Restore();
4627 }
4628
4629 void Cancel() override {
4630 SetIsDone(true);
4631 // Only write to our pipe to cancel if we are in
4632 // IOHandlerProcessSTDIO::Run().
4633 // We can end up with a python command that is being run from the command
4634 // interpreter:
4635 //
4636 // (lldb) step_process_thousands_of_times
4637 //
4638 // In this case the command interpreter will be in the middle of handling
4639 // the command and if the process pushes and pops the IOHandler thousands
4640 // of times, we can end up writing to m_pipe without ever consuming the
4641 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4642 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4643 if (m_is_running) {
4644 char ch = 'q'; // Send 'q' for quit
4645 size_t bytes_written = 0;
4646 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004647 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004648 }
4649
4650 bool Interrupt() override {
4651 // Do only things that are safe to do in an interrupt context (like in
4652 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4653 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4654 // that was written to the pipe and then call
4655 // m_process->SendAsyncInterrupt()
4656 // from a much safer location in code.
4657 if (m_active) {
4658 char ch = 'i'; // Send 'i' for interrupt
4659 size_t bytes_written = 0;
4660 Error result = m_pipe.Write(&ch, 1, bytes_written);
4661 return result.Success();
4662 } else {
4663 // This IOHandler might be pushed on the stack, but not being run
4664 // currently
4665 // so do the right thing if we aren't actively watching for STDIN by
4666 // sending
4667 // the interrupt to the process. Otherwise the write to the pipe above
4668 // would
4669 // do nothing. This can happen when the command interpreter is running and
4670 // gets a "expression ...". It will be on the IOHandler thread and sending
4671 // the input is complete to the delegate which will cause the expression
4672 // to
4673 // run, which will push the process IO handler, but not run it.
4674
4675 if (StateIsRunningState(m_process->GetState())) {
4676 m_process->SendAsyncInterrupt();
4677 return true;
4678 }
4679 }
4680 return false;
4681 }
4682
4683 void GotEOF() override {}
4684
Greg Clayton44d93782014-01-27 23:43:24 +00004685protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004686 Process *m_process;
4687 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4688 File m_write_file; // Write to this file (usually the master pty for getting
4689 // io to debuggee)
4690 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004691 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004692};
4693
Kate Stoneb9c1b512016-09-06 20:57:50 +00004694void Process::SetSTDIOFileDescriptor(int fd) {
4695 // First set up the Read Thread for reading/handling process I/O
4696
4697 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4698 new ConnectionFileDescriptor(fd, true));
4699
4700 if (conn_ap) {
4701 m_stdio_communication.SetConnection(conn_ap.release());
4702 if (m_stdio_communication.IsConnected()) {
4703 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4704 STDIOReadThreadBytesReceived, this);
4705 m_stdio_communication.StartReadThread();
4706
4707 // Now read thread is set up, set up input reader.
4708
4709 if (!m_process_input_reader)
4710 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004711 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004712 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004713}
4714
Kate Stoneb9c1b512016-09-06 20:57:50 +00004715bool Process::ProcessIOHandlerIsActive() {
4716 IOHandlerSP io_handler_sp(m_process_input_reader);
4717 if (io_handler_sp)
4718 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4719 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004720}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004721bool Process::PushProcessIOHandler() {
4722 IOHandlerSP io_handler_sp(m_process_input_reader);
4723 if (io_handler_sp) {
4724 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4725 if (log)
4726 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004727
Kate Stoneb9c1b512016-09-06 20:57:50 +00004728 io_handler_sp->SetIsDone(false);
4729 GetTarget().GetDebugger().PushIOHandler(io_handler_sp);
4730 return true;
4731 }
4732 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004733}
4734
Kate Stoneb9c1b512016-09-06 20:57:50 +00004735bool Process::PopProcessIOHandler() {
4736 IOHandlerSP io_handler_sp(m_process_input_reader);
4737 if (io_handler_sp)
4738 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4739 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004740}
4741
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004742// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004743void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004744
Kate Stoneb9c1b512016-09-06 20:57:50 +00004745void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004746
Kate Stoneb9c1b512016-09-06 20:57:50 +00004747namespace {
4748// RestorePlanState is used to record the "is private", "is master" and "okay to
4749// discard" fields of
4750// the plan we are running, and reset it on Clean or on destruction.
4751// It will only reset the state once, so you can call Clean and then monkey with
4752// the state and it
4753// won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004754
Kate Stoneb9c1b512016-09-06 20:57:50 +00004755class RestorePlanState {
4756public:
4757 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4758 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4759 if (m_thread_plan_sp) {
4760 m_private = m_thread_plan_sp->GetPrivate();
4761 m_is_master = m_thread_plan_sp->IsMasterPlan();
4762 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4763 }
4764 }
4765
4766 ~RestorePlanState() { Clean(); }
4767
4768 void Clean() {
4769 if (!m_already_reset && m_thread_plan_sp) {
4770 m_already_reset = true;
4771 m_thread_plan_sp->SetPrivate(m_private);
4772 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4773 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4774 }
4775 }
4776
4777private:
4778 lldb::ThreadPlanSP m_thread_plan_sp;
4779 bool m_already_reset;
4780 bool m_private;
4781 bool m_is_master;
4782 bool m_okay_to_discard;
4783};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004784} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004785
Pavel Labath2ce22162016-12-01 10:57:30 +00004786static microseconds
4787GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4788 const milliseconds default_one_thread_timeout(250);
4789
4790 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004791 if (!options.GetTimeout()) {
4792 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4793 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004794 }
4795
4796 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004797 if (options.GetOneThreadTimeout())
4798 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004799
4800 // Otherwise use half the total timeout, bounded by the
4801 // default_one_thread_timeout.
4802 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004803 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004804}
4805
4806static Timeout<std::micro>
4807GetExpressionTimeout(const EvaluateExpressionOptions &options,
4808 bool before_first_timeout) {
4809 // If we are going to run all threads the whole time, or if we are only
4810 // going to run one thread, we can just return the overall timeout.
4811 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004812 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004813
4814 if (before_first_timeout)
4815 return GetOneThreadExpressionTimeout(options);
4816
Pavel Labath43d35412016-12-06 11:24:51 +00004817 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004818 return llvm::None;
4819 else
Pavel Labath43d35412016-12-06 11:24:51 +00004820 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004821}
4822
Jim Ingham1624a2d2014-05-05 02:26:40 +00004823ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004824Process::RunThreadPlan(ExecutionContext &exe_ctx,
4825 lldb::ThreadPlanSP &thread_plan_sp,
4826 const EvaluateExpressionOptions &options,
4827 DiagnosticManager &diagnostic_manager) {
4828 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004829
Kate Stoneb9c1b512016-09-06 20:57:50 +00004830 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4831
4832 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004833 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004834 eDiagnosticSeverityError,
4835 "RunThreadPlan called with empty thread plan.");
4836 return eExpressionSetupError;
4837 }
4838
4839 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004840 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004841 eDiagnosticSeverityError,
4842 "RunThreadPlan called with an invalid thread plan.");
4843 return eExpressionSetupError;
4844 }
4845
4846 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004847 diagnostic_manager.PutString(eDiagnosticSeverityError,
4848 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004849 return eExpressionSetupError;
4850 }
4851
4852 Thread *thread = exe_ctx.GetThreadPtr();
4853 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004854 diagnostic_manager.PutString(eDiagnosticSeverityError,
4855 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004856 return eExpressionSetupError;
4857 }
4858
4859 // We need to change some of the thread plan attributes for the thread plan
4860 // runner. This will restore them
4861 // when we are done:
4862
4863 RestorePlanState thread_plan_restorer(thread_plan_sp);
4864
4865 // We rely on the thread plan we are running returning "PlanCompleted" if when
4866 // it successfully completes.
4867 // For that to be true the plan can't be private - since private plans
4868 // suppress themselves in the
4869 // GetCompletedPlan call.
4870
4871 thread_plan_sp->SetPrivate(false);
4872
4873 // The plans run with RunThreadPlan also need to be terminal master plans or
4874 // when they are done we will end
4875 // up asking the plan above us whether we should stop, which may give the
4876 // wrong answer.
4877
4878 thread_plan_sp->SetIsMasterPlan(true);
4879 thread_plan_sp->SetOkayToDiscard(false);
4880
4881 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004882 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004883 eDiagnosticSeverityError,
4884 "RunThreadPlan called while the private state was not stopped.");
4885 return eExpressionSetupError;
4886 }
4887
4888 // Save the thread & frame from the exe_ctx for restoration after we run
4889 const uint32_t thread_idx_id = thread->GetIndexID();
4890 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4891 if (!selected_frame_sp) {
4892 thread->SetSelectedFrame(nullptr);
4893 selected_frame_sp = thread->GetSelectedFrame();
4894 if (!selected_frame_sp) {
4895 diagnostic_manager.Printf(
4896 eDiagnosticSeverityError,
4897 "RunThreadPlan called without a selected frame on thread %d",
4898 thread_idx_id);
4899 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004900 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004901 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004902
Pavel Labath2ce22162016-12-01 10:57:30 +00004903 // Make sure the timeout values make sense. The one thread timeout needs to be
4904 // smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004905 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4906 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004907 diagnostic_manager.PutString(eDiagnosticSeverityError,
4908 "RunThreadPlan called with one thread "
4909 "timeout greater than total timeout");
4910 return eExpressionSetupError;
4911 }
4912
Kate Stoneb9c1b512016-09-06 20:57:50 +00004913 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004914
Kate Stoneb9c1b512016-09-06 20:57:50 +00004915 // N.B. Running the target may unset the currently selected thread and frame.
4916 // We don't want to do that either,
4917 // so we should arrange to reset them as well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004918
Kate Stoneb9c1b512016-09-06 20:57:50 +00004919 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004920
Kate Stoneb9c1b512016-09-06 20:57:50 +00004921 uint32_t selected_tid;
4922 StackID selected_stack_id;
4923 if (selected_thread_sp) {
4924 selected_tid = selected_thread_sp->GetIndexID();
4925 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4926 } else {
4927 selected_tid = LLDB_INVALID_THREAD_ID;
4928 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004929
Kate Stoneb9c1b512016-09-06 20:57:50 +00004930 HostThread backup_private_state_thread;
4931 lldb::StateType old_state = eStateInvalid;
4932 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004933
Kate Stoneb9c1b512016-09-06 20:57:50 +00004934 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4935 LIBLLDB_LOG_PROCESS));
4936 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4937 // Yikes, we are running on the private state thread! So we can't wait for
4938 // public events on this thread, since
4939 // we are the thread that is generating public events.
4940 // The simplest thing to do is to spin up a temporary thread to handle
4941 // private state thread events while
4942 // we are fielding public events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004943 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004944 log->Printf("Running thread plan on private state thread, spinning up "
4945 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004946
Kate Stoneb9c1b512016-09-06 20:57:50 +00004947 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004948
Kate Stoneb9c1b512016-09-06 20:57:50 +00004949 // One other bit of business: we want to run just this thread plan and
4950 // anything it pushes, and then stop,
4951 // returning control here.
4952 // But in the normal course of things, the plan above us on the stack would
4953 // be given a shot at the stop
4954 // event before deciding to stop, and we don't want that. So we insert a
4955 // "stopper" base plan on the stack
4956 // before the plan we want to run. Since base plans always stop and return
4957 // control to the user, that will
4958 // do just what we want.
4959 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4960 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4961 // Have to make sure our public state is stopped, since otherwise the
4962 // reporting logic below doesn't work correctly.
4963 old_state = m_public_state.GetValue();
4964 m_public_state.SetValueNoLock(eStateStopped);
4965
4966 // Now spin up the private state thread:
4967 StartPrivateStateThread(true);
4968 }
4969
4970 thread->QueueThreadPlan(
4971 thread_plan_sp, false); // This used to pass "true" does that make sense?
4972
4973 if (options.GetDebug()) {
4974 // In this case, we aren't actually going to run, we just want to stop right
4975 // away.
4976 // Flush this thread so we will refetch the stacks and show the correct
4977 // backtrace.
4978 // FIXME: To make this prettier we should invent some stop reason for this,
4979 // but that
4980 // is only cosmetic, and this functionality is only of use to lldb
4981 // developers who can
4982 // live with not pretty...
4983 thread->Flush();
4984 return eExpressionStoppedForDebug;
4985 }
4986
4987 ListenerSP listener_sp(
4988 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4989
4990 lldb::EventSP event_to_broadcast_sp;
4991
4992 {
4993 // This process event hijacker Hijacks the Public events and its destructor
4994 // makes sure that the process events get
4995 // restored on exit to the function.
4996 //
4997 // If the event needs to propagate beyond the hijacker (e.g., the process
4998 // exits during execution), then the event
4999 // is put into event_to_broadcast_sp for rebroadcasting.
5000
5001 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
5002
5003 if (log) {
5004 StreamString s;
5005 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5006 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5007 " to run thread plan \"%s\".",
5008 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00005009 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005010
5011 bool got_event;
5012 lldb::EventSP event_sp;
5013 lldb::StateType stop_state = lldb::eStateInvalid;
5014
5015 bool before_first_timeout = true; // This is set to false the first time
5016 // that we have to halt the target.
5017 bool do_resume = true;
5018 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005019
5020 // This is just for accounting:
5021 uint32_t num_resumes = 0;
5022
Kate Stoneb9c1b512016-09-06 20:57:50 +00005023 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00005024 // going to run one thread, then we don't need the first timeout. So we
5025 // pretend we are after the first timeout already.
5026 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00005027 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005028
Kate Stoneb9c1b512016-09-06 20:57:50 +00005029 if (log)
Pavel Labath2ce22162016-12-01 10:57:30 +00005030 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
5031 options.GetStopOthers(), options.GetTryAllThreads(),
5032 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005033
5034 // This isn't going to work if there are unfetched events on the queue.
5035 // Are there cases where we might want to run the remaining events here, and
5036 // then try to
5037 // call the function? That's probably being too tricky for our own good.
5038
5039 Event *other_events = listener_sp->PeekAtNextEvent();
5040 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00005041 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005042 eDiagnosticSeverityError,
5043 "RunThreadPlan called with pending events on the queue.");
5044 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00005045 }
5046
Kate Stoneb9c1b512016-09-06 20:57:50 +00005047 // We also need to make sure that the next event is delivered. We might be
5048 // calling a function as part of
5049 // a thread plan, in which case the last delivered event could be the
5050 // running event, and we don't want
5051 // event coalescing to cause us to lose OUR running event...
5052 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00005053
Kate Stoneb9c1b512016-09-06 20:57:50 +00005054// This while loop must exit out the bottom, there's cleanup that we need to do
5055// when we are done.
5056// So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00005057
Kate Stoneb9c1b512016-09-06 20:57:50 +00005058#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5059 // It's pretty much impossible to write test cases for things like:
5060 // One thread timeout expires, I go to halt, but the process already stopped
5061 // on the function call stop breakpoint. Turning on this define will make
5062 // us not
5063 // fetch the first event till after the halt. So if you run a quick
5064 // function, it will have
5065 // completed, and the completion event will be waiting, when you interrupt
5066 // for halt.
5067 // The expression evaluation should still succeed.
5068 bool miss_first_event = true;
5069#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00005070 while (true) {
5071 // We usually want to resume the process if we get to the top of the loop.
5072 // The only exception is if we get two running events with no intervening
5073 // stop, which can happen, we will just wait for then next stop event.
5074 if (log)
5075 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5076 "before_first_timeout: %i.",
5077 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00005078
Kate Stoneb9c1b512016-09-06 20:57:50 +00005079 if (do_resume || handle_running_event) {
5080 // Do the initial resume and wait for the running event before going
5081 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00005082
Kate Stoneb9c1b512016-09-06 20:57:50 +00005083 if (do_resume) {
5084 num_resumes++;
5085 Error resume_error = PrivateResume();
5086 if (!resume_error.Success()) {
5087 diagnostic_manager.Printf(
5088 eDiagnosticSeverityError,
5089 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5090 resume_error.AsCString());
5091 return_value = eExpressionSetupError;
5092 break;
5093 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005094 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005095
Pavel Labathd35031e12016-11-30 10:41:42 +00005096 got_event =
5097 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005098 if (!got_event) {
5099 if (log)
5100 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5101 "resume %" PRIu32 ", exiting.",
5102 num_resumes);
5103
5104 diagnostic_manager.Printf(eDiagnosticSeverityError,
5105 "didn't get any event after resume %" PRIu32
5106 ", exiting.",
5107 num_resumes);
5108 return_value = eExpressionSetupError;
5109 break;
5110 }
5111
5112 stop_state =
5113 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5114
5115 if (stop_state != eStateRunning) {
5116 bool restarted = false;
5117
5118 if (stop_state == eStateStopped) {
5119 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5120 event_sp.get());
5121 if (log)
5122 log->Printf(
5123 "Process::RunThreadPlan(): didn't get running event after "
5124 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5125 "handle_running_event: %i).",
5126 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5127 handle_running_event);
5128 }
5129
5130 if (restarted) {
5131 // This is probably an overabundance of caution, I don't think I
5132 // should ever get a stopped & restarted
5133 // event here. But if I do, the best thing is to Halt and then get
5134 // out of here.
5135 const bool clear_thread_plans = false;
5136 const bool use_run_lock = false;
5137 Halt(clear_thread_plans, use_run_lock);
5138 }
5139
5140 diagnostic_manager.Printf(
5141 eDiagnosticSeverityError,
5142 "didn't get running event after initial resume, got %s instead.",
5143 StateAsCString(stop_state));
5144 return_value = eExpressionSetupError;
5145 break;
5146 }
5147
5148 if (log)
5149 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5150 // We need to call the function synchronously, so spin waiting for it to
5151 // return.
5152 // If we get interrupted while executing, we're going to lose our
5153 // context, and
5154 // won't be able to gather the result at this point.
5155 // We set the timeout AFTER the resume, since the resume takes some time
5156 // and we
5157 // don't want to charge that to the timeout.
5158 } else {
5159 if (log)
5160 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5161 }
5162
Kate Stoneb9c1b512016-09-06 20:57:50 +00005163 do_resume = true;
5164 handle_running_event = true;
5165
5166 // Now wait for the process to stop again:
5167 event_sp.reset();
5168
Pavel Labath2ce22162016-12-01 10:57:30 +00005169 Timeout<std::micro> timeout =
5170 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005171 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005172 if (timeout) {
5173 auto now = system_clock::now();
5174 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
5175 "endpoint is %s",
5176 llvm::to_string(now).c_str(),
5177 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005178 } else {
5179 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005180 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005181 }
5182
5183#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5184 // See comment above...
5185 if (miss_first_event) {
5186 usleep(1000);
5187 miss_first_event = false;
5188 got_event = false;
5189 } else
5190#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005191 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005192
5193 if (got_event) {
5194 if (event_sp) {
5195 bool keep_going = false;
5196 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5197 const bool clear_thread_plans = false;
5198 const bool use_run_lock = false;
5199 Halt(clear_thread_plans, use_run_lock);
5200 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005201 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5202 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005203 if (log)
5204 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5205 "eBroadcastBitInterrupted, exiting.");
5206 break;
5207 } else {
5208 stop_state =
5209 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5210 if (log)
5211 log->Printf(
5212 "Process::RunThreadPlan(): in while loop, got event: %s.",
5213 StateAsCString(stop_state));
5214
5215 switch (stop_state) {
5216 case lldb::eStateStopped: {
5217 // We stopped, figure out what we are going to do now.
5218 ThreadSP thread_sp =
5219 GetThreadList().FindThreadByIndexID(thread_idx_id);
5220 if (!thread_sp) {
5221 // Ooh, our thread has vanished. Unlikely that this was
5222 // successful execution...
5223 if (log)
5224 log->Printf("Process::RunThreadPlan(): execution completed "
5225 "but our thread (index-id=%u) has vanished.",
5226 thread_idx_id);
5227 return_value = eExpressionInterrupted;
5228 } else {
5229 // If we were restarted, we just need to go back up to fetch
5230 // another event.
5231 if (Process::ProcessEventData::GetRestartedFromEvent(
5232 event_sp.get())) {
5233 if (log) {
5234 log->Printf("Process::RunThreadPlan(): Got a stop and "
5235 "restart, so we'll continue waiting.");
5236 }
5237 keep_going = true;
5238 do_resume = false;
5239 handle_running_event = true;
5240 } else {
Boris Ulasevich86aaa8a2017-02-15 11:42:47 +00005241 ThreadPlanSP plan = thread->GetCompletedPlan();
5242 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005243
Kate Stoneb9c1b512016-09-06 20:57:50 +00005244 if (log)
5245 log->PutCString("Process::RunThreadPlan(): execution "
5246 "completed successfully.");
5247
5248 // Restore the plan state so it will get reported as
5249 // intended when we are done.
5250 thread_plan_restorer.Clean();
5251
5252 return_value = eExpressionCompleted;
5253 } else {
Boris Ulasevich86aaa8a2017-02-15 11:42:47 +00005254 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005255 // Something restarted the target, so just wait for it to
5256 // stop for real.
Boris Ulasevich86aaa8a2017-02-15 11:42:47 +00005257 if (stop_info_sp &&
5258 stop_info_sp->GetStopReason() == eStopReasonBreakpoint) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005259 if (log)
5260 log->Printf("Process::RunThreadPlan() stopped for "
5261 "breakpoint: %s.",
5262 stop_info_sp->GetDescription());
5263 return_value = eExpressionHitBreakpoint;
5264 if (!options.DoesIgnoreBreakpoints()) {
5265 // Restore the plan state and then force Private to
5266 // false. We are
5267 // going to stop because of this plan so we need it to
5268 // become a public
5269 // plan or it won't report correctly when we continue to
5270 // its termination
5271 // later on.
5272 thread_plan_restorer.Clean();
5273 if (thread_plan_sp)
5274 thread_plan_sp->SetPrivate(false);
5275 event_to_broadcast_sp = event_sp;
5276 }
5277 } else {
5278 if (log)
5279 log->PutCString("Process::RunThreadPlan(): thread plan "
5280 "didn't successfully complete.");
5281 if (!options.DoesUnwindOnError())
5282 event_to_broadcast_sp = event_sp;
5283 return_value = eExpressionInterrupted;
5284 }
5285 }
5286 }
5287 }
5288 } break;
5289
5290 case lldb::eStateRunning:
5291 // This shouldn't really happen, but sometimes we do get two
5292 // running events without an
5293 // intervening stop, and in that case we should just go back to
5294 // waiting for the stop.
5295 do_resume = false;
5296 keep_going = true;
5297 handle_running_event = false;
5298 break;
5299
5300 default:
5301 if (log)
5302 log->Printf("Process::RunThreadPlan(): execution stopped with "
5303 "unexpected state: %s.",
5304 StateAsCString(stop_state));
5305
5306 if (stop_state == eStateExited)
5307 event_to_broadcast_sp = event_sp;
5308
Zachary Turnere2411fa2016-11-12 19:12:56 +00005309 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005310 eDiagnosticSeverityError,
5311 "execution stopped with unexpected state.");
5312 return_value = eExpressionInterrupted;
5313 break;
5314 }
5315 }
5316
5317 if (keep_going)
5318 continue;
5319 else
5320 break;
5321 } else {
5322 if (log)
5323 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5324 "the event pointer was null. How odd...");
5325 return_value = eExpressionInterrupted;
5326 break;
5327 }
5328 } else {
5329 // If we didn't get an event that means we've timed out...
5330 // We will interrupt the process here. Depending on what we were asked
5331 // to do we will
5332 // either exit, or try with all threads running for the same timeout.
5333
5334 if (log) {
5335 if (options.GetTryAllThreads()) {
5336 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005337 LLDB_LOG(log,
5338 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005339 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005340 LLDB_LOG(log, "Restarting function with all threads enabled and "
5341 "timeout: {0} timed out, abandoning execution.",
5342 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005343 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005344 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5345 "abandoning execution.",
5346 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005347 }
5348
5349 // It is possible that between the time we issued the Halt, and we get
5350 // around to calling Halt the target
5351 // could have stopped. That's fine, Halt will figure that out and send
5352 // the appropriate Stopped event.
5353 // BUT it is also possible that we stopped & restarted (e.g. hit a
5354 // signal with "stop" set to false.) In
5355 // that case, we'll get the stopped & restarted event, and we should go
5356 // back to waiting for the Halt's
5357 // stopped event. That's what this while loop does.
5358
5359 bool back_to_top = true;
5360 uint32_t try_halt_again = 0;
5361 bool do_halt = true;
5362 const uint32_t num_retries = 5;
5363 while (try_halt_again < num_retries) {
5364 Error halt_error;
5365 if (do_halt) {
5366 if (log)
5367 log->Printf("Process::RunThreadPlan(): Running Halt.");
5368 const bool clear_thread_plans = false;
5369 const bool use_run_lock = false;
5370 Halt(clear_thread_plans, use_run_lock);
5371 }
5372 if (halt_error.Success()) {
5373 if (log)
5374 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5375
Pavel Labathd35031e12016-11-30 10:41:42 +00005376 got_event =
5377 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005378
5379 if (got_event) {
5380 stop_state =
5381 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5382 if (log) {
5383 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5384 StateAsCString(stop_state));
5385 if (stop_state == lldb::eStateStopped &&
5386 Process::ProcessEventData::GetInterruptedFromEvent(
5387 event_sp.get()))
5388 log->PutCString(" Event was the Halt interruption event.");
5389 }
5390
5391 if (stop_state == lldb::eStateStopped) {
5392 // Between the time we initiated the Halt and the time we
5393 // delivered it, the process could have
5394 // already finished its job. Check that here:
5395
5396 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5397 if (log)
5398 log->PutCString("Process::RunThreadPlan(): Even though we "
5399 "timed out, the call plan was done. "
5400 "Exiting wait loop.");
5401 return_value = eExpressionCompleted;
5402 back_to_top = false;
5403 break;
5404 }
5405
5406 if (Process::ProcessEventData::GetRestartedFromEvent(
5407 event_sp.get())) {
5408 if (log)
5409 log->PutCString("Process::RunThreadPlan(): Went to halt "
5410 "but got a restarted event, there must be "
5411 "an un-restarted stopped event so try "
5412 "again... "
5413 "Exiting wait loop.");
5414 try_halt_again++;
5415 do_halt = false;
5416 continue;
5417 }
5418
5419 if (!options.GetTryAllThreads()) {
5420 if (log)
5421 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5422 "was false, we stopped so now we're "
5423 "quitting.");
5424 return_value = eExpressionInterrupted;
5425 back_to_top = false;
5426 break;
5427 }
5428
5429 if (before_first_timeout) {
5430 // Set all the other threads to run, and return to the top of
5431 // the loop, which will continue;
5432 before_first_timeout = false;
5433 thread_plan_sp->SetStopOthers(false);
5434 if (log)
5435 log->PutCString(
5436 "Process::RunThreadPlan(): about to resume.");
5437
5438 back_to_top = true;
5439 break;
5440 } else {
5441 // Running all threads failed, so return Interrupted.
5442 if (log)
5443 log->PutCString("Process::RunThreadPlan(): running all "
5444 "threads timed out.");
5445 return_value = eExpressionInterrupted;
5446 back_to_top = false;
5447 break;
5448 }
5449 }
5450 } else {
5451 if (log)
5452 log->PutCString("Process::RunThreadPlan(): halt said it "
5453 "succeeded, but I got no event. "
5454 "I'm getting out of here passing Interrupted.");
5455 return_value = eExpressionInterrupted;
5456 back_to_top = false;
5457 break;
5458 }
5459 } else {
5460 try_halt_again++;
5461 continue;
5462 }
5463 }
5464
5465 if (!back_to_top || try_halt_again > num_retries)
5466 break;
5467 else
5468 continue;
5469 }
5470 } // END WAIT LOOP
5471
5472 // If we had to start up a temporary private state thread to run this thread
5473 // plan, shut it down now.
5474 if (backup_private_state_thread.IsJoinable()) {
5475 StopPrivateStateThread();
5476 Error error;
5477 m_private_state_thread = backup_private_state_thread;
5478 if (stopper_base_plan_sp) {
5479 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5480 }
5481 if (old_state != eStateInvalid)
5482 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005483 }
5484
Kate Stoneb9c1b512016-09-06 20:57:50 +00005485 if (return_value != eExpressionCompleted && log) {
5486 // Print a backtrace into the log so we can figure out where we are:
5487 StreamString s;
5488 s.PutCString("Thread state after unsuccessful completion: \n");
5489 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005490 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005491 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005492 // Restore the thread state if we are going to discard the plan execution.
5493 // There are three cases where this
5494 // could happen:
5495 // 1) The execution successfully completed
5496 // 2) We hit a breakpoint, and ignore_breakpoints was true
5497 // 3) We got some other error, and discard_on_error was true
5498 bool should_unwind = (return_value == eExpressionInterrupted &&
5499 options.DoesUnwindOnError()) ||
5500 (return_value == eExpressionHitBreakpoint &&
5501 options.DoesIgnoreBreakpoints());
5502
5503 if (return_value == eExpressionCompleted || should_unwind) {
5504 thread_plan_sp->RestoreThreadState();
5505 }
5506
5507 // Now do some processing on the results of the run:
5508 if (return_value == eExpressionInterrupted ||
5509 return_value == eExpressionHitBreakpoint) {
5510 if (log) {
5511 StreamString s;
5512 if (event_sp)
5513 event_sp->Dump(&s);
5514 else {
5515 log->PutCString("Process::RunThreadPlan(): Stop event that "
5516 "interrupted us is NULL.");
5517 }
5518
5519 StreamString ts;
5520
5521 const char *event_explanation = nullptr;
5522
5523 do {
5524 if (!event_sp) {
5525 event_explanation = "<no event>";
5526 break;
5527 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5528 event_explanation = "<user interrupt>";
5529 break;
5530 } else {
5531 const Process::ProcessEventData *event_data =
5532 Process::ProcessEventData::GetEventDataFromEvent(
5533 event_sp.get());
5534
5535 if (!event_data) {
5536 event_explanation = "<no event data>";
5537 break;
5538 }
5539
5540 Process *process = event_data->GetProcessSP().get();
5541
5542 if (!process) {
5543 event_explanation = "<no process>";
5544 break;
5545 }
5546
5547 ThreadList &thread_list = process->GetThreadList();
5548
5549 uint32_t num_threads = thread_list.GetSize();
5550 uint32_t thread_index;
5551
5552 ts.Printf("<%u threads> ", num_threads);
5553
5554 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5555 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5556
5557 if (!thread) {
5558 ts.Printf("<?> ");
5559 continue;
5560 }
5561
5562 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5563 RegisterContext *register_context =
5564 thread->GetRegisterContext().get();
5565
5566 if (register_context)
5567 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5568 else
5569 ts.Printf("[ip unknown] ");
5570
5571 // Show the private stop info here, the public stop info will be
5572 // from the last natural stop.
5573 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5574 if (stop_info_sp) {
5575 const char *stop_desc = stop_info_sp->GetDescription();
5576 if (stop_desc)
5577 ts.PutCString(stop_desc);
5578 }
5579 ts.Printf(">");
5580 }
5581
5582 event_explanation = ts.GetData();
5583 }
5584 } while (0);
5585
5586 if (event_explanation)
5587 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5588 s.GetData(), event_explanation);
5589 else
5590 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5591 s.GetData());
5592 }
5593
5594 if (should_unwind) {
5595 if (log)
5596 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5597 "discarding thread plans up to %p.",
5598 static_cast<void *>(thread_plan_sp.get()));
5599 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5600 } else {
5601 if (log)
5602 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5603 "plan: %p not discarding.",
5604 static_cast<void *>(thread_plan_sp.get()));
5605 }
5606 } else if (return_value == eExpressionSetupError) {
5607 if (log)
5608 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5609
5610 if (options.DoesUnwindOnError()) {
5611 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5612 }
5613 } else {
5614 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5615 if (log)
5616 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5617 return_value = eExpressionCompleted;
5618 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5619 if (log)
5620 log->PutCString(
5621 "Process::RunThreadPlan(): thread plan was discarded");
5622 return_value = eExpressionDiscarded;
5623 } else {
5624 if (log)
5625 log->PutCString(
5626 "Process::RunThreadPlan(): thread plan stopped in mid course");
5627 if (options.DoesUnwindOnError() && thread_plan_sp) {
5628 if (log)
5629 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5630 "'cause unwind_on_error is set.");
5631 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5632 }
5633 }
5634 }
5635
5636 // Thread we ran the function in may have gone away because we ran the
5637 // target
5638 // Check that it's still there, and if it is put it back in the context.
5639 // Also restore the
5640 // frame in the context if it is still present.
5641 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5642 if (thread) {
5643 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5644 }
5645
5646 // Also restore the current process'es selected frame & thread, since this
5647 // function calling may
5648 // be done behind the user's back.
5649
5650 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5651 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5652 selected_stack_id.IsValid()) {
5653 // We were able to restore the selected thread, now restore the frame:
5654 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5655 StackFrameSP old_frame_sp =
5656 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5657 selected_stack_id);
5658 if (old_frame_sp)
5659 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5660 old_frame_sp.get());
5661 }
5662 }
5663 }
5664
5665 // If the process exited during the run of the thread plan, notify everyone.
5666
5667 if (event_to_broadcast_sp) {
5668 if (log)
5669 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5670 BroadcastEvent(event_to_broadcast_sp);
5671 }
5672
5673 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005674}
5675
Kate Stoneb9c1b512016-09-06 20:57:50 +00005676const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5677 const char *result_name;
5678
5679 switch (result) {
5680 case eExpressionCompleted:
5681 result_name = "eExpressionCompleted";
5682 break;
5683 case eExpressionDiscarded:
5684 result_name = "eExpressionDiscarded";
5685 break;
5686 case eExpressionInterrupted:
5687 result_name = "eExpressionInterrupted";
5688 break;
5689 case eExpressionHitBreakpoint:
5690 result_name = "eExpressionHitBreakpoint";
5691 break;
5692 case eExpressionSetupError:
5693 result_name = "eExpressionSetupError";
5694 break;
5695 case eExpressionParseError:
5696 result_name = "eExpressionParseError";
5697 break;
5698 case eExpressionResultUnavailable:
5699 result_name = "eExpressionResultUnavailable";
5700 break;
5701 case eExpressionTimedOut:
5702 result_name = "eExpressionTimedOut";
5703 break;
5704 case eExpressionStoppedForDebug:
5705 result_name = "eExpressionStoppedForDebug";
5706 break;
5707 }
5708 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005709}
5710
Kate Stoneb9c1b512016-09-06 20:57:50 +00005711void Process::GetStatus(Stream &strm) {
5712 const StateType state = GetState();
5713 if (StateIsStoppedState(state, false)) {
5714 if (state == eStateExited) {
5715 int exit_status = GetExitStatus();
5716 const char *exit_description = GetExitDescription();
5717 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5718 GetID(), exit_status, exit_status,
5719 exit_description ? exit_description : "");
5720 } else {
5721 if (state == eStateConnected)
5722 strm.Printf("Connected to remote target.\n");
5723 else
5724 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5725 }
5726 } else {
5727 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5728 }
Pavel Labatha933d512016-04-05 13:07:16 +00005729}
5730
Kate Stoneb9c1b512016-09-06 20:57:50 +00005731size_t Process::GetThreadStatus(Stream &strm,
5732 bool only_threads_with_stop_reason,
5733 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005734 uint32_t num_frames_with_source,
5735 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005736 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005737
Kate Stoneb9c1b512016-09-06 20:57:50 +00005738 // You can't hold the thread list lock while calling Thread::GetStatus. That
5739 // very well might run code (e.g. if we need it
5740 // to get return values or arguments.) For that to work the process has to be
5741 // able to acquire it. So instead copy the thread
5742 // ID's, and look them up one by one:
5743
5744 uint32_t num_threads;
5745 std::vector<lldb::tid_t> thread_id_array;
5746 // Scope for thread list locker;
5747 {
5748 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5749 ThreadList &curr_thread_list = GetThreadList();
5750 num_threads = curr_thread_list.GetSize();
5751 uint32_t idx;
5752 thread_id_array.resize(num_threads);
5753 for (idx = 0; idx < num_threads; ++idx)
5754 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5755 }
5756
5757 for (uint32_t i = 0; i < num_threads; i++) {
5758 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5759 if (thread_sp) {
5760 if (only_threads_with_stop_reason) {
5761 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5762 if (!stop_info_sp || !stop_info_sp->IsValid())
5763 continue;
5764 }
5765 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005766 num_frames_with_source,
5767 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005768 ++num_thread_infos_dumped;
5769 } else {
5770 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5771 if (log)
5772 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5773 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005774 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005775 }
5776 return num_thread_infos_dumped;
5777}
5778
5779void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5780 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5781}
5782
5783bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5784 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5785 region.GetByteSize());
5786}
5787
5788void Process::AddPreResumeAction(PreResumeActionCallback callback,
5789 void *baton) {
5790 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5791}
5792
5793bool Process::RunPreResumeActions() {
5794 bool result = true;
5795 while (!m_pre_resume_actions.empty()) {
5796 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5797 m_pre_resume_actions.pop_back();
5798 bool this_result = action.callback(action.baton);
5799 if (result)
5800 result = this_result;
5801 }
5802 return result;
5803}
5804
5805void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5806
Jim Inghamffd91752016-10-20 22:50:00 +00005807void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5808{
5809 PreResumeCallbackAndBaton element(callback, baton);
5810 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5811 if (found_iter != m_pre_resume_actions.end())
5812 {
5813 m_pre_resume_actions.erase(found_iter);
5814 }
5815}
5816
Kate Stoneb9c1b512016-09-06 20:57:50 +00005817ProcessRunLock &Process::GetRunLock() {
5818 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5819 return m_private_run_lock;
5820 else
5821 return m_public_run_lock;
5822}
5823
5824void Process::Flush() {
5825 m_thread_list.Flush();
5826 m_extended_thread_list.Flush();
5827 m_extended_thread_stop_id = 0;
5828 m_queue_list.Clear();
5829 m_queue_list_stop_id = 0;
5830}
5831
5832void Process::DidExec() {
5833 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5834 if (log)
5835 log->Printf("Process::%s()", __FUNCTION__);
5836
5837 Target &target = GetTarget();
5838 target.CleanupProcess();
5839 target.ClearModules(false);
5840 m_dynamic_checkers_ap.reset();
5841 m_abi_sp.reset();
5842 m_system_runtime_ap.reset();
5843 m_os_ap.reset();
5844 m_dyld_ap.reset();
5845 m_jit_loaders_ap.reset();
5846 m_image_tokens.clear();
5847 m_allocated_memory_cache.Clear();
5848 m_language_runtimes.clear();
5849 m_instrumentation_runtimes.clear();
5850 m_thread_list.DiscardThreadPlans();
5851 m_memory_cache.Clear(true);
5852 m_stop_info_override_callback = nullptr;
5853 DoDidExec();
5854 CompleteAttach();
5855 // Flush the process (threads and all stack frames) after running
5856 // CompleteAttach()
5857 // in case the dynamic loader loaded things in new locations.
5858 Flush();
5859
5860 // After we figure out what was loaded/unloaded in CompleteAttach,
5861 // we need to let the target know so it can do any cleanup it needs to.
5862 target.DidExec();
5863}
5864
5865addr_t Process::ResolveIndirectFunction(const Address *address, Error &error) {
5866 if (address == nullptr) {
5867 error.SetErrorString("Invalid address argument");
5868 return LLDB_INVALID_ADDRESS;
5869 }
5870
5871 addr_t function_addr = LLDB_INVALID_ADDRESS;
5872
5873 addr_t addr = address->GetLoadAddress(&GetTarget());
5874 std::map<addr_t, addr_t>::const_iterator iter =
5875 m_resolved_indirect_addresses.find(addr);
5876 if (iter != m_resolved_indirect_addresses.end()) {
5877 function_addr = (*iter).second;
5878 } else {
5879 if (!InferiorCall(this, address, function_addr)) {
5880 Symbol *symbol = address->CalculateSymbolContextSymbol();
5881 error.SetErrorStringWithFormat(
5882 "Unable to call resolver for indirect function %s",
5883 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5884 function_addr = LLDB_INVALID_ADDRESS;
5885 } else {
5886 m_resolved_indirect_addresses.insert(
5887 std::pair<addr_t, addr_t>(addr, function_addr));
5888 }
5889 }
5890 return function_addr;
5891}
5892
5893void Process::ModulesDidLoad(ModuleList &module_list) {
5894 SystemRuntime *sys_runtime = GetSystemRuntime();
5895 if (sys_runtime) {
5896 sys_runtime->ModulesDidLoad(module_list);
5897 }
5898
5899 GetJITLoaders().ModulesDidLoad(module_list);
5900
5901 // Give runtimes a chance to be created.
5902 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5903 m_instrumentation_runtimes);
5904
5905 // Tell runtimes about new modules.
5906 for (auto pos = m_instrumentation_runtimes.begin();
5907 pos != m_instrumentation_runtimes.end(); ++pos) {
5908 InstrumentationRuntimeSP runtime = pos->second;
5909 runtime->ModulesDidLoad(module_list);
5910 }
5911
5912 // Let any language runtimes we have already created know
5913 // about the modules that loaded.
5914
5915 // Iterate over a copy of this language runtime list in case
5916 // the language runtime ModulesDidLoad somehow causes the language
5917 // riuntime to be unloaded.
5918 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5919 for (const auto &pair : language_runtimes) {
5920 // We must check language_runtime_sp to make sure it is not
5921 // nullptr as we might cache the fact that we didn't have a
5922 // language runtime for a language.
5923 LanguageRuntimeSP language_runtime_sp = pair.second;
5924 if (language_runtime_sp)
5925 language_runtime_sp->ModulesDidLoad(module_list);
5926 }
5927
5928 // If we don't have an operating system plug-in, try to load one since
5929 // loading shared libraries might cause a new one to try and load
5930 if (!m_os_ap)
5931 LoadOperatingSystemPlugin(false);
5932
5933 // Give structured-data plugins a chance to see the modified modules.
5934 for (auto pair : m_structured_data_plugin_map) {
5935 if (pair.second)
5936 pair.second->ModulesDidLoad(*this, module_list);
5937 }
5938}
5939
5940void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5941 const char *fmt, ...) {
5942 bool print_warning = true;
5943
5944 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5945 if (!stream_sp)
5946 return;
5947 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5948 return;
5949 }
5950
5951 if (repeat_key != nullptr) {
5952 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5953 if (it == m_warnings_issued.end()) {
5954 m_warnings_issued[warning_type] = WarningsPointerSet();
5955 m_warnings_issued[warning_type].insert(repeat_key);
5956 } else {
5957 if (it->second.find(repeat_key) != it->second.end()) {
5958 print_warning = false;
5959 } else {
5960 it->second.insert(repeat_key);
5961 }
5962 }
5963 }
5964
5965 if (print_warning) {
5966 va_list args;
5967 va_start(args, fmt);
5968 stream_sp->PrintfVarArg(fmt, args);
5969 va_end(args);
5970 }
5971}
5972
5973void Process::PrintWarningOptimization(const SymbolContext &sc) {
5974 if (GetWarningsOptimization() && sc.module_sp &&
5975 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5976 sc.function->GetIsOptimized()) {
5977 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5978 "%s was compiled with optimization - stepping may behave "
5979 "oddly; variables may not be available.\n",
5980 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5981 }
5982}
5983
5984bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5985 info.Clear();
5986
5987 PlatformSP platform_sp = GetTarget().GetPlatform();
5988 if (!platform_sp)
5989 return false;
5990
5991 return platform_sp->GetProcessInfo(GetID(), info);
5992}
5993
5994ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5995 ThreadCollectionSP threads;
5996
5997 const MemoryHistorySP &memory_history =
5998 MemoryHistory::FindPlugin(shared_from_this());
5999
6000 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00006001 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006002 }
6003
6004 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6005
6006 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00006007}
Kuba Brecka63927542014-10-11 01:59:32 +00006008
6009InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00006010Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
6011 InstrumentationRuntimeCollection::iterator pos;
6012 pos = m_instrumentation_runtimes.find(type);
6013 if (pos == m_instrumentation_runtimes.end()) {
6014 return InstrumentationRuntimeSP();
6015 } else
6016 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00006017}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006018
Kate Stoneb9c1b512016-09-06 20:57:50 +00006019bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6020 const ArchSpec &arch, ModuleSpec &module_spec) {
6021 module_spec.Clear();
6022 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006023}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006024
Kate Stoneb9c1b512016-09-06 20:57:50 +00006025size_t Process::AddImageToken(lldb::addr_t image_ptr) {
6026 m_image_tokens.push_back(image_ptr);
6027 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006028}
6029
Kate Stoneb9c1b512016-09-06 20:57:50 +00006030lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
6031 if (token < m_image_tokens.size())
6032 return m_image_tokens[token];
6033 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006034}
6035
Kate Stoneb9c1b512016-09-06 20:57:50 +00006036void Process::ResetImageToken(size_t token) {
6037 if (token < m_image_tokens.size())
6038 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00006039}
Jason Molendafd4cea52016-01-08 21:40:11 +00006040
6041Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00006042Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
6043 AddressRange range_bounds) {
6044 Target &target = GetTarget();
6045 DisassemblerSP disassembler_sp;
6046 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006047
Kate Stoneb9c1b512016-09-06 20:57:50 +00006048 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006049
Kate Stoneb9c1b512016-09-06 20:57:50 +00006050 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00006051 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006052 if (!default_stop_addr.IsValid())
6053 return retval;
6054
6055 ExecutionContext exe_ctx(this);
6056 const char *plugin_name = nullptr;
6057 const char *flavor = nullptr;
6058 const bool prefer_file_cache = true;
6059 disassembler_sp = Disassembler::DisassembleRange(
6060 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6061 prefer_file_cache);
6062 if (disassembler_sp)
6063 insn_list = &disassembler_sp->GetInstructionList();
6064
6065 if (insn_list == nullptr) {
6066 return retval;
6067 }
6068
6069 size_t insn_offset =
6070 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6071 if (insn_offset == UINT32_MAX) {
6072 return retval;
6073 }
6074
6075 uint32_t branch_index =
6076 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6077 if (branch_index == UINT32_MAX) {
6078 return retval;
6079 }
6080
6081 if (branch_index > insn_offset) {
6082 Address next_branch_insn_address =
6083 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6084 if (next_branch_insn_address.IsValid() &&
6085 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6086 retval = next_branch_insn_address;
6087 }
6088 }
6089
6090 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00006091}
Howard Hellyerad007562016-07-07 08:21:28 +00006092
Kate Stoneb9c1b512016-09-06 20:57:50 +00006093Error Process::GetMemoryRegions(
6094 std::vector<lldb::MemoryRegionInfoSP> &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00006095
Kate Stoneb9c1b512016-09-06 20:57:50 +00006096 Error error;
Howard Hellyerad007562016-07-07 08:21:28 +00006097
Kate Stoneb9c1b512016-09-06 20:57:50 +00006098 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00006099
Kate Stoneb9c1b512016-09-06 20:57:50 +00006100 region_list.clear();
6101 do {
6102 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6103 error = GetMemoryRegionInfo(range_end, *region_info);
6104 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6105 if (error.Fail()) {
6106 region_list.clear();
6107 break;
Todd Fiala75930012016-08-19 04:21:48 +00006108 }
6109
Kate Stoneb9c1b512016-09-06 20:57:50 +00006110 range_end = region_info->GetRange().GetRangeEnd();
6111 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6112 region_list.push_back(region_info);
6113 }
6114 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00006115
Kate Stoneb9c1b512016-09-06 20:57:50 +00006116 return error;
6117}
6118
6119Error Process::ConfigureStructuredData(
6120 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
6121 // If you get this, the Process-derived class needs to implement a method
6122 // to enable an already-reported asynchronous structured data feature.
6123 // See ProcessGDBRemote for an example implementation over gdb-remote.
6124 return Error("unimplemented");
6125}
6126
6127void Process::MapSupportedStructuredDataPlugins(
6128 const StructuredData::Array &supported_type_names) {
6129 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6130
6131 // Bail out early if there are no type names to map.
6132 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00006133 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006134 log->Printf("Process::%s(): no structured data types supported",
6135 __FUNCTION__);
6136 return;
6137 }
Todd Fiala75930012016-08-19 04:21:48 +00006138
Kate Stoneb9c1b512016-09-06 20:57:50 +00006139 // Convert StructuredData type names to ConstString instances.
6140 std::set<ConstString> const_type_names;
6141
6142 if (log)
6143 log->Printf("Process::%s(): the process supports the following async "
6144 "structured data types:",
6145 __FUNCTION__);
6146
6147 supported_type_names.ForEach(
6148 [&const_type_names, &log](StructuredData::Object *object) {
6149 if (!object) {
6150 // Invalid - shouldn't be null objects in the array.
6151 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006152 }
6153
6154 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006155 if (!type_name) {
6156 // Invalid format - all type names should be strings.
6157 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006158 }
6159
6160 const_type_names.insert(ConstString(type_name->GetValue()));
6161 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006162 log->Printf("- %s", type_name->GetValue().c_str());
Todd Fiala75930012016-08-19 04:21:48 +00006163 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006164 });
Todd Fiala75930012016-08-19 04:21:48 +00006165
Kate Stoneb9c1b512016-09-06 20:57:50 +00006166 // For each StructuredDataPlugin, if the plugin handles any of the
6167 // types in the supported_type_names, map that type name to that plugin.
6168 uint32_t plugin_index = 0;
6169 for (auto create_instance =
6170 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6171 plugin_index);
6172 create_instance && !const_type_names.empty(); ++plugin_index) {
6173 // Create the plugin.
6174 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6175 if (!plugin_sp) {
6176 // This plugin doesn't think it can work with the process.
6177 // Move on to the next.
6178 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006179 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006180
6181 // For any of the remaining type names, map any that this plugin
6182 // supports.
6183 std::vector<ConstString> names_to_remove;
6184 for (auto &type_name : const_type_names) {
6185 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6186 m_structured_data_plugin_map.insert(
6187 std::make_pair(type_name, plugin_sp));
6188 names_to_remove.push_back(type_name);
6189 if (log)
6190 log->Printf("Process::%s(): using plugin %s for type name "
6191 "%s",
6192 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6193 type_name.GetCString());
6194 }
6195 }
6196
6197 // Remove the type names that were consumed by this plugin.
6198 for (auto &type_name : names_to_remove)
6199 const_type_names.erase(type_name);
6200 }
Todd Fiala75930012016-08-19 04:21:48 +00006201}
6202
Kate Stoneb9c1b512016-09-06 20:57:50 +00006203bool Process::RouteAsyncStructuredData(
6204 const StructuredData::ObjectSP object_sp) {
6205 // Nothing to do if there's no data.
6206 if (!object_sp)
6207 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006208
Kate Stoneb9c1b512016-09-06 20:57:50 +00006209 // The contract is this must be a dictionary, so we can look up the
6210 // routing key via the top-level 'type' string value within the dictionary.
6211 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6212 if (!dictionary)
6213 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006214
Kate Stoneb9c1b512016-09-06 20:57:50 +00006215 // Grab the async structured type name (i.e. the feature/plugin name).
6216 ConstString type_name;
6217 if (!dictionary->GetValueForKeyAsString("type", type_name))
6218 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006219
Kate Stoneb9c1b512016-09-06 20:57:50 +00006220 // Check if there's a plugin registered for this type name.
6221 auto find_it = m_structured_data_plugin_map.find(type_name);
6222 if (find_it == m_structured_data_plugin_map.end()) {
6223 // We don't have a mapping for this structured data type.
6224 return false;
6225 }
Todd Fiala75930012016-08-19 04:21:48 +00006226
Kate Stoneb9c1b512016-09-06 20:57:50 +00006227 // Route the structured data to the plugin.
6228 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6229 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006230}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006231
6232Error Process::UpdateAutomaticSignalFiltering() {
6233 // Default implementation does nothign.
6234 // No automatic signal filtering to speak of.
6235 return Error();
6236}